python - TicTacToe 再次播放时如何重置棋盘?
问题描述
我在任何功能之外都有我的板子列表,当我想再次玩时,我正在尝试重置板子。我尝试创建一个单独的函数来将板重置为其原始值并返回新板,但我无法让它工作。我试图在 play_again 函数中将棋盘重置为空白,但是当我再次选择播放时它仍然不会将棋盘重置为空白。我还尝试制作一个单独的函数来使用深拷贝操作符复制棋盘并在游戏开始时使用,尽管我不确定如何正确实现它。
graph = [[' ', '|', ' ', '|', ' '],
['-','+', '-', '+', '-'],
[' ', '|', ' ', '|', ' '],
['-', '+', '-', '+', '-'],
[' ', '|', ' ', '|', ' ']]
def draw_graph():
for row in graph:
for col in row:
print(col, end = '')
print()
def play_game():
again = 'yes'
while again == 'yes':
graph = [[' ', '|', ' ', '|', ' '],
['-','+', '-', '+', '-'],
[' ', '|', ' ', '|', ' '],
['-', '+', '-', '+', '-'],
[' ', '|', ' ', '|', ' ']]
draw_graph()
won = False
current_player = 'player1'
while not won:
place_spot(current_player)
draw_graph()
won = check_win()
current_player = flip_player(current_player)
again = input("Do you want to play again? (yes/no) ")
print("Thank you for playing.")
解决方案
这是一个范围问题。
graph
while 块内的定义是函数的局部play_game
变量,它隐藏包级graph
变量,而不是更改它。
您要么需要graph
在函数中定义为全局play_game
,要么(更好的 IMO)删除包级graph
变量并将其graph
作为参数传递给draw_graph
。
所以这就是我将如何重写你的程序:
def draw_graph(graph):
for row in graph:
for col in row:
print(col, end = '')
print()
def play_game():
again = 'yes'
while again == 'yes':
graph = [[' ', '|', ' ', '|', ' '],
['-','+', '-', '+', '-'],
[' ', '|', ' ', '|', ' '],
['-', '+', '-', '+', '-'],
[' ', '|', ' ', '|', ' ']]
draw_graph(graph)
won = False
current_player = 'player1'
while not won:
place_spot(current_player)
draw_graph(graph)
won = check_win()
current_player = flip_player(current_player)
again = input("Do you want to play again? (yes/no) ")
print("Thank you for playing.")