Pygame error font not initialized ошибка

I am currently making a small game but it is showing a strange error message. Namely:

'Pygame Error': Font Not Initialized

What does this mean?

This is my code:

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
    

And this is the error:

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

I am currently making a small game but it is showing a strange error message. Namely:

'Pygame Error': Font Not Initialized

What does this mean?

This is my code:

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
    

And this is the error:

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

Pygame – это библиотека на языке Python для создания 2D игр. Однако, при работе с этой библиотекой могут возникнуть некоторые проблемы, которые необходимо знать и решать. В этой статье мы рассмотрим различные проблемы с открытием игр на Pygame и их возможные решения.

Проблема 1: ошибка «Pygame.error: No video mode has been set»

Эта ошибка возникает из-за того, что игра не определяет разрешение экрана. Для решения этой проблемы необходимо указать размер окна при помощи следующих команд:

import pygame 

pygame.init() 

win = pygame.display.set_mode((500, 500)) 

Проблема 2: ошибка «pygame.error: font not initialized»

Данная ошибка возникает из-за того, что шрифты не были инициализированы. Чтобы решить эту проблему, необходимо инициализировать шрифты при помощи следующих команд:

import pygame 

pygame.init() 
pygame.font.init() 

Проблема 3: игра начинается в ограниченном режиме

Если игра начинается в ограниченном режиме, то это может быть вызвано ограничениями на использование видеокарты. Для решения этой проблемы рекомендуется проверить настройки видеокарты и обновить драйвера.

Проблема 4: замедленная работа игры

Замедленная работа игры может быть связана с недостаточной производительностью компьютера. Чтобы ускорить работу игры, необходимо закрыть другие приложения, которые также используют ресурсы компьютера. Также можно уменьшить качество графики в игре.

Проблема 5: игра зависает или вылетает

Если игра зависает или вылетает, то это может быть связано с ошибками в коде. Для решения этой проблемы необходимо проверить код на наличие ошибок, например, открыть консоль и просмотреть логи.

Заключение

В данной статье мы рассмотрели различные проблемы с открытием игр на Pygame и их возможные решения. Надеемся, что это поможет вам успешно разрабатывать свои игры на Python.

Итак, я решил начать игру, и я немного ее тестировал, а затем получил эту ошибку:

Traceback (most recent call last):
  File "TheAviGame.py", line 15, in <module>
    font = pygame.font.Font(None,25)
pygame.error: font not initialized

Я понятия не имею, что я сделал неправильно до сих пор…
Код:

#!/usr/bin/python
import pygame
blue = (25,25,112)
black = (0,0,0)
red = (255,0,0)
white = (255,255,255)
groundcolor = (139,69,19)
gameDisplay = pygame.display.set_mode((1336,768))
pygame.display.set_caption("TheAviGame")
direction = 'none'
clock = pygame.time.Clock()
img = pygame.image.load('player.bmp')
imgx = 1000
imgy = 100
font = pygame.font.Font(None,25)
def mts(text, textcolor, x, y):
    text = font.render(text, True, textcolor)
    gamedisplay.blit(text, [x,y])
def gameloop():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.pygame == pygame.KEYDOWN:
                if event.key == pygame.RIGHT:
                    imgx += 10
        gameDisplay.fill(blue)
        pygame.display.update()
        clock.tick(15)
gameloop()

ProgrammerAH

Programmer Guide, Tips and Tutorial

The pygame.init() function, which must be called after the pygame module is imported and before you start using any of the functions provided by PyGame, you don’t have to know what this function does, just know that in order to work with pyGame functions, you must call it at the beginning. If you run into an error like Pygame.error: font not initialized, check to see if you forgot to call Pygame.init () in front of your program

Read More:

Понравилась статья? Поделить с друзьями:
  • Pycharm проверка кода на ошибки
  • Pycharm поиск ошибок
  • Ps5 ошибка загрузки
  • Ps5 ошибка программного обеспечения
  • Pycharm ошибка при запуске