现在,我为我的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代码很难看,我知道,但我的网格正常工作。我可以反复研究一下。我现在的问题是,我不知道怎么用一个数字来填充正方形?我想在[row][col]位于rect2中的位置添加数独网格中的数字。
我希望你们中的一个能帮我。
发布于 2020-09-01 22:30:38
要在矩形中绘制文本,需要一些东西。第一种是游戏Font 对象。这基本上只是一个配置好的字体。您可以将其传递给真类型字体(可能是其他字体)的完整路径,也可以使用系统字体。
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
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 ) )发布于 2020-09-01 14:32:38
我不知道soduku是如何工作的,但这就是你在游戏中呈现文本的方式。首先创建一个字体。
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,因为您正在呈现数字。这个曲面和游戏中的任何其他曲面一样,所以您可以简单地使用win.blit(surface, (row, col))来呈现它。
https://stackoverflow.com/questions/63689556
复制相似问题