如何检查列表中的特定索引是否为x?

问题描述 投票:-1回答:1

我正在尝试检查列表中用户的输入是否与我的井字游戏中的“ X”或“ O”相同,但出现错误

TypeError: unsupported operand type(s) for -: 'str' and 'int'

对于此代码:

  player1 = input("Where do you want to place your X, player 1? (row number, space, number)")
  if(moves[int(player1[0] - 1)][int(player1[2] - 1)] == "X" or moves[int(player1[0] - 1)][int(player1[2] - 1)] == "O" ):
    print("Spot taken try again")
    playerInput()

我意识到这可能不是最好的方法,因此,如果您有所改进,请提出建议!

python tic-tac-toe
1个回答
0
投票

您应该将输入转换为int 然后减去1,但是您尝试在转换为int之前先减去1。同样,也不需要两次访问该值。您可以这样做:

spot = moves[int(player1[0]) - 1][int(player1[2]) - 2]

if spot == 'O' or spot == 'X':
    print('Spot taken, try again.')
© www.soinside.com 2019 - 2024. All rights reserved.