华容道java代码解释 华容道程序( 二 )


Cell cell[];//定义方格
Rectangle cellNull;//定义空方格区域是一个矩形类
public static int pictureID=4;//当前选择的图片代号
public MyCanvas() {
this.setLayout(null);
this.setSize(400,400);
cellNull=new Rectangle(300,300,100,100);//空方格区域在第三行每三列
cell=new Cell[16];
Icon icon;
for (int i = 0; i4; i++) {
for(int j=0;j4;j++){
icon=new ImageIcon("images/pic_"+pictureID+"_"+(i*4+j+1)+".jpg");
cell[i*4+j]=new Cell(icon);
cell[i*4+j].setLocation(j*100,i*100);
this.add(cell[i*4+j]);
}
}
this.remove(cell[15]);//移除最后一个多余的方格
}//放置9张小图片并且移调最后一张
public void reLoadPictrue(){//当选择其它图形进行拼图时,需重新加载新图片
Icon icon;
for (int i = 0; i4; i++) {
for(int j=0;j4;j++){
icon=new ImageIcon("images/pic_"+pictureID+"_"+(i*4+j+1)+".jpg");
cell[i*4+j].setIcon(icon);
}
}
}
public boolean isFinish(){//判断是否拼合成功
for(int i=0;i15;i++)
{int x=cell[i].getBounds().x;
int y=cell[i].getBounds().y;
if(y/100*4+x/100!=i)
return false;
} //end of for
return true;
}
public void Start(){//对方格进行重新排列,打乱顺序
while(cell[0].getBounds().x=100cell[0].getBounds().y=100){//当第一个方格距左上角较近时
int x=cellNull.getBounds().x;
int y=cellNull.getBounds().y;
int direction=(int)(Math.random()*4);//产生0-4 , 对应空方格的上下左右移动
if(direction==0){//空方格左移动,与左侧方格互换位置,左侧方格右移动
x-=100;
if(test(x,y)){
for(int j=0;j15;j++){
if((cell[j].getBounds().x==x)(cell[j].getBounds().y==y)){//依次寻找左侧的按钮
cell[j].move("RIGHT",100);
cellNull.setLocation(x,y);
break;//找到后跳出for循环
}
}
}
}else if(direction==1){//RIGHT
x+=100;
if(test(x,y)){
for(int j=0;j15;j++){
if((cell[j].getBounds().x==x)(cell[j].getBounds().y==y)){
cell[j].move("LEFT",100);
cellNull.setLocation(x,y);
break;
}
}
}
}else if(direction==2){//UP
y-=100;
if(test(x,y)){
for(int j=0;j15;j++){
if((cell[j].getBounds().x==x)(cell[j].getBounds().y==y)){
cell[j].move("DOWN",100);
cellNull.setLocation(x,y);
break;
}
}
}
}else{//DOWN
y+=100;
if(test(x,y)){
for(int j=0;j15;j++){
if((cell[j].getBounds().x==x)(cell[j].getBounds().y==y)){
cell[j].move("UP",100);
cellNull.setLocation(x,y);
break;
}
}
}
}
}
if(!hasAddActionListener)//如果尚未添加动作事件 , 则添加
for(int i=0;i15;i++)//为第个方格添加动作事件,这样单击按钮就能移动了
cell[i].addMouseListener(this);
hasAddActionListener=true;
}
【华容道java代码解释 华容道程序】 private boolean test(int x,int y){
if((x=0x=200)||(y=0y=200))
return true;
else
return false;
}
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e){ }
public void mouseReleased(MouseEvent e) { }
public void mousePressed(MouseEvent e) {
//方格的鼠标事件,因为用到了MyCanvas中的一些方法,因此没有在Cell类中处理鼠标事件
Cell button=(Cell)e.getSource();
int x1=button.getBounds().x;//得到所单击方格的坐标
int y1=button.getBounds().y;
int x2=cellNull.getBounds().x;//得到空方格的坐标
int y2=cellNull.getBounds().y;
if(x1==x2y1-y2==100)//进行比较,如果满足条件则进行交换

推荐阅读