1

我正在尝试制作连接四游戏。在这一点上,我试图使游戏仅用于控制台交互,并且无法使网格看起来像这种格式:

创建 7 列,每列包含“。” 直到被任何一种颜色替换的时间(以防格式显示不正确):

1  2  3  4  5  6  7
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  Y  .  .  .  .
.  Y  R  .  .  .  .
.  R  Y  .  .  .  .
.  R  R  .  .  .  .

这是我到目前为止所拥有的:

NONE = ' '
RED = 'R'
YELLOW = 'Y'

BOARD_COLUMNS = 7
BOARD_ROWS = 6

# board=two dimensional list of strings and
# turn=which player makes next move'''    
ConnectFourGameState = collections.namedtuple('ConnectFourGameState',
                                              ['board', 'turn'])

def new_game_state():
    '''
    Returns a ConnectFourGameState representing a brand new game
    in which no moves have been made yet.
    '''
    return ConnectFourGameState(board=_new_game_board(), turn=RED)

def _new_game_board():
    '''
    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
4

1 回答 1

2

您将要设置NONE'.',而不是空格。然后,您可以为板子制作这样的打印功能:

def printBoard (b):
    print('  '.join(map(lambda x: str(x + 1), range(BOARD_COLUMNS))))
    for y in range(BOARD_ROWS):
        print('  '.join(b[x][y] for x in range(BOARD_COLUMNS)))

像这样使用:

>>> x = _new_game_board()
>>> printBoard(x)
1  2  3  4  5  6  7
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .

在重建您的示例状态时:

>>> x[1][-1] = RED
>>> x[1][-2] = RED
>>> x[1][-3] = YELLOW
>>> x[2][-1] = RED
>>> x[2][-2] = YELLOW
>>> x[2][-3] = RED
>>> x[2][-4] = YELLOW
>>> printBoard(x)
1  2  3  4  5  6  7
.  .  .  .  .  .  .
.  .  .  .  .  .  .
.  .  Y  .  .  .  .
.  Y  R  .  .  .  .
.  R  Y  .  .  .  .
.  R  R  .  .  .  .

如果你有兴趣,我根据这个想法对整个游戏做了一个简单的实现。你可以在这里看到它。

于 2013-10-10T23:02:34.643 回答