繁体   English   中英

在控制台上格式化输出-Python

[英]formatting output on the console - Python

这里的第一个问题,为格式混乱而道歉。

我希望有几个提示。 我正在尝试将棋盘游戏作为OOP的练习。 因此,我需要一个8x8的“棋盘”,类似于国际象棋棋盘,但是游戏性(即将棋子放到棋盘上)仅发生在7x7的单元格上。 我通过遍历8个列表的列表来实现它。 这是代码:

class Board(object):

    def __init__(self):
        self.Board = [[[] for x in range(LENGTH)] for y in range(LENGTH)]

    def makeBoard(self, initial_blocked):

        for row in range(LENGTH):
            for col in range(LENGTH):
                self.Board[row][col] = 'e'
        self.Board[0][1] = 'A'
        self.Board[0][2] = 'B'
        self.Board[0][3] = 'C'
        self.Board[0][4] = 'D'
        self.Board[0][5] = 'E'
        self.Board[0][6] = 'F'
        self.Board[0][7] = 'G'

        self.Board[0][0] = '~'
        self.Board[1][0] = '1'
        self.Board[2][0] = '2'
        self.Board[3][0] = '3'
        self.Board[4][0] = '4'
        self.Board[5][0] = '5'
        self.Board[6][0] = '6'
        self.Board[7][0] = '7'

        if True:
            while initial_blocked > 0:
                position_x = rand(0, 7)
                position_y = rand(0, 7)
                if self.Board[position_x][position_y] == 'e':
                    self.Board[position_x][position_y] = 'X'
                    initial_blocked -= 1

        for line in range(8):
            print(self.Board[line])

输出看起来像这样:

['~', 'A', 'B', 'C', 'D', 'E', 'F', 'G']
['1', 'e', 'e', 'e', 'e', 'e', 'e', 'e']
['2', 'e', 'e', 'e', 'X', 'X', 'e', 'e']
['3', 'e', 'X', 'e', 'e', 'X', 'e', 'e']
['4', 'e', 'e', 'e', 'X', 'e', 'e', 'e']
['5', 'e', 'e', 'e', 'e', 'e', 'e', 'e']
['6', 'e', 'e', 'e', 'e', 'e', 'e', 'e']
['7', 'e', 'e', 'e', 'e', 'e', 'e', 'e']

第一行和第一列将用于用户输入(例如,A1,D4)'X'是被阻止的单元格,'e'表示为空。 玩家进入他们想要保留其棋子的位置,例如A1,并且'e'将变为黑色或白色的'b'或'w'。 还没有弄清楚我将如何做,但是首先要做的是。
我希望它至少类似于某个板。 如果我尝试使用许多print()打印输出板,则无法弄清楚如何更改该板上的单元格,该单元格引用与索引相同的单元格。 也就是说,输入A1会更改[1] [1]上的列表以及板上的该单元格。

我希望这是有道理的。 谢谢!

我对您的代码做了一些优化,可能会对您有所帮助。 无需执行所有这些单独的语句来初始化列和行标题,而是可以使用循环来完成。 另外,在可行的情况下,直接遍历列表也比使用索引好,这是很好的。 而且我已经更改了您的一些名称,以使其符合PEP-0008样式指南; 这使其他人更容易阅读您的代码,尤其是当他们使用颜色编码的语法突出显示时。

from random import seed, randrange

seed(123)

LENGTH = 8

# A dict for converting reference letters to integers
letters = {ch: i for i, ch in enumerate('ABCDEFG', 1)}

def ref_to_index(ref):
    ''' Convert a ref from A1 form to a tuple of (row, col) integers
        Return None if the ref is invalid 
    '''
    if len(ref) != 2:
        return None
    x, y = ref.upper()
    if x not in letters or y not in '1234567':
        return None
    return int(y), letters[x]

class Board(object):
    def __init__(self):
        # Initialize the board lists
        self.board = [['e'] * LENGTH for y in range(LENGTH)]
        # Add the column headers
        self.board[0][:] = list('~ABCDEFG')
        # Add the row headers
        for i, row in enumerate(self.board[1:], 1):
            row[0] = str(i)

    def add_blocks(self, initial_blocked):
        for _ in range(initial_blocked):
            while True:
                position_x = randrange(1, LENGTH)
                position_y = randrange(1, LENGTH)
                row = self.board[position_y]
                if row[position_x] == 'e':
                    row[position_x] = 'X'
                    break

    def reset(self):
        ''' Make all the board cells empty '''
        size = LENGTH - 1
        for row in self.board[1:]:
            row[1:] = ['e'] * size

    def show(self):
        for row in self.board:
            print(' '.join(row))
        print()

# test

board = Board()
board.show()
board.add_blocks(7)
board.show()
while True:
    ref = input('Select a move: ')
    idx = ref_to_index(ref)
    if idx is None:
        print('Invalid move')
        continue
    y, x = idx
    row = board.board[y]
    if row[x] != 'e':
        print("That cell isn't empty")
        continue
    row[x] = 'b'
    board.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM