Java GUI Basics Eight Puzzle (puzzle game)

Source: Internet
Author: User

Easy to use Java GUI to make 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) {Ico n 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 of 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 Jeightpuz Zleframe extends JFrame {/** * *///private static final long serialversionuid = 1l;private bufferedimage img;private Buff Eredimage [] IMGs = new Bufferedimage[8];p rivate jbutton[] buttons = new Jbutton[8];p rivate imageicon [] imgicons = new Im AGEICON[8]; Private Icon [] icons = new Icon[8];p rivate GridLayout layout;private JPanel panel;private ContainerContainer;private JLabel label;private int[][] array = new Int[3][3];p ublic jeightpuzzleframe (string title, string path) { Super (title); System.out.println (This.getlocation ()); container = new container (); container = Getcontentpane ();p anel = 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.prin Tstacktrace ();} 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 t He 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].geticonheigh T ());} Set the size of the 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 (but Add (Buttons[1]), add (Buttons[4]), add (Buttons[5]), add (Buttons[2]), add (Buttons[3]), add (Buttons[6]), add (tons[0); 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 &l T 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/huaz He/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 t Here are 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: When you want to run, replace the img1.png in main with the path to your own picture.



Java GUI Basics Eight Puzzle (puzzle game)

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.