Minesweeper in PHP

Whilst my Sudoku solver is up to a basic level, I just need to implement so more logic to reduce possible values, I started to think about the game Minesweeper.  I’ve played it since it was in the Microsoft Entertainment Pack 1, which was installed in to Windows 3.

Minesweeper is another grid based game, the player has to find all the mines which are hidden.  The basic game is an 8×8 grid with 10 mines. The first reveal is never a mine, but will show either a blank grid or a number. If it’s a number, it means in the 8 surrounding cells, there are that many mines. If it’s blank, all the blocks around will be revealed until a number is shown, indicating there is a mine in a surrounding cell.  If you think a cell is a mine, you can mark so it can’t be clicked.

The game is over when the number of remaining cells are the same as the number of mines, whether they are marked or not.

I actually started to think about this while I was trying to work out better ways to handle the logic in the Sudoku solver.  I was thinking, how are the minesweeper grids generated. I read one site where it say when the grid is presented, on the first click, if it’s a mine, the mine is moved to another cell and the grid is recalculated. I started to think the other way around. Generate the grid AFTER the first click, eliminating that cell as a possible mine.  So it would be a case of creating an array with all the cell references, remove the click cell, randomise the remaining references and then trimming the array to the number of bombs.  So that’s where I started.

I started coding and was able to quickly generate the grid, values and the numbers to indicate the number of mines surrounding a cell.  I did have to think of a better way to identify the numbers on the grid, mainly because of the function to reveal blank cells could go out of the region by using a 2 digit identification number.  So the grid numbers are identified by 4 digits, starting from 1010.  This method might not have been the best, but it worked for me.

I had a rough idea how I wanted to handle what happens when a blank cell is clicked, but that’s what took me the most time. Given that the surrounding cells have to be checked, then those have to be checked as well if they are blank.

The code is commented and I’ve tried using variable names that make things obvious. I’ve still used the similar classes as Sudoku. An input handler and a grid generator.  It’s a basic interface, but the core game mechanics are there.

When you run it, you get to choose difficulty or specify a custom sized grid:

Then when you start the game, you are submitting values from a form over and over again.

Until the game is lost

Or won

Below is the code. I’ve tried to factor as best I could without going too far.  Let me know if you have any suggestions.

index.php

input_handler.php

grid_gen.php

 

Leave a Reply