RandomMove 方法 Tic Tac Toe 不起作用

发布于 2024-12-28 03:36:04 字数 681 浏览 1 评论 0原文

我正在开发一款井字游戏,允许用户与计算机对战。当用户选择板上的按钮时,人工智能将检测是否存在可能的三连击。如果没有检测到威胁,计算机将在棋盘上随机选择一个点进行移动。

然而,我的问题是,当我做出某个动作时,计算机有时会下一个动作,有时会被跳过。我想知道如何解决这个问题,我的 randomMove() 方法如下所示。

这种情况是否需要递归方法(我的老师简短地告诉我这可能是必要的)或其他方法?如果是递归的话,能解释一下吗?感谢您的帮助!

public void RandomMove()
{
    Random x = new Random();
    int y = 1 + x.nextInt(9);
    if (buttons[y].getText().equals("O") || buttons[y].getText().equals("X")) {
        RandomMove();
    }
    else {
        buttons[y].setText("O");
        buttons[y].setEnabled(false);
    }
}

更具体地说,我有时会收到此错误:

线程“AWT-EventQueue-0”java.lang.StackOverflowError 中出现异常

I am working on creating a tic tac toe game that allows the user to play against a computer. When the user selects a button on the board, the AI will detect if there is a possible three combo. If there is no threat detected, than the computer will pick a spot randomly on the board to move.

However, my problem is when I make a certain move, the computer sometimes places a move and sometimes get skipped. I was wondering how to fix this, my randomMove() method is displayed below.

Would this situation call for a recursive method (my teacher briefly told me this might be necessary) or otherwise? If it is recursive, can you explain it? Thanks for any help!

public void RandomMove()
{
    Random x = new Random();
    int y = 1 + x.nextInt(9);
    if (buttons[y].getText().equals("O") || buttons[y].getText().equals("X")) {
        RandomMove();
    }
    else {
        buttons[y].setText("O");
        buttons[y].setEnabled(false);
    }
}

More specifically I get this error sometimes:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

本宫微胖 2025-01-04 03:36:04

根据安德鲁·汤普森的答案,尝试

Random x = new Random();
int y = 1 + x.nextInt(9);

用这个替换

int y = (int)(Math.random() * 9);

Working off of Andrew Thompson's answer, try replacing

Random x = new Random();
int y = 1 + x.nextInt(9);

with this

int y = (int)(Math.random() * 9);
樱花落人离去 2025-01-04 03:36:04
Random x = new Random();

By creating a new Random every time the method is called (in a potentially recursive method), the code will 'choke'. The reason is that the Random instance is seeded with the current time in milliseconds, thereafter the sequence of numbers it will produce is 'set in stone'. The method will complete many times within a single millisecond, creating many Random objects.

Instead, the (poorly named) x should be declared as a class attribute and created once only.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文