【发布时间】:2020-03-29 18:09:01
【问题描述】:
我正在创建井字游戏,但脚本中的 move_base 函数不起作用。我以前见过这种类型的 if 语句,但我不知道为什么该函数不起作用。没有错误,但该函数不会更新 num_word 或移动。我没有很多python经验,所以我不知道我做错了什么。我会为游戏添加更多功能,但我不能,因为它的基本部分不起作用。我还没有看到任何其他地方告诉我如何解决这个问题。
#tic tac toe game
#global variables
game_over = False
#game script
def game():
#game variables
#positions on the board
one = '1'
two = '2'
three = '3'
four = '4'
five = '5'
six = '6'
seven = '7'
eight = '8'
nine = '9'
positions = [one, two, three, four, five, six, seven, eight, nine]
num_chosen = ''
#moves in the game
moves = 0
#prints board
def board():
print(f'{one}|{two}|{three}')
print(f'{four}|{five}|{six}')
print(f'{seven}|{eight}|{nine}')
#how to check who won
def check_win_base(xo, num1, num2, num3):
if num1 == xo and num2 == xo and num3 == xo:
if(xo == 'x'):
print('x player wins')
game_over = True
elif(xo == 'o'):
print('o player wins')
game_over = True
#check_win_base applied to all numbers
def check_win(xo):
check_win_base(xo, one, two, three)
check_win_base(xo, four, five, six)
check_win_base(xo, seven, eight, nine)
check_win_base(xo, one, four, seven)
check_win_base(xo, two, five, eight)
check_win_base(xo, three, six, nine)
check_win_base(xo, one, five, nine)
check_win_base(xo, three, five, seven)
#checks if game is a draw
def check_draw():
if moves == 9:
print('The game is a draw')
game_over = True
#how to pick a square
def move_base(xo, num_word, num):
if num_chosen == num:
num_word = xo
moves += 1
#move_base applied to all numbers
def move(xo):
move_base(xo, one, 1)
move_base(xo, two, 2)
move_base(xo, three, 3)
move_base(xo, four, 4)
move_base(xo, five, 5)
move_base(xo, six, 6)
move_base(xo, seven, 7)
move_base(xo, eight, 8)
move_base(xo, nine, 9)
#all the required functions put together
def turn(xo):
board()
print(f'{xo} move')
num_chosen = int(input())
move(xo)
check_win(xo)
check_draw()
turn('x')
turn('o')
turn('x')
turn('o')
turn('x')
turn('o')
turn('x')
turn('o')
turn('x')
#checks if game is over or not
if game_over == False:
game()
else:
print('Game Over')
【问题讨论】:
-
我在代码中看到了很多问题。大多数情况下,您正在定义与外部范围中的变量同名的新变量 - 可能是因为您认为这会更改外部范围中的值,但事实并非如此。在某些情况下,您还会将值重新分配给参数变量。这也无济于事——这可能不是你所假设的。
-
即使您在每个内部函数中修改了每个 var 的
nonlocal var,您的move_base()也不会起作用,因为它会尝试修改其参数num_word,而这将不起作用。
标签: python python-3.x function if-statement tic-tac-toe