Friday, July 10, 2009

chess game

import java.awt.*;
import java.applet.Applet;
import java.net.URL;
import Client;

public class Chess extends Frame
{
String player1;
String player2;
public int move;

public int qizi;

Label msg=new Label("Hello, This is the WeiQi game");

public int[][] bd=new int[20][20];

public int[][] rstct=new int[20][20];

Client cl;

int movedx,movedy;

Button quit=new Button(" Quit the Game ");

Chess(String name1,String name2,int can_move,Client mcl)
{
super(name1+" V.S. "+name2);

player1=name1;
player2=name2;
move=can_move;
qizi=can_move;
cl=mcl;
resize(440,500);

movedx=-1;
movedy=-1;

setLayout(new BorderLayout());

Panel p=new Panel();
p.add(msg);
p.add(quit);

add("North",p);
}

public void oppmove(int y,int x)
{
bd[y][x]=-qizi;
move=1;
movedx=x;
movedy=y;
repaint();
};

public void checkSurround(int qi)
{
int[][] temp=new int[20][20];
for (int i=1;i<=19;i++)
for (int j=1;j<=19;j++)
if (bd[i][j]==0)
temp[i][j]=1;

int counter=999;
while (counter!=0)
{
counter=0;
for (int i=1;i<=19;i++)
for (int j=1;j<=19;j++)
if ((temp[i][j]==1) && (bd[i][j]!=-qi))
{
if ((i>1) && (temp[i-1][j]!=1)) {temp[i-1][j]=1;counter++;};
if ((i<19) && (temp[i+1][j]!=1)) {temp[i+1][j]=1;counter++;};
if ((j>1) && (temp[i][j-1]!=1)) {temp[i][j-1]=1;counter++;};
if ((j<19) && (temp[i][j+1]!=1)) {temp[i][j+1]=1;counter++;};
};
}

for (int i=1;i<=19;i++)
for (int j=1;j<=19;j++)
if ((temp[i][j]==0) && (bd[i][j]==qi))
{
bd[i][j]=0;
rstct[i][j]=1;
};
};

public void paint(Graphics g)
{
if (move==-1)
msg.setText("Waiting for opponent's move...");
else
msg.setText("It is your turn to move !");

for (int i=1;i<=19;i++)
g.drawLine(40,(i+1)*20+40,400,(i+1)*20+40);
for (int j=1;j<=19;j++)
g.drawLine((j+1)*20,80,(j+1)*20,440);

for (int i=1;i<=19;i++)
for (int j=1;j<=19;j++)
if (bd[i][j]==1)
g.fillOval((j+1)*20-10,(i+1)*20+40-10,20,20);
else
if (bd[i][j]==-1)
{
g.setColor(Color.white);
g.fillOval((j+1)*20-10,(i+1)*20+40-10,20,20);
g.setColor(Color.black);
g.drawOval((j+1)*20-10,(i+1)*20+40-10,20,20);
};

if (movedx!=-1)
{
g.setColor(Color.green);
g.drawOval((movedx+1)*20-10,
(movedy+1)*20+40-10,20,20);
g.setColor(Color.black);
};

};

public boolean mouseDown(Event e,int x,int y)
{
if (move==1)
{
x=Math.round((float) x/20)-1;
y=Math.round((float) (y-40)/20)-1;
if ((y>=1) && (y<=19) && (x>=1) && (x<=19)
&& (bd[y][x]==0) && (rstct[y][x]==0))
{
bd[y][x]=qizi;
checkSurround(-qizi);
checkSurround(qizi);
move=-1;
cl.sendRequest("Move "+(y*100+x));
repaint();
}
else
msg.setText("Cannot make that move !");
}
else
msg.setText("Please wait for your opponent ...");
return super.mouseDown(e,x,y);
};

public boolean action(Event e,Object arg)
{
if (e.target==quit)
cl.sendRequest("Endgame");
return super.action(e,arg);
};

};

No comments:

Post a Comment