python - 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”,它与整个代码一起导入。
解决方案
您正在关注的教程看起来不太好,有几点:
- 如果你这样做
pg.font.init()
,你不需要这样做pg.init()
(文档) - 如果您要使用 Sysfont(如 calibri),则无需执行
self.font_name = pg.font.match_font('calibri')
thenpg.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
推荐阅读
- angular - Ionic App 在更新到 Angular 8 后中断 -> 无法解析 setupPlatform 的所有参数:(?, ...)
- python - Python:“系列”对象是可变的,因此它们不能被散列
- c# - 在 Xamarin.MAC 上使用 WebView 时出错
- .net - QuillJS 与 .net blazor 最大字符串长度
- indexing - Rust 无法索引类型为 'datatype<{integer}, {integer}>` 的值
- python - 如何使用 gitpython 删除特定分支
- java - Spring boot 错误创建名称为 Error 的 bean
- php - 循环由 mysql 查询中的逗号分隔值创建的数组,仅获取第一个结果
- c++ - 除了提供必要的保证之外,硬件内存屏障是否可以更快地看到原子操作?
- php - Laravel - 从中间件调用服务类 - 类 App\Http\Middleware\** 不存在