0

因此,我正在重新设计我最近创建的井字游戏,以拥有更简洁和优化的代码。但是,当任一玩家在空白处移动时,我在使用 OR 语句时遇到了一些问题

(一些快速的旁注:在我的代码中,user_team 和 computer_team 等于 'X' 或 'O' 取决于玩家选择的团队,并且板上的每个空间默认等于 ' ')

如果我这样运行代码:

move = int(raw_input('Where would you like to move? (Enter a number from 1-9) \n'))
if 0 < move < 10:
    if board[move] == user_team:
        print ('That space is already taken by a player.'
               'Please select an open space \n')
        user_turn()
    elif board[move] == computer_team:
        print ('That space is already taken by a player.'
               'Please select an open space \n')
    else:
        board[move] = computer_team
        print
else:
    print ('That is not a valid move. Please try again. \n')
    computer_turn()

上面的代码完全按照预期运行,并将玩家移动分配到空白空间,如果空间被占用,则拒绝。

但是,如果我像这样缩短代码:

move = int(raw_input('Where would you like to move? (Enter a number from 1-9) \n'))
if 0 < move < 10:
    if board[move] == user_team or computer_team:
        print ('That space is already taken by a player. '
               'Please select an open space \n')
        user_turn()
    else:
        board[move] = computer_team
        print
else:
    print ('That is not a valid move. Please try again. \n')

然后代码将阻止玩家占用空白区域。本质上,代码是说:

if ' ' == 'X' or 'O':

但它表现得好像它是真的,即使它显然是假的。

旁注:以防万一有人问,这就是我绘制电路板的方式:

def draw_board():
print '', board[1], '|', board[2], '|', board[3], \
      '\n-----------\n', \
      '', board[4], '|', board[5], '|', board[6], \
      '\n-----------\n', \
      '', board[7], '|', board[8], '|', board[9], \
      '\n'

董事会是十人的名单' '

4

1 回答 1

1

改变

if board[move] == user_team or computer_team:

if board[move] in [user_team, computer_team]:

if board[move] == user_team or computer_team将被评估为(board[move] == user_team) or (computer_team),因为computer_team始终评估为真值,因此该条件将始终为真。

通过使用in运算符,我们确保它board[move]在后面的项目列表中,其中包含user_teamand computer_team。如果它不在该列表中,它将返回 False。

于 2013-10-26T05:27:29.720 回答