Java GUI basic Eight Puzzle (jigsaw Puzzle), eightpuzzle

Source: Internet
Author: User

Java GUI basic Eight Puzzle (jigsaw Puzzle), eightpuzzle

It's easy to use java GUI to create a simple puzzle game

// Main

package HW1;import java.io.IOException;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;public class HW1 extends JFrame{/** *  */public HW1_0586(String string) {Icon icon = new ImageIcon(string);JLabel label = new JLabel(icon);this.add(label);this.setTitle("Original image!");this.setLocation(200,0);}/** * To build icon from an existing image. * * @param path the path of the image * @return */public static void main( String args[] ) throws IOException{String path = "img1.png";//String path ="img2.png"<span style="font-family: Arial, Helvetica, sans-serif;">;</span>   HW1 buttonFrame = new HW1(path);      JEightPuzzleFrame jframe = new JEightPuzzleFrame("Eight Puzzle",path);   jframe.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   jframe.setSize( 165,165 ); // set frame size   jframe.setVisible( true ); // display frame      buttonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   buttonFrame.setSize( 165,165 ); // set frame size   buttonFrame.setVisible( true ); // display frame   }}


// Eight puzzle


package HW1;import java.awt.Container;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.Random;import javax.imageio.ImageIO;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;/** this is a eight puzzle game. * two-dimensional array save the location of button * the one-array save the individual button *  */public class JEightPuzzleFrame extends JFrame {/** *  *///private static final long serialVersionUID = 1L;private BufferedImage img;private BufferedImage [] imgs = new BufferedImage[8];private JButton[] buttons = new JButton[8];private ImageIcon [] imgicons = new ImageIcon[8]; private Icon [] icons = new Icon[8];private GridLayout layout;private JPanel panel;private Container container;private JLabel label;private int[][] array = new int[3][3];public JEightPuzzleFrame(String title, String path) {super(title);System.out.println(this.getLocation());container = new Container();container = getContentPane();panel = new JPanel();layout = new GridLayout(3, 3);setLayout(layout); label = new JLabel("");for (int i = 0; i < 8; i++) {buttons[i] = new JButton();}panel.add(label);try {img = ImageIO.read(new File(path));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}int num = img.getWidth(); // because of square,same length in width and// heightcontainer = getContentPane();imgs[0] = img.getSubimage(0, 0, num / 3, num / 3);imgs[1] = img.getSubimage(num / 3, 0, num / 3, num / 3);imgs[2] = img.getSubimage(2 * num / 3, 0, num / 3, num / 3);imgs[3] = img.getSubimage(0, num / 3, num / 3, num / 3);imgs[4] = img.getSubimage(num / 3, num / 3, num / 3, num / 3);imgs[5] = img.getSubimage(2 * num / 3, num / 3, num / 3, num / 3);imgs[6] = img.getSubimage(0, 2 * num / 3, num / 3, num / 3);imgs[7] = img.getSubimage(num / 3, 2 * num / 3, num / 3, num / 3);//instantiated the object of image iconfor(int i =0; i < 8; i++){imgicons[i] = new ImageIcon();}//set the image into image iconfor(int i = 0; i < 8; i++){imgicons[i].setImage(imgs[i]);}//assign image icon to iconfor(int i = 0; i < 8; i++){icons[i] = imgicons[i];}//instantiated the buttonfor(int i = 0;i < 8; i++){buttons[i] = new JButton(icons[i]);}//set the size of the buttonfor(int i =0; i < 8; i++){buttons[i].setSize(icons[0].getIconWidth(), icons[0].getIconHeight());}//set the size of empty panel panel.setSize(icons[0].getIconWidth(), icons[0].getIconHeight());//instantiated the button handlerButtonHandler handler = new ButtonHandler();for (int i = 0; i < 8; i++) {//add handle to buttonbuttons[i].addActionListener(handler);}//first time initial game.this.initialGame();}//initialize the first game!private void initialGame() {array[0][0] = 8;array[1][0] = 0;array[2][0] = 1;array[0][1] = 4;array[1][1] = 5;array[2][1] = 2;array[0][2] = 3;array[1][2] = 6;array[2][2] = 7;add(panel);add(buttons[0]);add(buttons[1]);add(buttons[4]);add(buttons[5]);add(buttons[2]);add(buttons[3]);add(buttons[6]);add(buttons[7]);}//button action listenerprivate class ButtonHandler implements ActionListener {public void actionPerformed(ActionEvent e) {int num = -1;for (int i = 0; i < 8; i++) {if (e.getSource() == buttons[i]) {num = i;break;}}determineLocation(num);move();Congratulation(win());if(win()){reInitializeGame();move();}}}//determine the location of the empty panelprivate void determineLocation(int num) {for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++) {if (array[j][i] == num) {determineMove(j,i);return;//we need to stop this processing,// so we return over here.}}}//determine whether it can mvoveprivate void determineMove(int j, int i) {int a, b, c, d;int temp;a = j - 1;b = j + 1;c = i - 1;d = i + 1;if (a >= 0 && array[a][i] == 8) {temp = array[a][i];array[a][i] = array[j][i];array[j][i] = temp;System.out.print("left ");} else if (b <= 2 && array[b][i] == 8) {temp = array[b][i];array[b][i] = array[j][i];array[j][i] = temp;System.out.print("right ");} else if (c >= 0 && array[j][c] == 8) {temp = array[j][c];array[j][c] = array[j][i];array[j][i] = temp;System.out.print("up ");} else if (d <= 2 && array[j][d] == 8) {temp = array[j][d];array[j][d] = array[j][i];array[j][i] = temp;System.out.print("down ");}}//execute the action of moveprivate void move() {System.out.println("can move");container.removeAll();for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {if (array[j][i] == 8) {add(panel);} elseadd(buttons[array[j][i]]);}}getContentPane().validate();}//show the congratulation dialog!private void Congratulation(boolean win) {if(win){Icon icon = new ImageIcon("/Users/huazhe/Desktop/File of Eclipse/HW1_1/src/image/Congratulation.gif");System.out.println("you win!");JOptionPane.showMessageDialog(this,"","Congratulation!",0,icon); }else{//nothing}}//if win return trueprivate boolean win() {int [][]Winarray = new int [3][3];int temp = 0;for(int i =0; i < 3; i++)for(int j =0; j < 3; j++){Winarray[j][i] = temp;temp++;}for(int i =0; i < 3; i++){for(int j =0; j < 3; j++){if(Winarray[j][i] != array[j][i]){return false;}}}return true;}//reinitialize the game.private void reInitializeGame() {ArrayList<Integer> list = new ArrayList<Integer>();Random random = new Random();Object[] value = new Object[8];//get the 9 random number( range from 0 to 9)//and make sure there is no repetition in it.while(true){int number = random.nextInt(9);if(!list.contains(number)){list.add(number);}if(list.size() == 9){break;}}value = list.toArray();for(int i = 0; i < 9; i++){System.out.println(value[i]);}int count = 0;for(int i = 0; i < 3; i++)for(int j = 0; j < 3; j++){array[j][i] = (Integer) value[count];count++;}}}

Tip: To run the command, replace img1.png in main with the path of your own image.




Java makes a flowchart of a jigsaw puzzle game. It is a simple 3*3 jigsaw puzzle game.

Use swing to construct a framework to call the APPlet and then create several variables. 3*3: Eight bind small databases.
It can be determined that when the eight buttons are replaced by buttons, the button is converted into an image, and the size of the pattern is set, it will be done if the position is true, it mainly depends on how you deploy it. First, let's look at the SWING layout.
 
Give a basic java GUI tutorial.

Java Swing
Java Swing graphic interface development and Case Study
Java API documentation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.