游戏字体属性

2024-04-16 17:06:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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\u font'

我觉得这个错误与pygame的安装有关。我通过MSVC运行python,并通过View>;Other Windows>;python环境安装Pygame。。我似乎无法使字体正常工作。我跟随一个教程试图从中学习,甚至复制粘贴的代码,为该教程的创建者工作,并得到相同的错误。谁能给我指出正确的方向吗?在

顺便说一句。。。不是整个代码。。我删掉了很多和字体无关的东西。。像width、screen等变量都是包含整个代码的有效变量。字体名称在中定义为“calibri”设置.py它与整个代码一起导入。。在


Tags: 代码textrectselfgametrueinitdef
1条回答
网友
1楼 · 发布于 2024-04-16 17:06:24

你下面的教程看起来不太好,有几点:

  • 你不需要做pg.font.init()如果你这样做了pg.init()docs
  • 如果要使用Sysfont(如calibri),则不需要先执行self.font_name = pg.font.match_font('calibri')操作,然后再执行pg.font.Font(self.font_name, size)。只需使用SysFont
  • self.all_sprites定义在哪里?您可以在draw中使用它,但我看不到initialize在哪里。在
  • 如果new()重置游戏,那么在游戏循环中调用它没有多大意义。另外,如果new()重置游戏,为什么它调用draw函数?在
  • ^{}代表声音。如果你不想播放任何声音,就不需要初始化它。另外,如果您不希望声音延迟,您必须在pg.init()之前初始化它,并使用^{}^{}
  • show_go_screen方法也丢失:/
  • ^{}方法没有接收到(0,0,0),它应该是((0,0,0))表示黑色。在
  • draw_text方法中,“白色”不是颜色,而是一个变量。您应该改用(255,255,255)。在

在所有这些之后:我的错误来自填充函数,而不是字体。在

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

修好这些之后。我没有任何错误。在

如果你懂西班牙语,我有一个带pygame https://github.com/Patataman/PythonBasic/tree/master/frameworks/pygame基础知识的回购协议。如果没有,也许你可以算出xD

相关问题 更多 >