RandomMove 方法 Tic Tac Toe 不起作用
我正在开发一款井字游戏,允许用户与计算机对战。当用户选择板上的按钮时,人工智能将检测是否存在可能的三连击。如果没有检测到威胁,计算机将在棋盘上随机选择一个点进行移动。
然而,我的问题是,当我做出某个动作时,计算机有时会下一个动作,有时会被跳过。我想知道如何解决这个问题,我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据安德鲁·汤普森的答案,尝试
用这个替换
Working off of Andrew Thompson's answer, try replacing
with this
通过创建一个新的
每次调用该方法时(在潜在的递归方法中),代码都会“阻塞”。原因是
Random
实例以当前时间(以毫秒为单位)作为种子,此后它将生成的数字序列被“一成不变”。该方法将在一毫秒内完成多次,创建许多Random
对象。相反,(命名不佳)
x
应该声明为类属性并仅创建一次。By creating a new
Random
every time the method is called (in a potentially recursive method), the code will 'choke'. The reason is that theRandom
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 manyRandom
objects.Instead, the (poorly named)
x
should be declared as a class attribute and created once only.