Friday, June 29, 2012

Minesweeper Applet - Part 2


This is part 2 of the series. It is recommended to read part 1 first. If you just want to play the game, you will need in part 1 and in part 2. Put both of them in the same folder and type :
javac *.java
java MineApplet
Part 1 can be found here:

Upload to web server

It is not necessary to have a web server in order to play this applet. Because it is written in such a way that a simple applet container is implemented in the code.

However, if you have a web server you may wish to upload the applet to share it. First you would need to create a jar file.

jar cvf mine.jar *.class
Then create an HTML file to hold the applet.

The user interface

It is almost identical to the Windows version of the MineSweeper. Left click to open a cell, right click to mark a mine, double click to auto-open safe neighbours.

All of the cells are implemented by JButton. I have extended the JButton class to MyButton for the following reasons:

  1. We can provide customize outlook of the button, for example, we may change the font color of the button according to the label. The standard MineSweeper game typically use red "1", green "2", red "3".
  2. We can draw an icon to the button. For example, the "new game" button at the top has a smiling face on it. See the paintComponent() method for details
  3. We can define mouse action listener for left click, right click and even double click. See the mouseClicked() method for details

Understanding the code

The logic of the game was implemented in in part 1.
The GUI is implemented in here. was explained in Part 1. I am not going to write detail explanation of here. The best way to understand it is to play the game then view the code. It illustrate many useful techniques.

  1. It contains a simple applet container so that it can be run as an java application. If you are searching for "Applet to Application", you may find an example right here. See the main() method for details
  2. It contains JButton with customized look
  3. It contains JButton with customized control. It implements a JButton class with right click and double click support.
  4. It uses the technique of embedding image into source code so that no separated image files are needed. See buildSmileImage() for details.
  5. It implements a timer thread to display the timer. The timer thread conform to the standard of the applet life cycle. See the start(), run() and stop() method.

Full source listing

No comments:

Post a Comment