Меню

Pygame error font not initialized ошибка

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()

Итак, у меня возникает эта ошибка 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()
                           

Here is my code:

import pygame, random, color, sys  #color is a module I made containing a list of variables with RGB values
pygame.init



Dice1 = pygame.image.load("Dice1.png")
Dice2 = pygame.image.load("Dice2.png")
Dice3 = pygame.image.load("Dice3.png")
Dice4 = pygame.image.load("Dice4.png")
Dice5 = pygame.image.load("Dice5.png")
Dice6 = pygame.image.load("Dice6.png")

Dice = [Dice1,Dice2,Dice3,Dice4,Dice5,Dice6]

splash = ["Bet until you're broke!","Rags to riches, and back to rags again","You aren't depending on this money, right?","Snake Eyes","MONEY!","Cause I'm a gambler","double or nothing"]

Random_Splash = random.choice(splash)

Window_Size = 600
screen = pygame.display.set_mode((Window_Size,Window_Size))
pygame.display.set_caption('Gamble: ' + Random_Splash)
screen.fill(color.maroon)    #refrincing color module
pygame.display.update()
icon = random.choice(Dice)
pygame.display.set_icon(icon)

def main():

    def TEXT(size,Color,msg,x=0,y=0):
        if size == 1:
            Font = pygame.font.SysFont("None",15)
        elif size == 2:
            Font = pygame.font.SysFont("None",30)
        elif size == 3:
            Font = pygame.font.SysFont("None",45)
        elif size == 4:
            Font = pygame.font.SysFont("None",60)

        text = Font.render(msg,True,Color)
        
        screen.blit(text,(x,y))


    while True:



        TEXT(2,color.red,"Hi")    #refrincing color module

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()


main()

I then get an error in sysfont itself, not in my program, saying  

Error:

error: font not initialized

Posts: 5,147

Threads: 395

Joined: Sep 2016

Reputation:
170

Quote:pygame.init

needs to be

pygame.init()

Posts: 41

Threads: 19

Joined: Jan 2017

Reputation:
1

wow…how did I miss that, thanks

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

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