@[TOC]

First of all, I wish programmers a happy children’s day(* ^ del ^ *)

Let’s take it home to the kids

All right, let’s get straight to talent! EG eamon, EG eamon EG eamon……… (At the end of the article, there is a link to the finished product of the game, and your favorite friend can connect it with three keys.)

1. Effect display

(Just part of it)Help rulesMy brain stupid, customs clearance can only test auxiliary (this may also be my reason to learn to do plug-ins, ha ha ha, don’t go away, a wave of three, plug-ins continue to update, and later Windows hacker technology articles you [PS: this is C++ bloggers exclusive bar])!Ahem, back to game design.

2. Game design

2.1. Interface design

First of all, don’t panic when you see the gorgeous interface.

Of course the game help is also the background image, but the words are also part of the imageAfter that, it’s time to add a menu bar, simply add a start game and exitNext, create 16 PictureBoxes for displaying 16 small imagesThen there are three Lables, which are used to display information during the game

2.2. Logical design

Before writing the logic we need to establish the variables that the game will use

// One dimensional array, corresponding to each picture box on the form, stores the corresponding picture index of each picture box
int[] pictureIds;
int firstIndex;      // Record the first picture box clicked
int secondIndex;     // Record the clicked matching picture box
int firstPictureId;  // The index of the picture displayed in the first picture box in the already clicked
int secondPictureId; // The index of the picture displayed in the matched picture box in the already clicked
int count;           // Count how many images are clicked

int gameState;       // Game status: 0- Ongoing, 1- new game, -1- not started

int gameTime;        // Game time
int matchNum;        // The number of pairs
int record;          // Record high
Copy the code

2.2.1. Game initialization

The first step is to re-instantiate the one-dimensional array, change the game state to not started (value -1), and set the highest record to 0.

The function code is as follows:

 this.pictureIds = new int[16];  // Create a one-dimensional array
 gameState = - 1;                 // The game state is not started
 record = 0;                     // There is no record
Copy the code

2.2.2. Start the game

The first is to set the initial state of each variable, which will not be described here, and then randomly place each picture into two boxes

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

PutIntoBox is a custom random image position function

// Place the indexed image randomly in an image box and record it in a one-dimensional array
private void PutIntoBox(int pictureIndex)
{
    Random r = new Random();
    int boxId = r.Next(16);   // Find a random picture box
    if (this.pictureIds[boxId] ! =- 1)  // There are already pictures
    {
        // Find a picture box that does not yet have a picture
        while (this.pictureIds[boxId] ! =- 1)
        {
            boxId = r.Next(16);   // Find a random picture box}}this.pictureIds[boxId] = pictureIndex;  // Specify the image corresponding to this picture box
}
Copy the code

Then don’t forget to start the timer

// Start the timer
tmrShow.Start();
Copy the code

2.2.3. Play a game

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

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

If you are in the game, you can determine whether the first image or the second one is clicked:

  • Click on the first image: Save the parameters of the current image
  • Click the second picture: save the parameters of the second picture, and call the judgment function to determine whether it matches.
if (count == 1)  // Click on the first image
{
    this.firstIndex = newIndex;
    this.firstPictureId = newPictureId;
    ((PictureBox)sender).Image = ilPictures.Images[newPictureId];
    
    tmrShow.Start();                
}
else if (count == 2)  // Click on two images
{
    this.secondIndex = newIndex;
    this.secondPictureId = newPictureId; ((PictureBox)sender).Image = ilPictures.Images[newPictureId]; tmrShow.Stop();// Stop the 3-second display timer
    tmrMatch.Start();    // Start the timer with a delay of 0.5s and determine whether it matches
}             
Copy the code

2.2.3.1. Judgment

Judgment requires two judgments:

  • Whether the match is successful for image elimination
  • Check if you want to stop the game

And the order can not be changed, to determine whether to eliminate, because when the last two pictures eliminated is the end of the game.

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

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

// Check if you want to stop the game
if (this.matchNum == 8)
{
    tmrGame.Stop();
    string message = string.Format("Match completed in {0} seconds, keep up the good work!".this.gameTime);
    MessageBox.Show(message, "Game over.", MessageBoxButtons.OK, MessageBoxIcon.Information);
    if (this.gameTime < this.record || this.record= =0)
    {
        lblRecord.Text = this.gameTime.ToString() + "Seconds";
    }
    this.gameState = - 1;   // The game is not started
}            
Copy the code

2.2.4. Quit

DialogResult result = MessageBox.Show("Are you sure?"."Tip",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
    Application.Exit();
}  
Copy the code

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 corresponding picture index of each picture box
        int[] pictureIds;
        int firstIndex;      // Record the first picture box clicked
        int secondIndex;     // Record the clicked matching picture box
        int firstPictureId;  // The index of the picture displayed in the first picture box in the already clicked
        int secondPictureId; // The index of the picture displayed in the matched picture box in the already clicked
        int count;           // Count how many images are clicked

        int gameState;       // Game status: 0- Ongoing, 1- new game, -1- not started

        int gameTime;        // Game time
        int matchNum;        // The number of pairs
        int record;          // Record high

        public BoxesForm()
        {
            InitializeComponent();
        }

        // When the form loads, each Picturebox is associated with an animal image
        private void BoxesForm_Load(object sender, EventArgs e)
        {
            this.pictureIds = new int[16];  // Create a one-dimensional array
            gameState = - 1;                 // The game state is not started
            record = 0;                     // There is no record
        }

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

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

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

            lblCostTime.Text = "0 seconds";

            // Set the array of images 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 image to display in each picture box
            for (int i = 1; i <= 8; i++)
            {
                // Each image is placed in two image boxes
                PutIntoBox(i);
                PutIntoBox(i);
            }

            // Display all images
            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 the timer
            tmrShow.Start();
        }

        // Place the indexed image randomly in an image box and record it in a one-dimensional array
        private void PutIntoBox(int pictureIndex)
        {
            Random r = new Random();
            int boxId = r.Next(16);   // Find a random picture box
            if (this.pictureIds[boxId] ! =- 1)  // There are already pictures
            {
                // Find a picture box that does not yet have a picture
                while (this.pictureIds[boxId] ! =- 1)
                {
                    boxId = r.Next(16);   // Find a random picture box}}this.pictureIds[boxId] = pictureIndex;  // Specify the image corresponding to this picture box
        }

        // Picture box click the 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 array
            int newPictureId = this.pictureIds[newIndex];               // The index of the picture displayed in the picture box in the current dot
                        
            count++;  / / count
            
            if (count == 1)  // Click on the first image
            {
                this.firstIndex = newIndex;
                this.firstPictureId = newPictureId;
                ((PictureBox)sender).Image = ilPictures.Images[newPictureId];
                
                tmrShow.Start();                
            }
            else if (count == 2)  // Click on two images
            {
                this.secondIndex = newIndex;
                this.secondPictureId = newPictureId; ((PictureBox)sender).Image = ilPictures.Images[newPictureId]; tmrShow.Stop();// Stop the 3-second display timer
                tmrMatch.Start();    // Start the timer with a delay of 0.5s and determine whether it matches}}// Restore the status
        private void ResetState()
        {
            this.firstIndex = - 1;
            this.secondIndex = - 1;
            this.firstPictureId = - 1;
            this.secondPictureId = - 1;
            this.count = 0;   
        }

        // Controls the image display for a maximum of 3 seconds
        private void tmrShow_Tick(object sender, EventArgs e)
        {
            tmrShow.Stop();  // Stop the timer

            if (gameState == 1)  // If the game is new
            {
                gameState = 0;   // Change the game state to Ongoing
                tmrGame.Start(); // Start the timer
            }

            ResetState();      // Clear the recordHidePictures();// Hide the image
        }
        
        // Hide all images
        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 image 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 0.5 seconds
        private void tmrMatch_Tick(object sender, EventArgs e)
        {
            tmrMatch.Stop();

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

            ResetState();     // Restart the pairing
            HidePictures();
            
            // Check if you want to stop the game
            if (this.matchNum == 8)
            {
                tmrGame.Stop();
                string message = string.Format("Match completed in {0} seconds, keep up the good work!".this.gameTime);
                MessageBox.Show(message, "Game over.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (this.gameTime < this.record || this.record= =0)
                {
                    lblRecord.Text = this.gameTime.ToString() + "Seconds";
                }
                this.gameState = - 1;   // The game is not started}}// Start a new game
        private void tsmiNewGame_Click(object sender, EventArgs e)
        {
            StartGame();
        }

        / / exit
        private void tsmiExit_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure?"."Tip",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            if(result == DialogResult.Yes) { Application.Exit(); }}// Game timing
        private void tmrGame_Tick(object sender, EventArgs e)
        {
            this.gameTime++;  // Increase the time by 1s
            lblCostTime.Text = gameTime.ToString() + "Seconds";                     
        }

        private void tsmiRule_Click(object sender, EventArgs e)
        {
            GameRuleForm ruleForm = newGameRuleForm(); ruleForm.ShowDialog(); }}}Copy the code

4. Resource links

CSDN download: mp-new.csdn.net/mp_download… Baidu cloud: link: pan.baidu.com/s/1gxe1EVFL… Extract code: Y2j1 Copy this section of content after opening Baidu network disk mobile App, operation is more convenient oh — from Baidu network disk super member V4 share

Thank you for your support.