Monday, January 24, 2011

Minesweeper in Java: Part One - GUI

Continuing from yesterdays post about Minesweeper as an introduction to game programming today we are going to start by creating Minesweeper in Java, a traditional starting language. Creating graphical user interfaces is normally more advanced of a topic than a usual starting tutorial, but the basics are quite simple.

For Minesweeper the basic interface for the game is a simple grid with squares. In Java we will do this by creating a JPanel with GridLayout. For simplicity sake we will assume that the grid will always be 10x10. These are set in the constructor.

import java.awt.*;
import javax.swing.*;

public class GameGridGui extends JPanel{

public GameGridGui(){
     this.setSize(400,400);
     this.setLayout(new GridLayout(10,10));
}
}

Once the basic layout is taken care of the next thing that needs to be done is build the squares. There are lots of ways to do this but since we need to click on the squares there is no reason why we shouldn't just use an array of JButtons. Create a method called buildButtons and call it from your constructor.

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JPanel;

public class GameGridGui extends JPanel{

 private JButton squares[][];
 
public GameGridGui(){
     this.setSize(400,400);
     this.setLayout(new GridLayout(10,10));
     squares = new JButton[10][10];
     buildButtons();
}

private void buildButtons(){
     for(int i=0;i<10;i++){
          for(int j=0;j<10;j++){
               squares[i][j] = new JButton();
               squares[i][j].setSize(400,400);
               this.add(squares[i][j]);
          }
     }
}
}

If you want to test this out to see what it looks like, just create a quick main method with a JFrame.

public static void main(String[] args) {
  GameGridGui g = new GameGridGui();
  JFrame frame = new JFrame("My Minesweeper");
  frame.add(g);
  frame.setSize(400,400);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }

And with that you have a basic Minesweeper GUI in Java.

6 comments:

  1. how can i change the array into 6x6

    ReplyDelete
  2. Good practice, and something I did not do in this example, is to set the width and height as constants. In my case it would be:

    final int WIDTH = 10;
    final int HEIGHT = 10;

    But you can use any numbers you want. The GridLayout would need to be changed in the constructor, and the two for loops in the buildButtons method. It might also be a good idea to change the size, as 400x400 might be a little too large for just a 6x6 grid. 240x240 might be a better window size.

    ReplyDelete
  3. Nice Example ... I have also write java code for minesweeper visit Minesweeper Example

    ReplyDelete
  4. Well Explained . I have write cod for minesweeper game visit minesweeper game

    ReplyDelete