本文介绍了有没有办法在pygame的屏幕中央放置数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pygame,为了显示分数,我有 0 到 9 的图像,需要将它们集中放置,但我不能将其放在中间,因为分数的大小会发生变化,这是唯一的解决方案我发现直到现在是硬编码它的分数高达 9,然后高达 99 等,如下面的代码

I am working with pygame, to display the score I have images from 0 to 9 and need to place them centralized, but i can't just put it in the middle because the size of the score can change, the only solution I found until now is to hardcode it for scores up to 9, then up to 99 etc like in the code below

if len(str(self.value)) == 1:
    win.blit(self.imgs[self.value],
             ((x - self.imgs[self.value].get_width(), y)))

elif len(str(self.value)) == 2:
    win.blit(self.imgs[int(str(self.value)[0])],
             (x - self.imgs[int(str(self.value)[0])].get_width(), y))
    win.blit(self.imgs[int(str(self.value)[1])],
             (x, y))

有没有一种通用的方法来显示所有分数的数字集中循环?

Is there a generic way to do display n numbers centralized looping for all the numbers of the score?

推荐答案

获取 pygame.Rect 具有图像大小的对象 (pygame.Surface) 来自 get_rect().通过关键字属性(center = (x, y))设置矩形的中心,并使用矩形blit 图像:

Get a pygame.Rect object with the size of the image (pygame.Surface) by get_rect(). Set the center of the rectangle by an keyword attribute (center = (x, y)) and use the rectangle to blit the image:

centered_rect = self.imgs[self.value].get_rect(center = (x, y))
win.blit(self.imgs[self.value], centered_rect)

这篇关于有没有办法在pygame的屏幕中央放置数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 15:13