首页 > 解决方案 > 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()

标签: pythontextpygame

解决方案


推荐阅读