我正在玩井字游戏。我已经完成了,但是如果用户要求,我希望它再次循环。问题是当我将其放在主要功能下并全部缩进时。某些变量不再定义,因此不起作用!当它不在main()函数下时,它们就会执行。这些错误不会发生。有谁知道如何在不使用函数的情况下循环程序,或帮助修复我的代码。例如:
def main():
#My code here
#Ouput:
File "CandT.py", line 205, in <module>
main()
File "CandT.py", line 203, in main
run()
File "CandT.py", line 188, in run
runX()
File "CandT.py", line 163, in runX
askX()
File "CandT.py", line 59, in askX
check_stringX(x = s1)
NameError: name 's1' is not defined
完整代码在这里:https://pastebin.com/iGcqGkRe
答案 0 :(得分:0)
像这样创建一个while
循环。
def run()
clear()
#check_win() should return true if there is a winner or false if not
while(check_win()==False): #if there is nobody win, continue this loop
if turn == 0: # X's move
runX()
turn = 1 # the next turn will be O's
elif turn == 1: # O's move
runO()
turn = 0 # the next turn will be O's
#here after the loop, we check for the winner
if(turn == 0):
winner = O #because the last move is O's
else:
winner = X
def clear():
#reset all variables here
if __name__ == "__main__": #maybe you miss this line
while(True):
play_again = int(input("play again? 1: OK, 0: No"))
if play_again == 1:
run()
else:
break