Today’s sharing started, please give us more advice ~

Today is to share with you minesweeper, this is the system’s own classic small game, before school when the computer often play this, like it, so try.

rendering

Implementation approach

1. Create a two-dimensional array with 9 rows and 9 columns.

2. Set thunder: the number of random rows I and columns J, according to the random to I, J from the two-dimensional array to take out the corresponding element, set an attribute type of the element is equal to 1, indicating that the current element has been thunder, and increase the thunder counter, and then recursive call; If the element is already thunder, it skips ahead and jumps out of recursion when the thunder counter reaches its maximum value.

3. Count the number of mines around each element (top left, top right, top right, bottom right, bottom left, bottom left, and left) and display the corresponding number in the current position (more on this later).

4. From the same two-dimensional array, create small squares for the mask to cover the shape you created earlier.

5. Click the small square of the mask to trigger the unveiling. After unveiling, do different operations according to the corresponding number or thunder.

Code implementation

Create the background and related elements

Create thunder and display the corresponding picture

1. Randomize row and COL, and get the object from the two-dimensional array; 2. Determine if it is Thunder, if it is, skip the current; 3. If the current object is not a lightning object, mark it as a lightning object and change the image. 4. Recursion, jump out when the set amount is reached.

Count the amount of lightning around and display

1. The two-dimensional array defined earlier through the loop

2. If the subscript of the current element is (I,j), the upper left is (i-1, J-1), the upper left is (i-1,j), the upper right is (i-1,j+1), and so on, as shown in the figure below:

3. Take out these elements separately and judge whether they are thunder or not. If so, count them up and add them up.

Create a mask

Create timings and counters

Add mouse movement events

Add mouse click events

Success determination 1

The number of unopened is the same as the number of mines

Success determination 2

The number of flags marked as thunder is the same as the total number of classes

Effect of gori

Click the mouse after the thunder, will trigger an animation of the thunder explosion, which is achieved by switching pictures

Add the right mouse button event

This event is flagged or flagged as unknown.

Finally, add the restart event, and the victory and defeat pictures are displayed.

summary

I wrote this small game with canvas, it looks ok, I don’t know if there are any bugs I haven’t found, the difficulty is set as simple at present, if you want to change the difficulty, the code can be modified a little.

Today’s share has ended, please forgive and give advice!