在 Pygame 矩形中写入 number/text

Writing a number/text in a Pygame Rect

目前我正在为我的数独解算器创建一个可视化工具。

现在我想用 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

代码很丑,我知道,但我的网格有效。我可以迭代它。我现在的问题是,我不知道如何用数字填充矩形? 我想在 rect2.

内的 [row][col] 位置添加数独网格中的数字

我希望你们中的一个能帮助我。

我不知道数独是如何工作的,但这就是你在 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)).

简单地渲染它

要在矩形中绘制文本,您需要做一些事情。第一个是 pygame Font object。这基本上只是一种配置的字体。您可以将完整路径传递给 True Type 字体(可能是其他字体),或使用系统字体。

number_font = pygame.font.SysFont( None, 16 )   # default font, size 16

然后渲染一个数字,将它作为文本传递给字体的 render() method,给它一个前景色和背景色。第二个参数是要不要字体好看流畅。一般我都是留这个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
现在必须在每个单元格中居中。我们可以通过计算周围矩形的大小与 number-image 的大小之间的差异来做到这一点。将其分成两半应该会给我们一个中心位置。我只是猜测 16 的 font-size,它可能对你的网格来说太大了(或者太小了)。

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