这个错误是什么意思? Pygame错误:字体未初始化

时间:2019-05-01 10:53:30

标签: python-3.x pygame

我目前正在做一个小游戏,但显示了一个奇怪的错误消息。即:

'Pygame Error': Font Not Initialized

这是什么意思?请注意,我是一个初学者。

我正在使用Python3。

这是我的代码:

import pygame, random, sys, os, time
import sys
from pygame.locals import *
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
levens = 3
dead = False
Mousevisible = False

def terminate():
    pygame.quit()
    sys.exit()

def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE: #escape quits
                    terminate()
                return

def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)
#fonts
font = pygame.font.SysFont(None, 30)

#def gameover():
    #if dead == True:
        #pygame.quit

# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('hit the blocks')
pygame.mouse.set_visible(Mousevisible)

# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)+30)
pygame.display.update()
waitForPlayerToPressKey()
zero=0

这是错误:

Traceback (most recent call last):
  File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\schietspel.py", line 30, in <module>
    font = pygame.font.SysFont(None, 30)
  File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sysfont.py", line 320, in SysFont
    return constructor(fontname, size, set_bold, set_italic)
  File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sysfont.py", line 243, in font_constructor
    font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized

2 个答案:

答案 0 :(得分:1)

问题是您在初始化游戏之前设置了字体。要解决此问题,请将font = pygame.font.SysFont(None, 30)移到pygame.init()之后。

此外,为了使代码正常工作,您还需要定义TEXTCOLOR。它应该是具有RGB值的元组。 TEXTCOLOR = (255, 255, 255)代表白色(您可以将WINDOWHEIGHT放在顶部)。

答案 1 :(得分:0)

我认为您必须初始化pygame.font。

pygame.font.init()之后尝试from pygame.locals import *