【发布时间】:2021-11-14 19:48:06
【问题描述】:
我想我的问题与全局范围有关。我不确定我不理解的是什么。我在第 6 行的全局范围中定义了 computer_symbol。 那么第 18 行的 choose_symbol 函数应该使 computer_symbol 成为用户没有选择的任何东西。 然后我在第 30 行调用该函数。 但是,当我尝试使用第 45 行中的变量并测试我的代码时,我发现 computer_symbol 仍然等于仅用作占位符的“无”值。
import random
board_locations = [0, 1, 2, 3, 4, 5, 6, 7, 8]
computer_symbol = 'nothing'
def draw_board():
print(' | | ')
print(f'_{board_locations[0]}_|_{board_locations[1]}_|_{board_locations[2]}_')
print(' | | ')
print(f'_{board_locations[3]}_|_{board_locations[4]}_|_{board_locations[5]}_')
print(' | | ')
print(f' {board_locations[6]} | {board_locations[7]} | {board_locations[8]} ')
print(' | | ')
def choose_symbol(user_symbol):
if user_symbol == 'X':
computer_symbol = 'O'
else:
computer_symbol = 'X'
return computer_symbol
draw_board()
user_symbol = input("Would you like to be 'X' or 'O': ")
choose_symbol(user_symbol)
game = True
while game:
draw_board()
chosen_location = int(input('Choose the location you want to move on the board: '))
if chosen_location in board_locations:
board_locations.pop(chosen_location)
board_locations.insert(chosen_location, user_symbol)
draw_board()
computer_choice = random.choice(board_locations)
board_locations.pop(computer_choice)
board_locations.insert(computer_choice, computer_symbol)
起初,我什至没有 computer_symbol 变量,因为我认为我可以在函数 choose_symbol() 中做到这一点,但程序不喜欢这样,因为尚未定义 computer_symbol。
【问题讨论】:
标签: python tic-tac-toe global-scope