简体   繁体   English

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

[英]formatting output on the console - Python

First question here, so apologize for the messy formatting. 这里的第一个问题,为格式混乱而道歉。

I was hoping was a couple of pointers. 我希望有几个提示。 I'm trying to implement a board game as an exercise for OOP. 我正在尝试将棋盘游戏作为OOP的练习。 So I need a 8x8 'board', similar to a chess board, but the game play, ie putting pieces on the board only occurs on 7x7 cells. 因此,我需要一个8x8的“棋盘”,类似于国际象棋棋盘,但是游戏性(即将棋子放到棋盘上)仅发生在7x7的单元格上。 I've implemented it by iterating over a list of 8 lists. 我通过遍历8个列表的列表来实现它。 Here's the code: 这是代码:

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])

The output looks like this: 输出看起来像这样:

['~', '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']

1st row and column will be used for the user input( eg A1, D4) 'X' are cells that are blocked and 'e' stands for empty. 第一行和第一列将用于用户输入(例如,A1,D4)'X'是被阻止的单元格,'e'表示为空。 The players enter where they want to keep their piece, eg A1, and the 'e' will be changed to 'b' or 'w', black or white. 玩家进入他们想要保留其棋子的位置,例如A1,并且'e'将变为黑色或白色的'b'或'w'。 Haven't still figured out how I'll do that, but first things first. 还没有弄清楚我将如何做,但是首先要做的是。
I want it to resemble -at least somewhat- a board. 我希望它至少类似于某个板。 If I try to print out a board using many print()s, I cant figure out how I can change a cell on that board, that references the the same cell as the index. 如果我尝试使用许多print()打印输出板,则无法弄清楚如何更改该板上的单元格,该单元格引用与索引相同的单元格。 ie input A1 changes the list at [1][1] and that cell on the board. 也就是说,输入A1会更改[1] [1]上的列表以及板上的该单元格。

I hope this makes sense. 我希望这是有道理的。 Thanks! 谢谢!

I've made a few optimizations to your code that you may find helpful. 我对您的代码做了一些优化,可能会对您有所帮助。 Rather than doing all of those separate statements to initialise the column and row headers, we can do that using loops. 无需执行所有这些单独的语句来初始化列和行标题,而是可以使用循环来完成。 Also, it's good to iterate over lists directly, rather than using indices, when practical. 另外,在可行的情况下,直接遍历列表也比使用索引好,这是很好的。 And I've changed some of your names to make them comply with the PEP-0008 style guide; 而且我已经更改了您的一些名称,以使其符合PEP-0008样式指南; that makes it easier for others to read your code, especially if they're using colour-coded syntax highlighting. 这使其他人更容易阅读您的代码,尤其是当他们使用颜色编码的语法突出显示时。

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