![](/img/trans.png)
[英]Why does my update to a Listbox in a while loop with PySimpleGUI end up in my program hanging?
[英]Why is my program hanging
from random import *
IQ = []
row1 = ["#", "#", "#"]
row2 = ["#", "#", "#"]
row3 = ["#", "#", "#"]
board = [row1, row2, row3]
def Display_Board():
print(row1[0],"|", row1[1], "|", row1[2])
print("----------")
print(row2[0],"|", row2[1], "|", row2[2])
print("----------")
print(row3[0],"|", row3[1], "|", row3[2])
def Automated_Move(board):
while True:
RandomMove = randint(0,2)
if board[RandomMove][RandomMove] == "#":
board[RandomMove][RandomMove] = "O"
break
elif board[RandomMove][RandomMove] != "#":
pass
while True:
#print(IQ)
Display_Board()
Row = int(input("Row: ")) - 1
Col = int(input("Col: ")) - 1
if board[Row][Col] != "X" and board[Row][Col] != "O":
board[Row][Col] = "X"
IQ.append(Row)
IQ.append(Col)
elif board[Row][Col] == "X" or board[Row][Col] == "O":
print("This is already Taken")
pass
Automated_Move(board)
print("\n")
我正在尝试制作一个基于遗传算法的井字游戏,我不知道为什么它崩溃了。 我发现它在Automated_Move函数的循环中(如果有帮助的话)
您的主循环永无止境。 没有break
:
while True:
#print(IQ)
Display_Board()
Row = int(input("Row: ")) - 1
Col = int(input("Col: ")) - 1
if board[Row][Col] != "X" and board[Row][Col] != "O":
board[Row][Col] = "X"
IQ.append(Row)
IQ.append(Col)
elif board[Row][Col] == "X" or board[Row][Col] == "O":
print("This is already Taken")
pass
Automated_Move(board)
print("\n")
同样,您的Automated_Move()
的while
循环迟早也会陷入永远的循环。
def Automated_Move(board):
while True:
RandomMove = randint(0,2)
if board[RandomMove][RandomMove] == "#":
board[RandomMove][RandomMove] = "O"
break
elif board[RandomMove][RandomMove] != "#":
pass
仅在board
存在'#'
元素时(将元素更改为O
),此循环才会中断。 经过几次迭代后, board
所有(对角线)元素都将为'O'
,因此循环将永远不会退出。
一种可能的解决方案是将主循环修改为:
if any(['#' in r for r in board]):
Automated_Move(board)
else:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.