怎么修改这段代码实现人机对弈功能: public void actionPerformedActionEvent e button = egetActionCommand; 按钮内容对应鼠标点击信息 switch button case 开始点击开始 clean; 清空棋盘 coun
要实现人机对弈功能,需要在鼠标点击事件中添加判断条件,如果当前是人机模式,则人类下棋后,调用AI方法,让电脑下棋。
修改的代码如下:
public void mouseClicked (MouseEvent e){
//省略前面的代码
//下棋前添加判断条件:是否按了“开始”
if (start == true) {
// 判断棋子是否会越出棋盘界
if (0 <= x1 && x1 <= 14 && 0 <= y1 && y1 <= 14) {
// 判断只有空位置才能下棋
if (chessArr[y1][x1] == 0) {
// 加for循环是为了给棋子添加3D效果
for (int i = 0; i < 50; i++) {
// count为双数下黑棋,为单数下白棋
//下完黑棋在数组中存入1,白棋存入-1
if (count % 2 == 0) {
color = new Color(5 * i, 5 * i, 5 * i);// 3d效果
g.setColor(color);// 设置画笔颜色
g.fillOval(x1 * size + x0 + i / 2 - 25, y1 * size + y0 + i / 2 - 25, 50 - i, 50 - i);
chessArr[y1][x1] = 1;// 记录棋盘上每颗棋子的颜色(实际是记入1、-1)
} else {
color = new Color(155 + 2 * i, 155 + 2 * i, 155 + 2 * i);
g.setColor(color);
g.fillOval(x1 * size + x0 + i / 2 - 25, y1 * size + y0 + i / 2 - 25, 50 - i, 50 - i);
chessArr[y1][x1] = -1;
}
}
ChessR chess = new ChessR(x1,y1,color);//创建棋子对象存入棋子数值
chessB[count] = chess;//以count为下标存入棋子对象
count++;//每下完一颗棋,计数器加1
checkwin();
if (mode == "人机" && !end) { // 如果当前是人机模式且游戏没有结束
int[] bestMove = AI(chessArr, -1); // 计算电脑最优解
x1 = bestMove[1];
y1 = bestMove[0];
for (int i = 0; i < 50; i++) {
color = new Color(155 + 2 * i, 155 + 2 * i, 155 + 2 * i);
g.setColor(color);
g.fillOval(x1 * size + x0 + i / 2 - 25, y1 * size + y0 + i / 2 - 25, 50 - i, 50 - i);
chessArr[y1][x1] = -1;
}
ChessR chess2 = new ChessR(x1, y1, color);
chessB[count] = chess2;
count++;
checkwin();
}
}
} else {
System.out.print("超出棋盘边界");
}
}
}
其中,需要在类中添加一个变量mode,表示当前游戏模式(人人对战或人机模式),并且在初始化方法中为该变量赋值。
private String mode = "人人"; // 当前游戏模式,默认为人人对战
public void init() throws Exception { // 省略前面的代码
// 添加下拉菜单,选择游戏模式
JComboBox comboBox = new JComboBox(new String[]{"人人", "人机"});
comboBox.setBounds(600, 10, 80, 30);
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mode = (String) comboBox.getSelectedItem();
}
});
this.add(comboBox);
// 省略后面的代码
}
此外,还需要修改AI方法,将其从原来的返回int类型改为返回int[]类型,该数组表示最优解坐标。在鼠标点击事件中调用AI方法,获取电脑下棋的坐标,并且在棋盘上画出电脑的棋子
原文地址: https://www.cveoy.top/t/topic/hoVJ 著作权归作者所有。请勿转载和采集!