We are going to implement a mine sweeper game in Java. The game can be executed as an applet and as an application.
Text Mode
It is simpler to implement the game in text mode. Not only the code is simpler but also it is much easier to debug. We will implement the game in text mode first, then add a GUI after the game is working.
Data Structure
We will use a simple single dimensional array to represent the mine field. We will use the number 64 to represent a mine. We will hard code the mine field at the moment. Later we will add code to generate a random mine field.
Counting the neighboring mines
What we want :
0 1 1 1 0 1 64 1 0 0 1 64 1 0 2 2 2 0 0 1 1 1 0 2 64 2 0 0 0 0 0 0 2 64 3 1 0 0 0 0 0 1 2 3 64 0 1 1 1 0 0 2 64 3 0 1 64 1 0 0 2 64 2 1 2 1 1 0 0 1 2 2 64 1 0 0 0 0 0 1 64What we do : Debugging
As previously said, it is easier to debug a text mode program, we will write a simple method to display the mine field. M1.java
This is the first version of our mine sweeper, it just print out a hard code mine field, with the correct neighboring counts. Sample run :
javac *.java java M1 0 1 1 1 0 1 64 1 0 0 1 64 1 0 2 2 2 0 0 1 1 1 0 2 64 2 0 0 0 0 0 0 2 64 3 1 0 0 0 0 0 1 2 3 64 0 1 1 1 0 0 2 64 3 0 1 64 1 0 0 2 64 2 1 2 1 1 0 0 1 2 2 64 1 0 0 0 0 0 1 64Hiding all the cells
We will hide the mine field by setting bit 7 of all cells to one. We would need to modify printField() as well. Now we have the second version of MineSweeper Sample Run:
javac M2.java java M2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Opening a Cell
For example, to open cell number 2 in the field, add the following in main() Test run:
. . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .This is a "1". That means one of the neighbouring cell is a mine.
To open cell number 0, use the following Test run:
0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Since this is zero, we can be sure the three neighbouring cells are safe to open. So we open them automatically. Test run:
0 1 . 1 0 1 . . . 0 1 . 1 0 2 . . . 0 1 1 1 0 2 . . . 0 0 0 0 0 2 . . . 0 0 0 0 0 1 2 . . 0 1 1 1 0 0 2 . . 0 1 . 1 0 0 2 . . 1 2 1 1 0 0 1 2 . . 1 0 0 0 0 0 1 .We are so lucky that most of the cell are automatically opened.
Next we complete the text mode minesweeper. The user can enter any number between 0 to 63 to open a cell. Coming next
Though we have a working mine sweeper, it is quite difficult to play in text mode. We will make an applet version of the game. We won't reinvent the wheel and Mine.java would be completely reused without modification. We will just add a GUI wrapper.
Continue with part 2 here ...
No comments:
Post a Comment