我有任何功能之外的板的列表,当我想再次玩时,我正在尝试重置板。我试着创建一个单独的函数来将电路板重置为其原始值并返回新的电路板,但我无法使其工作。我试图在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.")
这是一个范围问题。
while块内部定义的graph
是play_game
函数的本地,它正在遮蔽包级别的graph
变量,而不是更改它。
您需要在play_game
函数中将graph
定义为全局,或者(甚至更好的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.")
用以下内容替换draw_graph()
函数应该有效:
def draw_graph():
global graph
for row in graph:
for col in row:
print(col, end = '')
print()
您还可以替换代码,使图形变量在函数中定义并在函数中传递:
def draw_graph(graph):
for row in graph:
for col in row:
print(col, end = '')
print()
def play_game():
graph = [[' ', '|', ' ', '|', ' '],
['-','+', '-', '+', '-'],
[' ', '|', ' ', '|', ' '],
['-', '+', '-', '+', '-'],
[' ', '|', ' ', '|', ' ']]
again = 'yes'
while again == 'yes':
graph = [[' ', '|', ' ', '|', ' '],
['-','+', '-', '+', '-'],
[' ', '|', ' ', '|', ' '],
['-', '+', '-', '+', '-'],
[' ', '|', ' ', '|', ' ']]
draw_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.")