Java GUI 基礎 Eight Puzzle (拼圖遊戲),eightpuzzle

來源:互聯網
上載者:User

Java GUI 基礎 Eight Puzzle (拼圖遊戲),eightpuzzle

很簡單使用java GUI 製作一個簡單的拼圖遊戲

// 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: 想要運行時,將main 中的 img1.png 換成 你自己圖片的路徑。




java製作拼圖遊戲的流程圖,是個簡單的3*3的拼圖遊戲

用swing先構建一個架構 調用APPlet然後建幾個變數就行了 3*3就是需要8個 綁定個小資料庫
判定下當這8個先用按鈕代替 ,最後再把按鈕整成圖片就行了 ,還有格局設定大小,都是這個位置是為真就完了,主要還是看你怎麼布局了,先看看SWING的那個布局,就這個思想
 
給個java GUI 基礎教程吧

《Java Swing》
《Java Swing圖形介面開發與案例詳解》
Java API 文檔
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.