目前我为我的数独求解器创建了一个可视化工具。
现在我想用
pygame
显示网格中的数字。
def draw(win):
global grid
w = 70
x,y = 0,0
for row in grid:
for col in grid:
rect = pygame.Rect(x,y,w,w)
pygame.draw.rect(win,BLACK,rect)
rect2 = pygame.Rect(x+2, y+2, w-1, w-1)
pygame.draw.rect(win,WHITE,rect2)
pygame.display.flip()
x = x + w
y = y + w
x = 0
我知道代码很丑陋,但我的网格可以工作。我可以迭代它。我现在的问题是,我不知道如何用数字填充矩形? 我想在
[row][col]
内的 rect2
位置添加数独网格中的数字。
我希望你们中的一位可以帮助我。
要在矩形中绘制文本,您需要一些东西。第一个是 pygame
Font
object。这基本上只是一个配置的字体。您可以将其传递给 True Type 字体(可能是其他字体)的完整路径,或使用系统字体。
number_font = pygame.font.SysFont( None, 16 ) # default font, size 16
然后要渲染一个数字,将其作为文本传递给字体的
render()
方法,为其指定前景色和背景色。第二个参数是你是否想要字体漂亮流畅。一般来说我总是留下这个True
。
number_font = pygame.font.SysFont( None, 16 ) # Default font, Size 16
number_image = number_font.render( "8", True, BLACK, WHITE ) # Number 8
这样就创建了一个
number_image
- 一个包含“渲染”数字的 pyagme.Surface
。16
,它对于您的网格来说可能太大(或者太小)。
# Creating the font object needs to be only done once, so don't put it inside a loop
number_font = pygame.font.SysFont( None, 16 ) # default font, size 16
...
for row in grid:
for col in grid:
rect = pygame.Rect(x,y,w,w)
pygame.draw.rect(win,BLACK,rect)
rect2 = pygame.Rect(x+2, y+2, w-1, w-1)
pygame.draw.rect(win,WHITE,rect2)
# make the number from grid[row][col] into an image
number_text = str( grid[row][col] )
number_image = number_font.render( number_text, True, BLACK, WHITE )
# centre the image in the cell by calculating the margin-distance
# Note: there is no "height", cells are square (w by w)
margin_x = ( w-1 - number_image.width ) // 2
margin_y = ( w-1 - number_image.height ) // 2
# Draw the number image
win.blit( number_image, ( x+2 + margin_x, y+2 + margin_y ) )
我不知道 soduku 是如何工作的,但这就是在 pygame 中渲染文本的方式。首先创建一个字体。
fontName = pygame.font.get_default_font()
size = 10 # This means the text will be 10 pixels in height.
# The width will be scaled automatically.
font = pygame.font.Font(fontName, size)
然后从字体创建文本表面。
text = number
antislias = True
color = (0, 0, 0)
surface = font.render(f"{text}", antialias, color)
注意,文本参数始终必须是字符串,因此在您的情况下,您必须使用
fstring
,因为您正在渲染数字。该表面与 pygame 中的任何其他表面一样,因此您可以简单地使用 win.blit(surface, (row, col))
来渲染它。