python - Pygame 中的文本渲染问题
问题描述
我正在尝试制作一个显示玩家生命值的 HUD。出于某种原因,尽管代码执行正确,但文本没有出现。为了提高效率,我正在使用我的 Button 类来呈现此文本,即使 HUD 从未真正与使用鼠标进行交互。这是 Button 类,然后是 HUD 类:
class Button:
def __init__(self, x, y, width, height, fg, bg, content, fontsize):
self.font = pygame.font.Font('Assets/PixelOperator-Bold.ttf', 32)
self.content = content
self.x = x
self.y = y
self.width = width
self.height = height
self.fg = fg
self.bg = bg
self._layer = 5
self.image = pygame.Surface((self.width, self.height))
self.image.fill(self.bg)
self.rect = self.image.get_rect()
self.rect.x = self.x
self.rect.y = self.y
self.text = self.font.render(self.content, True, self.fg)
self.text_rect = self.text.get_rect(center=(self.width/2, self.height/2))
self.image.blit(self.text, self.text_rect)
def is_pressed(self, pos, pressed):
if self.rect.collidepoint(pos):
if pressed[0]:
return True
return False
return False
class hud (pygame.sprite.Sprite):
def __init__(self, game, hudx, hudy):
self.game = game
self._layer = 3
self.groups = self.game.all_sprites
pygame.sprite.Sprite.__init__(self, self.groups)
self.hudx = 0
self.hudy = 0
self.width = WinWidth
self.height = 80
self.image = pygame.Surface([self.width, self.height])
self.image.fill(black)
self.rect = self.image.get_rect()
#self.hpdisplay = Button(10, 100, 100, 50, white, black, 'HP: {n}', 32)
self.hpdisplay = game.font.render('HP: 100', True, white)
self.hpdisplay.rect = self.hpdisplay.get_rect(x=10, y=10)
game.screen.blit(self.hpdisplay, self.hpdisplay.rect)```
这是此按钮类的一个实例:
def intro_screen(self):
intro = True
title = self.font.render('Cambria', True, white)
title_rect = title.get_rect(x=10, y=10)
pygame.mixer.music.play(-1)
play_button = Button(-5, 100, 100, 50, white, black, 'PLAY', 32)
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
self.running = False
mouse_pos = pygame.mouse.get_pos()
mouse_pressed = pygame.mouse.get_pressed()
if play_button.is_pressed(mouse_pos, mouse_pressed):
pygame.mixer.music.fadeout(500)
intro = False
self.screen.blit(self.intro_background, (0, 0))
self.screen.blit(title, title_rect)
self.screen.blit(play_button.image, play_button.rect)
self.clock.tick(FPS)
pygame.display.update()
解决方案
推荐阅读
- react-native - 如何在本机反应中使用 panresponder 增加视图高度?
- php - Laravel 中的自定义验证器规则总是返回消息
- odata - 对空 OData 导航属性的 GET 请求的正确响应是什么
- flutter - 颤动中的Remove.bg api http post返回图像
- mysql - MySql 按不同列分组和排序
- flutter - 如何在flutter中运行其他方法而不是runApp
- vue.js - 在 v-select multiple 中显示选定的值
- javascript - 谷歌搜索回调函数
- c - 根据用户和名称的输入,我想打印不同的东西
- image - 360全景图和普通图有什么区别