Pygame error font not initialized ошибка

So I decided to start making a game and I was testing it a bit and then I got this error:

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

I have no idea what I have done wrong so far…
Code:

#!/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()

Итак, у меня возникает эта ошибка pygame.error: font not initialized, и я устал исправлять, делая отступы, не идентифицировал его, менял шрифт и другие вещи, но он все еще не работает. Это в моем STARTMENUE. Я также пробовал использовать другой шрифт, думая, что это проблема, но это не так.

Были ли у меня проблемы

largeText = pygame.font.Font('freesansblod.ttf',115)

Мой полный код

import pygame

#set screen
window = pygame.display.set_mode((500,500))

#set Name
pygame.display.set_caption("Noob")


class Player:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.color = color
        self.speed = 0
        self.isJump = False
        self.JumpCount = 10
        self.fall = 0
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.topleft = (self.x,self.y)

class Floor:
    def __init__ (self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)


class Coin():
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.topleft = (self.x,self.y)
        self.draw.rect(self.color,self.rect)
    


white = (255,255,255)

green = (0,200,0)

red = (255,0,0)

drakred = (200,0,0)

darkgreen = (0,200,0)

black = (0,0,0)
 
player1 = Player(50,400,40,40,white)

coin = Coin(100,300,30,30,red)

floor1 = Floor(0,400,600,30,green)



fps = (30)

clock = pygame.time.Clock()

###########################################
#START MENUE
def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    #print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(window, ac,(x,y,w,h))

        if click[0] == 1 and action != None:
            action()         
    else:
        pygame.draw.rect(window, ic,(x,y,w,h))

    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    window.blit(textSurf, textRect)

def quitgame():
    pygame.quit()
    
def game_intro():
    

    intro = True

    while intro:
        for event in pygame.event.get():
            #print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        
        window.fill((255,255,255))
        largeText = pygame.font.Font('freesansblod.ttf',115)
        TextSurf, TextRect = text_objects("Jump", largeText)
        TextRect.center = ((500/2),(500/2))
        window.blit(TextSurf, TextRect)

        button("GO!",100,350,100,50,green,darkgreen,main_loop)
        button("Quit!",300,350,100,50,orange,darkred,quitgame)

        pygame.display.update()
        clock.tick(15)

###############################################



def main_loop():
    def redrawwindow():
        window.fill((0,0,0))

            
        player1.draw()
        coin1.draw()
        floor1.draw()


        window.blit(text,textRect)

        font = pygame.font.Font("freesansblod.ttf",30)
        score = 0
        text = ("Coin"+str(score),True,(255,255,255))
        textRect = text.get_rect()
        textRect.center = ((100,40))

        run = True
        while run:
            for event in pygame.event.get():
                if event.type == pygame.QUIT():
                    run = False

            for Coin in coin1:
                for coin1 in range(len(coin)-1-1-1):
                    if player1.rect.colliderect(coin1[one].rect):
                        del coin1[one]
                        score += 1
                        text = pygame.font.Font("blod.ttf",30)
                        textRect.center ((100,40))
                            
                        
                        



            key = pygame.key.get_pressed()
                    
            if key[pygame.K_a]:
                player1.x -= player1.speed

            if key[pygame.K_d]:
                player1.x += player1.speed

            if key[pygame.K_w]:
                player1.y -= player1.speed
            if key[pygame.K_s]:
                player1.y += player1.speed



        redrawwindow()
        pygame.display.update()
    pygame.quit()
game_intro()
main_loop()
                           

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import pygame
pygame.init() # чтобы курсив загружался 
import sys  # для того когда икс нажимаешь ошибки не было
 
WHITE = (255, 255, 255)  # цвет белый
BLACK = (0, 0, 0)        # веет черный
 
window = pygame.display.set_mode((400, 430))  # Создал окно с размером 400, 430
pygame.display.set_caption('hello py game')   # Имя окно
 
screen = pygame.Surface((400, 400))  # Создаю белый фон внутри window с размером (400, 400)
screen.fill(WHITE)  # Присваиваю фону белый цвет
 
strin = pygame.Surface((400, 60))  # Создаю черный фон внутри window с размером (400, 60)                  
strin.fill(BLACK)  # Присваиваю фону черный цвет
 
courier = pygame.font.SysFont('courier', 36)  # Создал шрифт который будем использовать для написание текста
 
while True:  # Создал цикл пока икс не нажато в окне программа работает
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # как только икс нажимаешь прог закрывается
            pygame.quit()
            sys.exit()
    
    window.blit(screen, (0, 0))  # Присваиваю нашему главному окну наш белый фон, он начинается с координаты 0, 0
    screen_text = courier.render("Text ", 0, BLACK)  # Создал Текст со светом черный
    screen.blit(screen_text, (100, 100))  # Присваивал ему координаты который будет отрабражатся на белом фоне
    
    window.blit(strin, (0, 0))  # Присваиваю нашему главному окну наш черный фон, он начинается с координаты 0, 0
    strin_text = courier.render("Text_TEXT ", 0, WHITE)  # Создал Текст_ТЕКСТ со светом Белый
    window.blit(strin_text, (25, 25))  # Присваивал ему координаты который будет отрабражатся на черном фоне
    
    pygame.display.flip()

The problem is that you’re setting the font before initializing the game. To fix this, move font = pygame.font.SysFont(None, 30) after pygame.init().

Also, for your code to work, you’ll need to define TEXTCOLOR as well. It should be a tuple with RGB values eg. TEXTCOLOR = (255, 255, 255) for white (you can put it at the top with the WINDOWHEIGHT).

beginner here, im trying to make a snake game and i get this error what does it mean, and how to solve it

Traceback (most recent call last):

File «C:UsersKhaledPycharmProjectspySnakemain.py», line 24, in <module>

massage_font = pygame.font.SysFont(‘ubuntu’, 25)

File «C:UsersKhaledPycharmProjectspySnakevenvlibsite-packagespygamesysfont.py», line 415, in SysFont

return constructor(fontname, size, set_bold, set_italic)

File «C:UsersKhaledPycharmProjectspySnakevenvlibsite-packagespygamesysfont.py», line 333, in font_constructor

font = Font(fontpath, size)

pygame.error: font not initialized

Process finished with exit code 1

  • Pycharm ошибка при установке пакетов
  • Python обработка ошибок valueerror
  • Python try обработка ошибок
  • Pycharm ошибка при установке модуля
  • Python не закрывать консоль при ошибке