import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
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("显示正确图象");
AudioClip m_audioClip1,m_audioClip2;
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);
m_audioClip1=getAudioClip(getCodeBase(),"au/move.au");
m_audioClip2=getAudioClip(getCodeBase(),"au/notmove.au");
}
void prepareImage(){
imgPuzzle=getImage(getCodeBase(),"images/4.jpg");
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);
x2=rnd.nextInt(4);
y1=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){
m_audioClip2.play(); return;}
if(map[x][y]==15)return;
map[fx][fy]=map[x][y];
map[x][y]=15;
fifteen.setLocation(x,y);
drawScreen();
m_audioClip1.play();
}
});
}
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);
}
}