一、前言:这两周实习周自己完成了一个五子棋小游戏,独立完成的过程中收获还是很多的,下面我就为搭建介绍一些五子棋的一些主要功能的实现:
二、五子棋的主要功能实现:
首先要实现五子棋的功能首先要让期实现MouseListener这个接口,让界面具有鼠标监听的功能才能实现落子的功能
public class Canvas extends JPanel implements MouseListener {}
(1)绘画棋盘和鼠标点击时的落子
public void paint(Graphics g) {
g.setColor(new Color(0xFFCC33));//确定画笔的颜色
g.fillRect(0, 0, getWidth(), getHeight());//将棋盘全图成黄色
h = this.getHeight() / 21;//把棋盘的高分成均匀的21份
g.setColor(Color.BLACK);//换画笔
for(int i=0;i<19;i++){
g.drawLine(h, h+i*h, 19*h, h+i*h);
g.drawLine(h+h*i, h, h+h*i, 19*h);//画横线
}
for(int r = 0;r < 19 ;r++ ){
for(int c =0;c<19;c++){
int x = (c+1)*h - h/2;
int y = (r+1)*h -h/2;//画竖线
if(chess[r][c] == BLACK){//判断落子的种类
g.setColor(Color.BLACK);//换成黑画笔
g.fillOval(x, y, h, h);//画上黑棋子
}else if(chess[r][c] == WHITE){//判断落子的种类
g.setColor(Color.WHITE);//换成白画笔
g.fillOval(x, y, h, h);//画上白子
}
}
这其中的getWidth()和getHeight()方法获得的是父类中的长和宽
(2)判断是否胜利
public boolean checkSuccess(int r,int c,int type){
//判断竖着的棋子是否满足同色为5个的标准
int num = 1;
for(int i = c-1;i>=0;i--){
if(chess[r][i] == type) num++;
else break;
}
for(int i = c+1;i<19;i++){
if(chess[r][i] == type) num++;
else break;
}
if(num >=5){
JOptionPane.showMessageDialog(null, NAMES[type]+"胜!");
return true;
}
//判断横着的棋子是否满足同色为5个的标准
num =1;
for(int i = r-1;i>=0;i--){
if(chess[i][c] == type) num++;
else break;
}
for(int i=r+1;i<19;i++){
if(chess[i][c] == type )num++;
else break;
}
if(num >=5){
JOptionPane.showMessageDialog(null, NAMES[type]+"胜!");
return true;
}
//判断东北方向的棋子是否满足同色为5个的标准
num = 1;
int ri = r +1;
int ci = c-1;
while(ri<19 && ci >=0){
if(chess[ri][ci] == type) num++;
else break;
ri ++;
ci --;
}
ri = r - 1;
ci = c + 1;
while(ri>=0 && ci <19){
if(chess[ri][ci] == type) num++;
else break;
ri -- ;
ci ++ ;
}
if(num >=5){
JOptionPane.showMessageDialog(null, NAMES[type]+"胜!");
return true;
}
//判断西南方向的棋子是否满足同色为5个的标准
num = 1;
ri = r -1;
ci = c -1;
while(ri >= 0 && ci >=0){
if(chess[ri][ci] == type) num++;
else break;
ri -- ;
ci --;
}
ri = r+1;
ci = c+1;
while(ri < 19 && ci < 19){
if(chess[ri][ci] == type) num++;
else break;
ri++;
ci++;
}
if(num >=5){
JOptionPane.showMessageDialog(null, NAMES[type]+"胜!");
return true;
}
return false;
}
(3)判断其中能否落子
这个因为我在前面提前设置的有一个19x19的数组来储存落子,如下:
final static int WHITE = 2; final static int BLACK = 1; final static int EMPTY = 0; int[][] chess = new int[19][19];
if(chess[r][c] != EMPTY){//不为0的可以落子(EMPTY=0)
return;
三、总结:
这次写五子棋的体会良多,也是第一次自己写游戏,中间遇到了许多的困得,但最后在自己的努力下克服了,最终完成了这个游戏,内心还是非常开心的,有满满的成就感。