我正在写一个Battleship游戏,我面临一些问题。我已经编写了一些足够的代码来创建一个10x10的地图,随机定位一个船的位置并给玩家10个猜测。现在我是尝试将数字1-10放在顶行和第一列中以使地图更清晰。 不幸的是,在添加数字后,我将列表更改为不同的内容:
from random import randint
board = []
board.append((str(n) for n in(range(0, 11))))
liczba_kolumn = 10
for x in range(9):
board.append([str(x + 1)] +["O"] * liczba_kolumn)
board.append(["10O"] + ["O"] * (liczba_kolumn - 1))
def print_board(board):
for row in board:
print(" ".join(row))
print ("Let's play Battleship!")
print_board(board)
def random_row(board):
return randint(1, len(board))
def random_col(board):
return randint(1, len(board[0]))
ship_row = random_row(board)
ship_col = random_col(board) `
for turn in range(10):
print ("Turn " + str(liczba_prob))
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
liczba_prob = liczba_prob - 1
if guess_row == "" or guess_col == "":
print ("guess the location")
else:
guess_row = int(guess_row) - 1
guess_col = int(guess_col) - 1
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sunk my battleship!")
break
else:
if (guess_row < 0 or guess_row > 9) or (guess_col < 0 or guess_col > 9):
print ("Wrong localisation")
elif(board[guess_row][guess_col] == "X"):
print ("You already guessed that one.")
第一个错误是
return randint(1, len(board[0]))
TypeError: object of type 'generator' has no len()
我将random_functions从len()改为“11”。但是下一个错误是
elif(board[guess_row][guess_col] == "X"):
TypeError: 'generator' object is not subscriptable.
我的问题是 - 我在哪个时刻将我的board []列表更改为'generator',如何将其更改为列表?
编辑:
感谢您的回答,他们帮助了我很多。现在我想了解一个不同的东西 - 为什么代码
board = []
board.append(["10O"] + ["O"] * (10))
print(" ".join(board))
返回一个错误:序列项0:预期的str实例,找到列表? 第一个和下一个项目都在括号中。看起来非常相似的代码不会返回错误:
board = []
board.append(["10O"] + ["O"] * 10)
def print_board(board):
for row in board:
print(" ".join(row))
print_board(board)
答案 0 :(得分:0)
行board.append((str(n) for n in(range(0, 11))))
将生成符附加到board
。您可能希望.extend()
或.insert([str(n) ... ])
(观看[
和]
)