gpt4 book ai didi

python - 如何在pygame的每个Tile网格中绘制数字?

转载 作者:行者123 更新时间:2023-12-04 09:36:26 25 4
gpt4 key购买 nike

我正在制作一个数独 GUI,到目前为止,我可以绘制网格,但无法在每个图块上显示值。到目前为止,我从另一个线程复制了一些关于如何在 pygame 上的网格上显示值的代码,并应用它以便在该图块上显示一个值,但不是显示单个图块的值,而是将所有数字在同一个角落,我不知道如何解决它。关于为什么我不能在我的 Tile 类的每个单独的 tile 中显示文本的任何帮助?这是我的一些代码:

    class Tile:
'''Represents each white tile/box on the grid'''
def __init__(self, value, window, x1, x2):
self.value = value #value of the num on this grid
self.rows = 9
self.cols = 9
self.width = 60
self.height = 60
self.window = window #the window/screen we're in
self.rect = pygame.Rect(x1, x2, self.width, self.height) #dimensions for the rectangle

def draw(self):
'''Draws a tile on the board'''
pygame.draw.rect(self.window, (0,0,0), self.rect, 1)
pygame.display.flip()

def display(self):
'''Displays a number on that tile'''
font = pygame.font.SysFont('arial', 50)
text = font.render(str(self.value), True, (0, 0, 0))
rect = text.get_rect() #Returns a new rectangle covering the entire surface
self.window.blit(text, rect)
pygame.display.update()
   class Board:
'''A sudoku board made out of Tiles'''
def __init__(self, window):
self.board = Sudoku([
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
])
self.window = window
self.tiles = [[0 for i in range(9)] for j in range(9)]

def draw_board(self):
'''Fills the board with Tiles'''
for i in range(9):
for j in range(9):
if j%3 == 0 and j != 0: #vertical lines
pygame.draw.line(self.window, (0, 0, 0), (((j//3)*180)+1, 0), (((j//3)*180)+1, 540), 5)
pygame.display.flip()

if i%3 == 0 and i != 0: #horizontal lines
pygame.draw.line(self.window, (0, 0, 0), (0, ((i//3)*180)+1), (540, ((i//3)*180)+1), 5)
pygame.display.flip()

self.tiles[i][j] = Tile(self.board.get_board()[i][j], self.window, i*60, j*60) #draw a single tile
self.tiles[i][j].draw()
self.tiles[i][j].display()
输出:
The numbers are all in the upper left corner instead of being in each tile?

最佳答案

使用 blit 方法时,可能值得使用坐标而不是矩形对象。通过这种方式,您可以传递一个参数,说明您希望在屏幕上添加数字的位置。您可能希望在 display 方法中将此作为参数。
例如

def display(self, position):
'''Displays a number on that tile'''
font = pygame.font.SysFont('arial', 50)
text = font.render(str(self.value), True, (0, 0, 0))
self.window.blit(text, position)
pygame.display.update()
您还可以使用一些简单的数学方法来更改您“位图”图像的位置,以反射(reflect)板上的坐标。这可能使它更具可扩展性。

关于python - 如何在pygame的每个Tile网格中绘制数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62560902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com