java拼图_java拼图

packagejava拼图;importjava.awt.event.MouseEvent;importjava.awt.event.MouseListener;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.IOException;importjava.util.Random;importjavax.imageio.ImageIO;importjavax.swing.Icon;importjavax.swing.ImageIcon;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjava拼图.Cell.Direction;public class GamePanel extends JPanel implementsMouseListener{

Icon icon=null;private Cell[] cells=new Cell[9];private Cell cellBlank=null;publicGamePanel() {super();

setLayout(null);

init();

}public voidinit() {int x=0,y=0,w=50,h=50;

BufferedImage src=null;

BufferedImage newpic=null;try{

src=ImageIO.read(new File("images\\link.jpg"));

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}int num=0;//图片序号

Cell cell=null;//单元图片对象

for(int i=0;i<3;i++) {//分割图片时的行

for(int j=0;j<3;j++) {//列

num=i*3+j;

x=j*100;

y=i*100;

newpic=src.getSubimage(x, y, w, h);if(num+1==9)

icon=new ImageIcon("images\\图片9.png");elseicon=newImageIcon(newpic);

cell=newCell(icon,num);

cell.setLocation(j*cell.IMAGEWIDTH,i*Cell.IMAGEHEIGHT);

cells[num]=cell;

}

}for(int i=0;i

}

}//对图片进行随机排序

public voidrandom() {

Random random=newRandom();intm,n,x,y;if(cellBlank==null) {

cellBlank=cells[cells.length-1];for(int i=0;i

cells[i].addMouseListener(this);

}

}

}for(int i=0;i

m=random.nextInt(cells.length);

n=random.nextInt(cells.length);

x=cells[m].getX();

y=cells[m].getY();

cells[m].setLocation(cells[n].getX(),cells[n].getY());

cells[n].setLocation(x,y);

}

}

@Overridepublic voidmouseClicked(MouseEvent e) {//TODO Auto-generated method stub

Cell cell=(Cell)e.getSource();//获取触发事件的对象

int x=cells[8].getX();int y=cells[8].getY();if((x-cell.getX())==Cell.IMAGEWIDTH&&cell.getY()==y) {//左右移动

cell.move(Direction.RIGHT);

cellBlank.move(Direction.LEFT);

}if((x-cell.getX())==-Cell.IMAGEWIDTH&&cell.getY()==y) {

cell.move(Direction.LEFT);

cellBlank.move(Direction.RIGHT);

}if((cell.getX())==x&&cell.getY()-y==Cell.IMAGEHEIGHT) {//上下移动

cell.move(Direction.UP);

cellBlank.move(Direction.DOWN);

}if((cell.getX())==x&&cell.getY()-y==-Cell.IMAGEHEIGHT) {//上下移动

cell.move(Direction.DOWN);

cellBlank.move(Direction.UP);

}//判断是否成功

if(isSuccess()) {int i=JOptionPane.showConfirmDialog(this,"win!Do you want play again?","win",JOptionPane.YES_NO_OPTION);if(i==JOptionPane.YES_OPTION) {

random();//重新开始一局

}

}

}

@Overridepublic voidmouseEntered(MouseEvent e) {//TODO Auto-generated method stub

}

@Overridepublic voidmouseExited(MouseEvent e) {//TODO Auto-generated method stub

}

@Overridepublic voidmousePressed(MouseEvent e) {//TODO Auto-generated method stub

}

@Overridepublic voidmouseReleased(MouseEvent e) {//TODO Auto-generated method stub

}public booleanisSuccess() {for(int i=0;i

}

}

}return true;

}

}

你可能感兴趣的:(java拼图)