首页 > 解决方案 > pygame字体属性错误

问题描述

import sys, pygame as pg, random




class Game:
    def __init__(self):
         #initialize game window, etc
         pg.init()
         pg.font.init()
         pg.mixer.init()
         self.screen = pg.display.set_mode((800, 600))
         pg.display.set_caption('myFirstGame')
         self.running = True
         self.font_name = pg.font.match_font('calibri')


    def new(self):
        #resets the game
        self.score = 0
        self.run()

    def run(self):
        #game loop
        self.playing = True
        while self.playing:
            self.draw()


    def draw(self):
         #game loop draw
         self.screen.fill(0, 0, 0)

         self.all_sprites.draw(self.screen)
         self.draw_text(str(self.score), 22, white, 800 / 2, 20)
         #after drawing everything, flip the display
         pg.display.flip()



    def draw_text(self, text, size, color, x, y):
        font = pg.font.Font(self.font_name, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        text_rect.midtop = (x, y)
        self.screen.blit(text_surface, text_rect)

 g = Game()
 while g.running:
     g.new()
     g.show_go_screen()

 pg.quit()

所以我正在关注教程并收到此错误...

AttributeError:模块“pygame.font”没有属性“match_font”

我觉得这个错误与 pygame 的安装有关。我正在通过 MSVC 运行 python 并通过 View > Other Windows > Python Environments 安装 Pygame .. 我似乎无法让字体工作。我正在关注一个教程,试图从中学习,甚至复制粘贴了适用于教程创建者的代码并得到相同的错误。谁能指出我正确的方向?

顺便说一句……它不是整个代码……我删掉了很多与字体无关的东西……宽度、屏幕等变量都是整个代码的有效变量。FONT_NAME 在 settings.py 中被定义为“calibri”,它与整个代码一起导入。

标签: pythonpygame

解决方案


您正在关注的教程看起来不太好,有几点:

  • 如果你这样做pg.font.init(),你不需要这样做pg.init()文档
  • 如果您要使用 Sysfont(如 calibri),则无需执行self.font_name = pg.font.match_font('calibri')then pg.font.Font(self.font_name, size). 只需使用SysFont
  • 定义在哪里self.all_sprites?您使用它,draw但我看不到在哪里初始化。
  • 如果new()重置游戏,在游戏循环中调用它没有多大意义。另外,如果new()重置游戏,为什么它会调用绘图函数?
  • mixer是为了声音。如果您不打算播放任何声音,则无需对其进行初始化。另外,如果您不想要声音延迟,则必须在pg.init()使用之前对其mixer.pre_init()进行初始化mixer.init()
  • show_go_screen方法也丢失了:/
  • fill方法不接收(0,0,0),它应该是((0,0,0))为黑色。
  • 在该draw_text方法中,“白色”不是颜色,而是变量。你应该(255,255,255)改用。

毕竟:我的错误来自填充功能,而不是字体。

修复它后,我之前指出的缺少变量/方法有一个错误。

在解决这一切之后。我没有任何错误。

如果你懂西班牙语,我有一个包含 pygame 基础知识的仓库https://github.com/Patataman/PythonBasic/tree/master/frameworks/pygame。如果没有,好吧,也许你可以弄清楚xD


推荐阅读