Children's day teaches you to do a C# picture matching game

Posted by thoand on Thu, 03 Feb 2022 05:47:08 +0100

First of all, I wish programmers a happy children's Day (* ^ ▽ ^ *)

Game learning is useless. Take it home and coax the children

OK, don't talk much, go straight to talent! EG Emon, EG Emon, EG Emon, EG Emon
(there is a link to the finished game at the end of the article. My favorite little partner has three links with one button)

1. Effect display

(show only a part)

Help rule

I'm stupid. I can only pass the customs examination (this may be the reason why I learn to do plug-ins. Ha ha, ha ha, don't go away. There are three waves in a row. The plug-in articles are continuously updated, and there are Windows hacker technology articles in the later stage [PS: this is the exclusive right of C + + bloggers])!

Cough, back to the point, let's talk about game design.

2. Game design

2.1. Interface design

First of all, don't panic when you see the gorgeous interface. Hahaha, background knowledge is just a picture, which is harmless.

Of course, the game help is also the background picture, but the words are also part of the picture

Then add a menu bar to him, simply add a start game and exit

Then create 16 pictureboxes to display 16 small pictures

Then there are three labels, which are used to display the information in the process of the game


2.2. logic design

Before writing logic, we need to establish various variables to be used in the game

// One dimensional array, corresponding to each picture box on the form, stores the picture index corresponding to each picture box
int[] pictureIds;
int firstIndex;      // Record the first picture box clicked
int secondIndex;     // Record the matched picture box clicked
int firstPictureId;  // The picture index displayed in the first picture box in the has been clicked  
int secondPictureId; // The picture index displayed in the matched picture box in the has been clicked  
int count;           // Count and record how many pictures you clicked

int gameState;       // Game status: 0-in progress, 1-New game, - 1-not started

int gameTime;        // Game time
int matchNum;        // Number of pairs
int record;          // Highest record

2.2.1. Game initialization

First, we need to re instantiate the one-dimensional array, then change the game state to not started (the value is - 1), and set the maximum record to 0.

The function codes are as follows:

 this.pictureIds = new int[16];  // Create a one-dimensional array
 gameState = -1;                 // Game status is not started
 record = 0;                     // No record

2.2.2. Start the game

The first is to set the initial state of each variable, which will not be described one by one here, and then put each picture into two box es at random

// Randomly specify the animal pictures displayed in each picture box
for (int i = 1; i <= 8; i++)
{
    // Each picture is placed in two picture boxes
    PutIntoBox(i);
    PutIntoBox(i);
}

PutIntoBox is a custom random picture position function

// Randomly put the pictures with the specified index into a picture box and record them in a one-dimensional array
private void PutIntoBox(int pictureIndex)
{
    Random r = new Random();
    int boxId = r.Next(16);   // Randomly find a picture box
    if (this.pictureIds[boxId] != -1)  // There are already pictures
    {
        // Find a picture box that doesn't have a picture yet
        while (this.pictureIds[boxId] != -1)
        {
            boxId = r.Next(16);   // Randomly find a picture box
        }
    }

    this.pictureIds[boxId] = pictureIndex;  // Specify the picture corresponding to this picture box
}

Don't forget to turn on the timer after that

// Start timer
tmrShow.Start();

2.2.3. play a game

Picture box click event
First, if the game is not in progress, you cannot click on the picture box

// 
if (gameState != 0)
{
    return;
}

If you are in the game, you can judge whether you click the first picture or the second one:

  • Click the first picture: save the relevant parameters of the current picture
  • Click the second picture: save the relevant parameters of the second picture and call the judgment function to judge whether it matches.
if (count == 1)  // Click on the first picture
{
    this.firstIndex = newIndex;
    this.firstPictureId = newPictureId;
    ((PictureBox)sender).Image = ilPictures.Images[newPictureId];
    
    tmrShow.Start();                
}
else if (count == 2)  // Click on two pictures
{
    this.secondIndex = newIndex;
    this.secondPictureId = newPictureId;
    ((PictureBox)sender).Image = ilPictures.Images[newPictureId];

    tmrShow.Stop();   // Stop the timer that controls the 3-second display
    tmrMatch.Start();    // Start the timer with a delay of 0.5s and judge whether it matches
}             

2.2.3.1. judge

To judge, you need to judge two:

  • Whether the pairing is successful for picture elimination
  • Check if you want to stop the game

And the order cannot be changed. First judge whether it can be eliminated, because when the last two pictures are eliminated, it is the end of the game.

// Whether the pairing is successful for picture elimination
if (this.firstIndex != this.secondIndex && this.firstPictureId == this.secondPictureId)
{
    // Make the picture box invisible
    SetInvisible(this.firstIndex);
    SetInvisible(this.secondIndex);
    this.matchNum++;
}

ResetState();     // Restart pairing
HidePictures();

// Check if you want to stop the game            
if (this.matchNum == 8)
{
    tmrGame.Stop();
    string message = string.Format("Pairing completed, time{0}Seconds, keep trying!",this.gameTime);
    MessageBox.Show(message, "game over", MessageBoxButtons.OK, MessageBoxIcon.Information);
    if (this.gameTime < this.record || this.record ==0)
    {
        lblRecord.Text = this.gameTime.ToString() + "second";
    }
    this.gameState = -1;   // The game has not started
}            

2.2.4. sign out

DialogResult result = MessageBox.Show("Are you sure you want to exit?","Tips",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
    Application.Exit();
}  

3. Code implementation

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MatchBox
{
    public partial class BoxesForm : Form
    {
        // One dimensional array, corresponding to each picture box on the form, stores the picture index corresponding to each picture box
        int[] pictureIds;
        int firstIndex;      // Record the first picture box clicked
        int secondIndex;     // Record the matched picture box clicked
        int firstPictureId;  // The picture index displayed in the first picture box in the has been clicked  
        int secondPictureId; // The picture index displayed in the matched picture box in the has been clicked  
        int count;           // Count and record how many pictures you clicked

        int gameState;       // Game status: 0-in progress, 1-New game, - 1-not started

        int gameTime;        // Game time
        int matchNum;        // Number of pairs
        int record;          // Highest record

        public BoxesForm()
        {
            InitializeComponent();
        }

        // When the form is loaded, each picturebox is associated with an animal picture
        private void BoxesForm_Load(object sender, EventArgs e)
        {
            this.pictureIds = new int[16];  // Create a one-dimensional array
            gameState = -1;                 // Game status is not started
            record = 0;                     // No record
        }

        // Start the game
        private void StartGame()
        {
            gameState = 1;      // Mark as new game
            this.gameTime = 0;  // Game time
            this.matchNum = 0;  // Number of pairs

            // Set the initial state of each variable
            ResetState();

            // Stop all timers
            tmrGame.Stop();
            tmrShow.Stop();
            tmrMatch.Stop();

            lblCostTime.Text = "0 second";

            // Set the array of pictures displayed in the record picture box to - 1            
            for (int i = 0; i < this.pictureIds.Length; i++)
            {
                this.pictureIds[i] = -1;
            } 

            // Randomly specify the animal pictures displayed in each picture box
            for (int i = 1; i <= 8; i++)
            {
                // Each picture is placed in two picture boxes
                PutIntoBox(i);
                PutIntoBox(i);
            }

            // Show all pictures
            foreach (Control item in this.Controls)
            {
                if (item is PictureBox)
                {
                    int index = Convert.ToInt32(((PictureBox)item).Tag);
                    int pictureIndex = this.pictureIds[index];
                    ((PictureBox)item).Visible = true;
                    ((PictureBox)item).Image = ilPictures.Images[pictureIndex];
                }
            }

            // Start timer
            tmrShow.Start();
        }

        // Randomly put the pictures with the specified index into a picture box and record them in a one-dimensional array
        private void PutIntoBox(int pictureIndex)
        {
            Random r = new Random();
            int boxId = r.Next(16);   // Randomly find a picture box
            if (this.pictureIds[boxId] != -1)  // There are already pictures
            {
                // Find a picture box that doesn't have a picture yet
                while (this.pictureIds[boxId] != -1)
                {
                    boxId = r.Next(16);   // Randomly find a picture box
                }
            }

            this.pictureIds[boxId] = pictureIndex;  // Specify the picture corresponding to this picture box
        }

        // Picture box click event
        private void picBox_Click(object sender, EventArgs e)
        {
            // If the game is not in progress, you cannot click the picture box
            if (gameState != 0)
            {
                return;
            }

            int newIndex = Convert.ToInt32(((PictureBox)sender).Tag);   // The index of the picture box in the current point in the array
            int newPictureId = this.pictureIds[newIndex];               // The index of the picture displayed in the picture box in the current point            
                        
            count++;  // count
            
            if (count == 1)  // Click on the first picture
            {
                this.firstIndex = newIndex;
                this.firstPictureId = newPictureId;
                ((PictureBox)sender).Image = ilPictures.Images[newPictureId];
                
                tmrShow.Start();                
            }
            else if (count == 2)  // Click on two pictures
            {
                this.secondIndex = newIndex;
                this.secondPictureId = newPictureId;
                ((PictureBox)sender).Image = ilPictures.Images[newPictureId];

                tmrShow.Stop();   // Stop the timer that controls the 3-second display
                tmrMatch.Start();    // Start the timer with a delay of 0.5s and judge whether it matches
            }                      
        }

        // Restore state
        private void ResetState()
        {
            this.firstIndex = -1;
            this.secondIndex = -1;
            this.firstPictureId = -1;
            this.secondPictureId = -1;
            this.count = 0;   
        }

        // Control the display of pictures for up to 3 seconds
        private void tmrShow_Tick(object sender, EventArgs e)
        {
            tmrShow.Stop();  // Timer stop            

            if (gameState == 1)  // If it's a new game
            {
                gameState = 0;   // Change game status to in progress                
                tmrGame.Start(); // Start timing
            }

            ResetState();      // Clear record
            HidePictures();   // Hide picture           
        }
        
        // Hide all pictures
        private void HidePictures()
        {
            // Turn over all the pictures            
            foreach (Control item in this.Controls)
            {
                if (item is PictureBox)
                {
                    ((PictureBox)item).Image = ilPictures.Images[0];
                }
            }            
        }

        // Make the picture box of the specified index invisible
        private void SetInvisible(int index)
        {
            foreach (Control item in this.Controls)
            {
                if (item is PictureBox)
                {
                    if (Convert.ToInt32(((PictureBox)item).Tag) == index)
                    {
                        ((PictureBox)item).Visible = false;
                    }                    
                }
            }
        }

        // Display for 0.5 seconds
        private void tmrMatch_Tick(object sender, EventArgs e)
        {
            tmrMatch.Stop();

            if (this.firstIndex != this.secondIndex && this.firstPictureId == this.secondPictureId)
            {
                // Make the picture box invisible
                SetInvisible(this.firstIndex);
                SetInvisible(this.secondIndex);
                this.matchNum++;
            }

            ResetState();     // Restart pairing
            HidePictures();
            
            // Check if you want to stop the game            
            if (this.matchNum == 8)
            {
                tmrGame.Stop();
                string message = string.Format("Pairing completed, time{0}Seconds, keep trying!",this.gameTime);
                MessageBox.Show(message, "game over", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (this.gameTime < this.record || this.record ==0)
                {
                    lblRecord.Text = this.gameTime.ToString() + "second";
                }
                this.gameState = -1;   // The game has not started
            }            
        }

        // Start a new game
        private void tsmiNewGame_Click(object sender, EventArgs e)
        {
            StartGame();
        }

        // sign out
        private void tsmiExit_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you want to exit?","Tips",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                Application.Exit();
            }            
        }

        // Game timing
        private void tmrGame_Tick(object sender, EventArgs e)
        {
            this.gameTime++;  // Increase time by 1s
            lblCostTime.Text = gameTime.ToString() + "second";                     
        }

        private void tsmiRule_Click(object sender, EventArgs e)
        {
            GameRuleForm ruleForm = new GameRuleForm();
            ruleForm.ShowDialog();
        }
    }
}

4. Resource links

CSDN Download: https://mp-new.csdn.net/mp_download/manage/download/UpDetailed
Baidu online disk:
Link: Add link description
Extraction code: y2j1
After copying this content, open Baidu online disk mobile App, which is more convenient to operate - sharing from Baidu online disk super member V4

Like the little partner, please like the collection, thank you for your support.

Topics: Python Java Linux Game Development csharp