Friday 18 November 2011

Java program to design a GUI based 15 puzzle game

It is simply a game of arranging numbers 1-15 which are placed in a 4*4 2D array with one block left blank. One will have to arrange by moving the blank block. Here a timer is included to count total time to solve it. This logic is given a GUI with help of Java Swing.Here is the code for you -->
The Screenshot shown alongside is actually the picture how the game will look like when run on Windows7. It will look same as to the code of JAVA file link given below but different from the below code only in respect with game menubar. Try writing below code and also that is written in file (link given at last). Hope you will enjoy.

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.text.*;

public class FifteenPuzzle2 extends JPanel {
  public static JMenuItem newItem;
  public static javax.swing.Timer t;
  JButton[][] jb = new JButton[4][4];
  static int minute, second;
  static JFrame jf;

  public FifteenPuzzle2() {
       setLayout(new GridLayout(4, 4));

       int i, j, k;
       init(true);
       for (i = 0; i < jb.length; i++)
      for (j = 0; j < jb[i].length; j++)
           jb[i][j].addActionListener(
             new ActionListener() {
               public void actionPerformed(ActionEvent e) {
              String command = e.getActionCommand();
              String[] indices = command.split(" ");
              int i = Integer.parseInt(indices[0]);
              int j = Integer.parseInt(indices[1]);
              int[] r = {i - 1, i, i + 1, i};
              int[] c = {j, j + 1, j, j - 1};
                for (int k = 0; k < 4; k++) {
                 if (r[k] >= 0 && r[k] < 4 && c[k] >= 0 && c[k] < 4){
                    JButton button = jb[r[k]][c[k]];
                    if (button.getText().equals("")) {
                      button.setText(jb[i][j].getText());
                      jb[i][j].setText("");
                    }
                 }
                }
            }
        });

        newItem.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    init(false);
                }
            }
        );
    }
    public void init(boolean firstTime) {
        ArrayList a = new ArrayList();
        int i, j, k;
        for (i = 1; i <= 15; i++)
            a.add(new Integer(i));
        Collections.shuffle(a);
        a.add(new Integer(0));

        k = 0;
        for (i = 0; i < jb.length; i++)
            for (j = 0; j < jb[i].length; j++) {
                Integer val = (Integer)a.get(k++);
                if (firstTime) {
                    jb[i][j] = new JButton(val.intValue() + "");
                    jb[i][j].setActionCommand(i + " " + j);
                    add(jb[i][j]);
                }
                else
                    jb[i][j].setText(val.intValue() + "");
            }
        jb[3][3].setText("");
            minute = 0;
            second = 0;
    }

    public static void main(String[] args) {
        jf = new JFrame();
        jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

        JMenuBar jmb = new JMenuBar();
        jf.setJMenuBar(jmb);

        JMenu gameMenu = new JMenu("Game");
        jmb.add(gameMenu);
       
        newItem = new JMenuItem("New");
        gameMenu.add(newItem);

        gameMenu.addSeparator();

       
        FifteenPuzzle2 fp = new FifteenPuzzle2();
        jf.setContentPane(fp);

        final DecimalFormat dc = new DecimalFormat("00");

        t = new javax.swing.Timer(
            1000,
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jf.setTitle(dc.format(minute) + ":" + dc.format(second));
                    second++;
                    if (second >= 60) {
                        second %= 60;
                        minute++;
                    }
                }
            }
        );
        jf.pack();
        jf.setVisible(true);
        Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
        int w=(int)d.getWidth();
        int h=(int)d.getHeight();
        jf.setLocation((int)(w/2-jf.getWidth()/2),(int)(h/2-jf.getHeight()/2));
        t.start();
    }
}


You can also download the source code from following links -
DOWNLOAD the JAVA source code from MediaFire
DOWNLOAD the JAVA source file from 4shared

8 comments:

  1. This is a great one.
    Thank you for this code.

    ReplyDelete
    Replies
    1. U r always welcome. Thanks for following my blog. If you have any queries about any code or if you need any help about any code which is not posted here you can always ask for that code through my mail id or by coomenting . You can also take help through Gtalk when both of us are online.

      Delete
    2. hey Nirupam Das can u give me an detailed explanation regarding the code please

      Delete
  2. Great Code, i am new to java... i am having 4 years exp in PHP, now to learn JAVA, i want to switch over to JAVA. Can you help me out.

    ReplyDelete
  3. how too make PICTURE puzzle? please answer
    thank you mister

    ReplyDelete
  4. can u give me a document explaining the code please

    ReplyDelete
  5. Can u send me d document of ir prjct

    ReplyDelete
  6. can you make class diagram of it?

    ReplyDelete