【发布时间】:2018-01-05 01:55:20
【问题描述】:
我目前正在用 Python 创建游戏战舰,玩家可以在其中与计算机对战。我设法为他们俩创建了棋盘,并为玩家的棋盘放置了船只。但我坚持使用 random.randint 作为计算机板随机放置船只。
我在输出中收到此错误:文件“python”,第 98 行,在 comp_place_ships TypeError: 'function' 对象不可下标
代码如下:
#Computer place ships
def comp_place_ships(comp_board, ships):
for i, j in ships.items():
ship_not_placed = True
while ship_not_placed:
ori = random.randint(0,1)
x = random.randint(0,9)
y = random.randint(0,9)
placement = comp_board[x][y]
if ori == 0 and placement == '.':
for k in range(j):
comp_board[x][y] = i
comp_board[x+k][y] = i
ship_not_placed = False
elif ori == 1 and placement == '.':
for k in range(j):
comp_board[x][y] = i
comp_board[x][y+k] = i
ship_not_placed = False
elif ori != 0 or 1 and placement != '.':
print('Invalid choice, please try again.')
comp_place_ships(comp_board, ships)
我知道“placement = comp_board[x][y]”部分是产生错误代码的部分,但不知道如何解决它。我使用变量位置来检查坐标是否等于“。”这是二维列表中每个单元格的标准值。有没有人可能对如何解决这个问题有任何建议?
PS!我知道代码的结构很差,我没有添加其他条件,例如如何不随船下船。当我解决了这个问题时会添加它=)
已编辑!:为 comp_place_ships 函数添加了函数调用,让您更容易查看输出,这是我的 repl.it 代码:https://repl.it/J41A/10
【问题讨论】:
-
可以添加函数调用语句吗?
-
现在添加了函数调用以及我整个代码的链接。
-
但是您的 repl.it 代码是
comp_place_ships(comp_place_ships, ships),而不是comp_place_ships(comp_board, ships)。应该是问题吗? -
难以置信!我已经为这个问题苦苦挣扎了好几个小时!,这就是问题所在。非常感谢!
标签: list python-3.x random