打印二维列表
我正在尝试打印一个二维列表,用来表示一个四子连珠的控制台游戏。它应该看起来像这样:
1 2 3 4 5 6 7
. . . . . . .
. . . . . . .
. . . . . . .
. . R . . . .
. . Y R . . .
. R R Y . Y .
这是我目前的代码,但我似乎无法让它正常工作,总是出现“IndexError”,提示“元组索引超出范围”。请记住,在connect_four模块中,BOARD_ROWS等于6,BOARD_COLUMNS等于7。NONE是' '(空格),RED是'R',YELLOW是'Y'。另外,game_state是一个命名元组对象,有两个字段,第一个是游戏棋盘(字符串列表)。
def print_board(game_state) -> None:
""" Prints the game board given the current game state """
print("1 2 3 4 5 6 7")
for a in range(connect_four.BOARD_ROWS):
for b in range(connect_four.BOARD_COLUMNS):
if game_state[b][a] == connect_four.NONE:
print('.', end=' ')
elif game_state[b][a] == connect_four.RED:
print('R', end=' ')
elif game_state[b][a] == connect_four.YELLOW:
print('Y', end=' ')
else:
print('\n', end='')
命名元组的代码
def _new_game_board() -> [[str]]:
"""
Creates a new game board. Initially, a game board has the size
BOARD_COLUMNS x BOARD_ROWS and is comprised only of strings with the
value NONE
"""
board = []
for col in range(BOARD_COLUMNS):
board.append([])
for row in range(BOARD_ROWS):
board[-1].append(NONE)
return board
ConnectFourGameState = collections.namedtuple('ConnectFourGameState', ['board', 'turn'])
def new_game_state() -> ConnectFourGameState:
"""
Returns a ConnectFourGameState representing a brand new game
in which no moves have been made yet.
"""
return ConnectFourGameState(board=_new_game_board(), turn=RED)
1 个回答
1
在你添加了其他代码后,我对你表示行和列的方式有点困惑,所以如果我是用你那种方法来解决这个问题,我会这样写代码;希望对你有帮助:
def _new_game_board() -> [[str]]:
"""
Creates a new game board. Initially, a game board has the size
BOARD_COLUMNS x BOARD_ROWS and is comprised only of strings with the
value NONE
"""
return [[None] * BOARD_COLUMNS for _ in range(BOARD_ROWS)]
ConnectFourGameState = namedtuple('ConnectFourGameState', ['board', 'turn'])
def new_game_state() -> ConnectFourGameState:
"""
Returns a ConnectFourGameState representing a brand new game
in which no moves have been made yet.
"""
return ConnectFourGameState(board=_new_game_board(), turn=RED)
至于 print_board
函数:
def print_board(game_state):
"""Prints the game board given the current game state"""
print("1 2 3 4 5 6 7")
for row in range(BOARD_ROWS):
for col in range(BOARD_COLUMNS):
if game_state.board[row][col] == connect_four.NONE:
print('.', end=' ')
elif game_state.board[row][col] == connect_four.RED:
print('R', end=' ')
elif game_state.board[row][col] == connect_four.YELLOW:
print('Y', end=' ')
print()