下面是拼图游戏的代码.为了降低理解的程度,变量与方法的访问控制都省掉了.
PPuzzle.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class PPuzzle extends Applet {
Image imgpuzzle,buff;
Point fifteen=new Point(3,3);
int map[][]={{0,4,8,12},{1,5,9,13},{2,6,10,14},{3,7,11,15}};
int sx,sy;
Canvas screen;
Graphics gs,gb;
boolean running=false;
Button bStart=new Button("新游戏");
Button bSee=new Button("显示正确的图像");
public void init(){
prepareImage();
sx=imgpuzzle.getWidth(this)/4;
sy=imgpuzzle.getHeight(this)/4;
setBackground(Color.blue);
initScreen();
initButtons();
add(screen);
add(bStart);
add(bSee);
}
void prepareImage(){
imgpuzzle=getImage(getCodeBase(),"images/baby.gif");
MediaTracker mt =new MediaTracker(this);
mt.addImage(imgpuzzle,0);
try{
mt.waitForAll();
}catch(Exception e){}
buff=createImage(imgpuzzle.getWidth(this),imgpuzzle.getHeight(this));
gb=buff.getGraphics();
}
void initMap(){
java.util.Random rnd=new java.util.Random();
int temp,x1,y1,x2,y2;
for(int i=0;i<100;i++){
x1=rnd.nextInt(4);
y1=rnd.nextInt(4);
x2=rnd.nextInt(4);
y2=rnd.nextInt(4);
temp=map[x1][y1];
map[x1][y1]=map[x2][y2];
map[x2][y2]=temp;
}
outer:for(int j=0;j<4;j++)
for(int i=0;i<4;i++)
if(map[i][j]==15){
fifteen.setLocation(i,j);
break outer;
}
}
void initScreen(){
screen=new Canvas(){
public void paint(Graphics g){
if(gs==null) gs=getGraphics();
if(running)
drawScreen();
else
g.drawImage(imgpuzzle,0,0,this);
}
};
screen.setSize(imgpuzzle.getWidth(this),imgpuzzle.getHeight(this));
screen.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me){
if(!running) return;
int x=me.getX()/sx,y=me.getY()/sy;
int fx=(int)fifteen.getX(),fy=(int)fifteen.getY();
if(Math.abs(fx-x)+Math.abs(fy-y)>=2) return;
if(map[x][y]==15) return;
map[fx][fy]=map[x][y];
map[x][y]=15;
drawScreen();
}
});
}
void initButtons(){
bStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
initMap();
drawScreen();
running=true;
bSee.setLabel("显示正确的图像");
}
});
bSee.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(bSee.getLabel().equals("继续游戏")){
drawScreen();
bSee.setLabel("显示正确的图像");
}
else{
gs.drawImage(imgpuzzle, 0, 0, screen);
bSee.setLabel("继续游戏");
}
}
});
}
void drawScreen(){
gb.clearRect(0,0,sx*4,sy*4);
for(int j=0;j<4;j++)
for(int i=0;i<4;i++)
if(map[i][j]!=15) drawSegment(map[i][j],i,j);
gs.drawImage(buff,0,0,screen);
}
void drawSegment(int seg,int x,int y){
int dx=seg%4*sx,dy=seg/4*sy;
gb.drawImage(imgpuzzle,x*sx,y*sy,x*sx+sx-1,y*sy+sy-1,dx,dy,dx+sx-1,dy+sy-1,screen);
}
} 下面是Html的代码
<Htm>
<Body>
<Center>
<Applet code="PPuzzle.class" width=300 height=300 >
</Applet>
</Center>
</Body>
</Htm>
方法prepareImage()中的imgpuzzle=getImage(getCodeBase(),"images/baby.gif");images/baby.gif可以改成你自己文件中的图片.