我正在尝试在Python中创建像Battleship这样的游戏。我当前的代码隐藏了一艘船,如果您猜测船的位置(显示坐标是出于调试目的)。我的错误是它正在更改所有行的项目的文本,而不仅仅是一行。
from random import randint
board = []
board = [["O"]*5]*5
def print_board(board):
for row in board:
print(" ".join(row))
print_board(board)
ship_row = randint(0, len(board)-1)
ship_col = randint(0, len(board[0])-1)
print(ship_row, ship_col)
gr = input("Guess row: ")
gc = input("Guess column: ")
if gr == ship_row and gc == ship_col:
board[ship_row][ship_col] = "X"
print_board(board)
答案 0 :(得分:1)
board = [["O"]*5]*5
恭喜,您现在有5份相同的列表。
board = [["0"] * 5 for x in range(5)]