码迷,mamicode.com
首页 > 编程语言 > 详细

Java GUI 基础 Eight Puzzle (拼图游戏)

时间:2014-10-06 12:21:00      阅读:775      评论:0      收藏:0      [点我收藏+]

标签:des   style   io   os   使用   ar   java   for   sp   

很简单使用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 block
			e.printStackTrace();
		}

		int num = img.getWidth(); // because of square,same length in width and
									// height

		container = 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 icon
		for(int i =0; i < 8; i++)
		{
			imgicons[i] = new ImageIcon();
		}

		//set the image into image icon
		for(int i = 0; i < 8; i++)
		{
			imgicons[i].setImage(imgs[i]);
		}

		//assign image icon to icon
		for(int i = 0; i < 8; i++)
		{
			icons[i] = imgicons[i];
		}
		
		//instantiated the button
		for(int i = 0;i < 8; i++)
		{
			buttons[i] = new JButton(icons[i]);
		}
		
		//set the size of the button
		for(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 handler
		ButtonHandler handler = new ButtonHandler();
		for (int i = 0; i < 8; i++) {
			//add handle to button
			buttons[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 listener
	private 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 panel
	private 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 mvove
	private 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 move
	private 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);
				} else
					add(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 true
	private 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 GUI 基础 Eight Puzzle (拼图游戏)

标签:des   style   io   os   使用   ar   java   for   sp   

原文地址:http://blog.csdn.net/ytdxyhz/article/details/39826209

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!