This is a lab that I do with my AP Computer Science A students. The objective of the lab is to get students comfortable with using multidimensional arrays, recognizing when to use iteration or recursion, and getting comfortable reading documentation and javadocs.
Minesweeper is a game where there is a grid of squares. Some squares have mines on them. Other squares have a number on them indicating how many mines are are next to it in the eight squares around it. If the number is 0, the number the number will be blank. The objective of the game is to open all the squares except for the squares that contain a mine. If the player opens a square that contains a mine, the player loses.
The lab comes with a skeleton driver for the minesweeper. The skeleton driver does the following things:
- Provides the GUI where user can click on the the squares
- Places a specified number of bombs onto the grid
- Display the win or lose popup message
As you’ll notice if you initially run the lab, the game doesn’t work properly and is missing a lot of details.
There is a file named MyGrid.java. It contains four methods that the student must complete in order for MineSweeper to work correctly.
- void initializeHints()
This method generates the numbers that tell the player how many mines are around a square
- boolean checkDead(int r, int c)
This method returns true if the player clicks a mine
- boolean checkWin()
This method returns true when all the squares have been clicked except the squares containing bombs
- void updateGrid(int r, int c)
This method shows the number beneath the square. If the square is zero, the method will open all the adjacent squares that are not mines. The method will clear an area of zeros to enable faster play.
To help the students debug, there is a testing flag that the students can set. In testing mode, the students will be able to see the data in the Minesweeper grid.
The lab contains 4 files that must be placed in the same directory.
- MineSweeper.class: This contains the main method
- DrawingPanel.class: This class is responsible for the GUI
- TheGrid.class: This class contains the game data
- MyGrid.java: An extension of TheGrid. This is the file students will modify
To compile and run the lab, ensure that all the files are in the same directory. In a terminal, go to the directory and run the following commands:
- javac MyGrid.java
- java Minesweeper
I’ve packaged the lab in zip file that you can download below. It contains the a handout you can give to your students explaining the lab. It also has the four files and the Javadoc for TheGrid class
The source code is released under the MIT License. The lab is released under the Creative Commons Attribution ShareAlike 4.0 International License.
If you like my work, a small donation or feedback will be much appreciated.