连接四个游戏制作网格

时间:2013-10-10 22:30:56

标签: python

我正在尝试连接四个游戏。此时,我正在尝试仅为控制台交互制作游戏,并且无法使网格看起来像这样的格式:

创建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

1 个答案:

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

如果你有兴趣,我基于这个想法做了一个简单的整个游戏实现。你可以看到它here