更新内容:悔棋功能,部分代码优化。
一、创建一个Chess类
用于方便存储棋子的状态和坐标
package gobangv3;
//存储棋子的状态和坐标
public class Chess {
int chessflag;
int r;
int c;
public Chess(int chessflag, int r, int c) {
this.chessflag = chessflag;
this.r = r;
this.c = c;
}
}
二、悔棋功能的添加
1、在鼠标监听器部分的mousePressed中创建一个新的Chess对象
//创建一个新的Chess对象并将其引用赋给变量achess
Chess achess = new Chess(chessstatus, r, c);
//将新创建的chess对象achess存入chessList
chessList[chessSize] = achess;
//反映棋盘上新增加的棋子
chessSize++;
2、在鼠标监听器部分的actionPerformed中添加点击悔棋按钮后的执行代码
else if (ac.equals("悔棋")) {
//首先判断有几个棋子
if (chessSize > 0) {
//获取最后一个棋子
Chess achess = chessList[chessSize - 1];
//将悔棋去除的棋子位置设置为无棋子
chess[achess.r][achess.c] = 0;
//表明这个位置现在没有棋子对象
chessList[chessSize - 1] = null;
//确保下次落子棋子的颜色正确
chessstatus = achess.chessflag;
//去除悔棋的棋子的数量
chessSize--;
//重绘棋盘
drawChessPad();
//按照悔棋后的棋子位置画出棋子
drawChess();
}
}
三、优化部分
绘制棋子和绘制棋盘的功能的使用较为频繁,故将其写为单独的方法,后续使用时秩序调用即可。
//画棋盘
public void drawChessPad(){
g.setColor(new Color(18, 253, 0, 255));
g.fillRect(X - SIZE / 2, Y - SIZE / 2, (COL + 1) * SIZE, (ROW + 1) * SIZE);
g.setColor(new Color(0xFF070707, true));
for (int i = 0; i <= COL; i++) {
g.drawLine(X, Y + i * SIZE, X + COL * SIZE, Y + i * SIZE);
g.drawLine(X + i * SIZE, Y, X + i * SIZE, Y + ROW * SIZE);
}
}
//画棋子
public void drawChess(){
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
int cn = chess[i][j];
if (cn != 0){
if (cn == 1){
g.setColor(Color.BLACK);
}else if (cn == 2){
g.setColor(Color.WHITE);
}
int chessX = j * SIZE + X - SIZE / 2;
int chessY = i * SIZE + Y - SIZE / 2;
g.fillOval(chessX,chessY,SIZE,SIZE);
}
}
}
}