我试图在Codecademy中替换我的战舰游戏,但我无法改变" 0"到" X"。
这是我的代码:
from time import sleep
from random import randint
board = []
board_size = 7
turns = 0
def printboard(board):
for i in range(board_size):
board = (["0"] * 7)
print (" ".join(board))
return board
def random_row(board):
return randint(0, 5)
def random_col(board):
return randint(0, 5)
printboard(board)
ship_row = random_row(board)
print(ship_row)
ship_col = random_col(board)
print(ship_col)
for turns in range(4):
if turns <= 5:
guess_row = input("Guess row: ")
guess_row = int(guess_row)
guess_col = input("Guess col: ")
guess_col = int(guess_col)
if guess_row == ship_row and guess_col == ship_col:
print("You won!")
break
else:
if ((guess_row < 0 or guess_row > 6) or (guess_col < 0 or guess_col > 6)):
print("Not in map")
elif(board[guess_row][guess_col] == 'X'):
print("You guessed that already.")
else:
print("Missed")
board[guess_row][guess_col] = 'X'
print (turns + 1)
elif turns == 3:
print("Game Over!")
出现此错误:
elif(board[[guess_row][guess_col]] == 'X'):
IndexError:列表索引超出范围
如何将X放在我拍摄的地点?
答案 0 :(得分:0)
您的代码存在许多问题。
首先,board
是一个空列表,因此访问board[[guess_row][guess_col]
将始终抛出IndexError: list index out of range
例外。
其次,您有一个全局变量board
,但是您将其作为输入传递给printboard(board)
。确定是否要使用全局变量。此外,printboard
会返回board
,但不会在任何地方分配。
第三,你永远不会创造一个完整的董事会。您只需创建并打印一行永不保存的7个零。
不幸的是,为了让您的战舰游戏正常运行,需要进行大量的代码重写。 StackOverflow通常会在重写大块代码时皱眉。
只是为了帮助您开始并解决第一个异常,只需更改代码的开头:
from random import randint
board_size = 7
board = [["0"] * 7 for i in range(board_size)]
turns = 0
def printboard():
for row in board:
print ' '.join(row)
您可以运行here。