Pygame 文字不显示,只有背景显示

94 阅读2分钟

一位开发者在使用 Pygame 进行游戏开发时遇到一个问题:在添加了一个计分板代码后,游戏中只有背景显示,而文字不显示。以下是他所使用的代码:

class MenuScores(MenuClass):
    def __init__(self, surface, engine):
        MenuClass.__init__(self, surface)

        self.MoonSurvival = engine
        self.text = "Name"

    def name():

        size = 36
        screen = pygame.display.set_mode((1280, 720))
        name = ""
        font = pygame.font.SysFont('data/fonts/score.ttf', size)
        background = pygame.image.load('data/images/bg.jpg')

        while True:
            #  readlines returns a list; having this in
            #  loop allows pygame to draw recently added
            #  string; no need to close and open a window
            namefile = open('score.txt', 'r')
            names = namefile.readlines()

            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.unicode.isalpha():
                        if len(name) < 4:
                            if event.unicode == 3:
                                name += 0
                            else:
                                name += event.unicode
                    elif event.key == K_BACKSPACE:
                        name = name[:-1]
                    elif event.key == K_RETURN:
                        f = open("data/scores/score.txt", "a")
                        f.write(str(name) + "     " + str(self.MoonSurvival.total_score) + "\n")
                        f.close()
                        name = ""
                        self.text = ""
                elif event.type == QUIT:
                    return

            #  create a Rectangle container, where yours
            #  text variable will be drawn
            #  Rect(left, top, width, height)
            textrect = Rect(0, 0, 100, size)
            screen.fill((0, 0, 0))
            for i in names:
                #  iterate through lines from text file (it is stored
                #  in names variable and it is a list)

                #  create text variable and draw it to textrect
                text = font.render(i[:-1], True, (255,0,0), (0,0,0))
                screen.blit(text, textrect)
                #  change y coordinate of textrect; in next iteration
                #  next line will appear below the previous line
                textrect.centery += size

            block = font.render(name, True, (255, 255, 255))
            rect = block.get_rect()
            rect.center = screen.get_rect().center
            screen.blit(background, (0, 0))
            screen.blit(block, rect)
            pygame.display.update()
            pygame.display.flip()

    def draw(self):

        self.renderText()
        self.drawHint()
        self.surface.blit(self.background, (0, 0))

        # update surface
        pygame.display.update()

    def _handleEvents(self, event):
        def pressed(key):
            keys = pygame.key.get_pressed()

            if keys[key]:
                return True
            else:
                return False

        if pressed(pygame.K_SPACE):
            self.MoonSurvival.game_state = STATE_MENU
            self.MoonSurvival.level = 1

    def renderText(self):
        # split texts at \n (newline)

        texts = self.text.split('\n')

        for i in range(len(texts)):
            textSurface = self.menufont.render(texts[i], 0, (255, 0, 0))

            textRect = textSurface.get_rect()
            textRect.centerx = SCREEN_WIDTH / 2
            textRect.centery = SCREEN_HEIGHT / 2 + i * self.menufont.size(texts[i])[1]

            self.surface.blit(textSurface, textRect)

    def drawHint(self):
        textSurface = self.menufont.render('(Press SPACE to return to menu)', 0, (255, 0, 0))
        textRect = textSurface.get_rect()
        textRect.centerx = SCREEN_WIDTH / 2
        textRect.centery = SCREEN_HEIGHT - 50
        self.surface.blit(textSurface, textRect)

2. 解决方案

  1. 检查代码中的错误:

    • 确保 pygame.init() 已被调用,以便初始化 Pygame。
    • 确保 screen 对象已被创建,并且具有正确的尺寸。
    • 检查 font 对象是否已正确初始化,并且具有正确的字体和大小。
    • 重构了代码,将 name 函数改写成了一个独立的类,以便代码更加清晰。
    • 重新检查了所有的逻辑,确保他们没有问题。
    • 确保 text 变量的值不是 None 或空字符串。
    • 确保代码中没有逻辑错误。
  2. 确保代码中没有逻辑错误:

    • 确保文本正在被正确地渲染。
    • 确保文本正在被正确地绘制到屏幕上。
    • 确保屏幕正在被正确地更新。
  3. 尝试以下代码,看看是否有帮助:

class MenuScores(MenuClass):
    def __init__(self, surface, engine):
        MenuClass.__init__(self, surface)

        self.MoonSurvival = engine
        self.text = "Name"

    def draw(self):
        screen = pygame.display.get_surface()

        # Draw the background
        screen.fill((0, 0, 0))

        # Draw the text
        font = pygame.font.SysFont('arial', 36)
        text_surface = font.render(self.text, True, (255, 255, 255))
        text_rect = text_surface.get_rect()
        text_rect.center = screen.get_rect().center
        screen.blit(text_surface, text_rect)

        # Update the display
        pygame.display.update()

    def handle_events(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                self.MoonSurvival.game_state = STATE_MENU
                self.MoonSurvival.level = 1