如何在战舰游戏中修复“ TypeError:列表索引必须是整数或分片,而不是str”

时间:2019-06-16 15:42:32

标签: python-3.x

我有一个家庭作业,玩家将5艘船放在一维列表中,然后计算机猜测它们。但是,即使它在我的单人游戏版本中也有效,但是一行代码if board[guess]=="X":无法正常工作。

此外,我不认为for for in range等实际上是制造5艘船并将它们分配到列表中。

from random import randint
import random
board=["O","O","O","O","O","O","O","O","O","O"]

scounter=0
counter=0
shipcount=0

for i in range(5):
     place=int(input("Input index to place ship!"))
     ship=board.insert(place,"X")
     shipcount-=1

while scounter<6:
     guess=(random.choice(board))
     print(guess)
     if board[guess]=="X":
          print("Uh oh!",5-scounter,"ships left")
          scounter+=1
          counter+=1
     else:
          print("Yay, it missed!")
          counter+=1

print("The computer sunk your ships in",counter,"tries!")

结果:

Input index to place ship!1
Input index to place ship!2
Input index to place ship!3
Input index to place ship!4
Input index to place ship!5
X
Traceback (most recent call last):
  File "/Users//Desktop/CODE/battleships 3.py", line 17, in <module>
    if board[guess]=="X":
TypeError: list indices must be integers or slices, not str

1 个答案:

答案 0 :(得分:2)

hello whats up random.choice返回一个随机元素(它是一个列表字符串),因此board是一个字符串。

您可以使用guess代替if board[guess]=="X":

注意:您可以多次击中同一艘船:P,也可能遇到其他一些逻辑错误(尝试在输入循环的末尾打印if guess=="X":,请注意这并非您所期望的。 )。

但是这超出了这个问题的范围...