对网格/板中的行和列进行编号

时间:2017-01-12 17:37:53

标签: python grid enumerate

我正在运行一个函数,它将生成一个带有空方块的板,用'代表'。 '并且玩家将以'0'表示。

我想对行和列进行编号,以表示用户在提示时也可以轻松输入的坐标。这是我想到的最终结果:

  0 1 2 3 4 5 6 7
0 . . . . . . . . 
1 . . . . . . . . 
2 . . . . . . . . 
3 . . . . . . . . 
4 . . . . . . . . 
5 . . . . . . . . 
6 . . . . . . . . 
7 . . . . . . . . 

我认为有一个枚举函数可以帮助解决这个问题,我只是需要帮助来尝试实现它。

供参考,这是用于生成网格的函数:

def drawgrid(win,lose,counter,coordinate):
    for i in range(-1+(coordinate[0])):
            print(" . "*8)
    print(" . "*((coordinate[1])-1),counter," . "*(7-coordinate[1]))
    for i in range(8-coordinate[0]):
        print(" . "*8)

2 个答案:

答案 0 :(得分:0)

这是制作“纸板”然后打印出来的简单方法。

w,h = 8,8

board =[['.' for x in range(w)] for y in range(h)]
print ' ',
for i in range(w):
    print i,
print ''
for i in range(h):
    print i,
    for j in range(w):
        print board[i][j],
    print ''

结果

  0 1 2 3 4 5 6 7 
0 . . . . . . . . 
1 . . . . . . . . 
2 . . . . . . . . 
3 . . . . . . . . 
4 . . . . . . . . 
5 . . . . . . . . 
6 . . . . . . . . 
7 . . . . . . . . 
[Finished in 0.2s]

答案 1 :(得分:0)

好像你想要一个矩阵。您是希望标签对播放器可见,还是只能由程序访问?

这是一个可以同时执行这两项操作的小程序。

class Cell:
    """
    :param x: x-axis location
    :param y: y-axis location
    """
    def __init__(self, x, y):
        self.x = int(x)
        self.y = int(y)
        self.visual = "."

    def __str__(self):
        return self.visual

class Board:

    def __init__(self, x=10, y=10, show_labels=False):
        """
        :param x: How many columns the board uses
        :param y: How many rows the board uses
        :param show_labels: Display labels to the player
        """

        self.x = x
        self.y = y
        self.show_labels = show_labels
        self.board = {}

        self.generate_board()

    def generate_board(self):
        for y in range(0, self.y):

            # Add the key X to the board dictionary
            self.board[y] = []   

            for x in range(0, self.x):
                # Make a cell @ the current x, y and add it to the board
                cell = Cell(x, y)
                self.board[y].append(cell)

    def show_board(self):

        for key, cells in self.board.iteritems():

            # Add the X Labels
            if self.show_labels:
                if key == 0:
                    x_label = []
                    for cell in self.board[key]:
                        x_label.append(str(cell.x + 1))
                    print "".join(x_label)

            row = []
            for cell in cells:
                row.append(str(cell))

            # Add the Y labels
            if self.show_labels:
                row.append(str(cell.y + 1))

            print "".join(row)

    def set_player(self, x, y):
        self.board[y][x].visual = "0"

b = Board(5, 5, True)
b.set_player(2, 2)
b.show_board()

输出5x5

12345
.....1
.....2
..0..3
.....4
.....5

输出10x8

12345678910
..........1
..........2
..0.......3
..........4
..........5
..........6
..........7
..........8