在Pygame Rect中写数字/文字

问题描述

此刻,我为Sudoku求解器创建了可视化工具。

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

代码很丑,我知道,但是我的网格有效。我可以对其进行迭代。我现在的问题是,我不知道如何用数字填充Rect吗? 我想从Sudoku网格中的[row][col]中的位置rect2添加数字。

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

解决方法

我不知道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)
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
现在必须将其放在每个单元格的中心。我们可以通过计算周围矩形与数字图像大小之间的差异来做到这一点。将其分成两半应该使我们处于中心位置。我只是猜测字体大小为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,size 16

...

for row in grid:
    for col in grid:
        
        rect = pygame.Rect(x,y,w,w)
        pygame.draw.rect(win,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,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 ) )

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...