java - 如果程序仅通过 doClick() 进行交互,则 JFrame 永远不会呈现;
问题描述
我正在使用 Swing 编写 Othello 游戏,这是通用代码:(该片段不包括游戏结束/同一玩家再次出现的情况,这只是基本的游戏循环。)
视图/控制器:
public class OthelloGUI extends JFrame {
JSquare[][] board;
final int BOARD_SIZE = 8;
OthelloModel model;
public OthelloGUI(OthelloModel m) {
model = m;
/* Window size, etc... */
setLayout(new GridLayout(BOARD_SIZE, BOARD_SIZE));
//add 8x8 buttons to GUI
ActionListener ml = new MoveListener();
board = new JSquare[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
getContentPane.add(board[i][j] = new JSquare(new Point(i, j)));
board[i][j].addActionListener(ml);
}
}
update();
}
void update() {
//update GUI to reflect last move
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
//changes the JButton's text based on who owns it on the model's board
board[i][j].setText(model.getOwner(i, j).view());
}
}
//best place (I think) to have AI move is after the last move is processed
if (model.getCurrentPlayerType() == PlayerType.AI) {
//Computer player finds its next move, and clicks that button
int[] bestMove = GreedyAI.findMove(model);
board[bestMove[0]][bestMove[1]].doCLick();
}
}
static class JSquare extends JButton {
java.awt.Point p;
JSquare (Point p) {this.p = p;}
}
class MoveListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JSquare sq = (JSquare) e.getSource();
//places the piece on the model's "board" and flips all applicable pieces
int result = model.placeDisk(s.p, model.getCurrentColor());
if (result == 0) {//move executes successfully
update();
}
//otherwise... (illegal move, game end, same player again, etc...)
}
}
}
enum Owner {
NONE, BLACK, WHITE;
public String view() {
return this == BLACK ? "B" : this == WHITE ? "W" : ""
}
}
如果我开始游戏,这段代码执行得很好,但是,如果我开始游戏,Human v Human
则GUI 永远不会呈现。我得到了游戏设置的弹出框,以及游戏结束和谁赢了的弹出框,但是带有棋盘的主要内容从不渲染,所以我看不到 AI 做了什么动作。
有什么想法/建议吗?Human v AI
AI v AI
ContentPane
解决方案
人工智能是自动化的。人类是..不是。
- 当人类在扮演人类时,代码必须等待人类完成每个回合。它必须是事件驱动的。
- 当人类扮演人工智能时,人工智能是自动化的,但代码仍必须等待人类的事件。
- 但是当 AI 播放 AI 时,整个过程都留给了代码,这会导致 EDT 被阻塞。
不要阻塞 EDT(事件调度线程)。发生这种情况时,GUI 将“冻结”。有关详细信息和修复,请参阅Swing 中的并发。
推荐阅读
- linux - 我想在运行命令时获得变量的输出,但它都被合并到一行中。我应该怎么办?
- sql - af:query 中的多选 LOV
- java - Selenium webdriver - 无法在模式对话框中找到元素
- node.js - 使用 async/await 的 mongodb 连接 - NodeJS
- python - 如何创建带有图片的博客文章类型的表单?不断出现错误:NameError:未定义名称'blog_post_id'
- php - 从 Laravel 中的 Mysql Pivot 表中获取列并返回 JSON 对象
- eclipse-cdt - 如何以编程方式设置 Eclipse CDT 配置构建目录?
- c# - 是否还有 Microsoft Authenticator 开发 API?我该如何使用它?
- php - 如何在 echo 部分插入 php 代码。WordPress
- react-native - 无法使用 AWS S3 使用 react native 上传或获取任何文件