打印二维列表

时间:2014-04-21 21:08:04

标签: python list python-3.x

我正在尝试打印二维列表来表示连接四的控制台游戏。它应该是这样的:

 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是一个带有两个字段的namedtuple对象,第一个关闭的是游戏板(字符串列表)。

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='')

Namedtuple的代码

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 个答案:

答案 0 :(得分: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()