pygame.quit () выдаёт ошибку init.font при переключении файлов - PullRequest
0 голосов
/ 21 января 2020

Я сделал основной python файл, который содержит всю игру, и для каждого окна я использую разные файлы. Например, для начала игры я хочу создать окно, в котором вы можете выбрать язык с 2 полями, что делает переменную = 1 или 2. Основной файл читает переменную и с условием if определяется язык .

Основная проблема заключается в том, что когда я хочу закрыть языковой файл и продолжить работу с основным, появляется сообщение об ошибке, в котором говорится, что шрифт не был определен при выполнении pygame.quit ()

ГЛАВНЫЙ ФАЙЛ

import pygame
from lib.pygame_functions import *
from pygame.locals import *
import time
import random

def language():
    import lib.language.languageVS
    from lib.language.languageVS import lang

language()
pygame.quit()

if lang == '1':
    from languages.en import *
    lang_selection = 1
    print(selection_language)
elif lang == '2':
    from languages.es import *
    lang_selection = 1
    print(selection_language)


pygame.init()

white = (255,255,255)
black = (0,0,0)
green = (0, 200, 0)
red = (200, 0, 0)
blue = (0, 0, 200)
bright_green = (0, 255, 0)
bright_red = (255, 0, 0)
bright_blue = (0, 0, 255)

introbackground = pygame.image.load('introbg.png')

gameDisplay = pygame.display.set_mode((800, 600)) #surface
pygame.display.set_caption('Neon Fight') #titutlo

def names():
    import lib.playernames.TEXTINPUT
    from lib.playernames.TEXTINPUT import a
    print(a)
    import lib.playernames.TEXTINPUT2
    from lib.playernames.TEXTINPUT2 import b
    print(b)


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

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    pygame.display.update()

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

def game():
    time.sleep(4)

def startgame():
    pygame.quit()
    names()
    game()

def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed()

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

    smallText = pygame.font.Font('freesansbold.ttf', 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x+(w/2)), (y+(h/2)))
    gameDisplay.blit(textSurf, textRect)


def game_intro():

    intro = True

    while intro:
        gameDisplay.blit(introbackground, (0, 0))
        #gameDisplay.fill(white)
        mouse = pygame.mouse.get_pos() 
        #print(mouse)


        #BUTTONS
        button('Play', 350, 325, 100, 50, green, bright_green, startgame)
        button('Instructions', 350, 400, 100, 50, blue, bright_blue)  
        button('Quit', 350, 475, 100, 50, red, bright_red, quitgame)  


        pygame.display.update()

        #quit_x
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT:
                gameExit = True
                pygame.quit() #desinizialization
                quit()
game_intro()


gameExit = False 


while not gameExit: #quit_x
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True


    gameDisplay.fill(white)
    pygame.display.update() #actualizar_surface

pygame.quit() #desinizialization
quit()

lib.language.languageVS

import pygame
from pygame.locals import *
import time
import random

lang = 0

pygame.init() #inizialization

white = (255,255,255)
black = (0,0,0)
green = (0, 200, 0)
red = (200, 0, 0)
blue = (0, 0, 200)
bright_green = (0, 255, 0)
bright_red = (255, 0, 0)
bright_blue = (0, 0, 255)

gameDisplay = pygame.display.set_mode((800, 600)) #surface
pygame.display.set_caption('Neon Fight') #titutlo

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

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    pygame.display.update()

def english():
    global lang
    lang = 1
    pygame.quit()

def spanish():
    global lang
    lang = 2
    pygame.quit()

def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed()

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

    smallText = pygame.font.Font('freesansbold.ttf', 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x+(w/2)), (y+(h/2)))
    gameDisplay.blit(textSurf, textRect)


def language():


    language = True

    while language:
        gameDisplay.fill(white)
        mouse = pygame.mouse.get_pos() 
        #print(mouse)


        #BUTTONS
        button('Play', 350, 325, 100, 50, green, bright_green, spanish)
        button('Instructions', 350, 400, 100, 50, blue, bright_blue, english)  


        pygame.display.update()

        #quit_x
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT:
                gameExit = True
                pygame.quit() #desinizialization
                quit()
language()

gameExit = False 

while not gameExit: #quit_x
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True


    gameDisplay.fill(white)
    pygame.display.update() #actualizar_surface

TRACEBACK:

Exception has occurred: error
font not initialized
  File "F:\APPVISUAL\lib\language\languageVS.py", line 55, in button
    smallText = pygame.font.Font('freesansbold.ttf', 20)
  File "F:\APPVISUAL\lib\language\languageVS.py", line 73, in language
    button('Play', 350, 325, 100, 50, green, bright_green, spanish)
  File "F:\APPVISUAL\lib\language\languageVS.py", line 85, in <module>
    language()

Ответы [ 2 ]

1 голос
/ 21 января 2020

Простым решением было бы добавить pygame.init () до

smallText = pygame.font.Font('freesansbold.ttf', 20)

0 голосов
/ 23 января 2020

удалось решить. Видимо просто смена функции сработала. Я подумал, что вместо того, чтобы использовать pygame.quit () для закрытия модуля pygame, я мог бы просто добавить все на al oop и всякий раз, когда выбрана опция, l oop прекращает работу и позволяет коду самому завершаться, не форсируя Это. Таким образом, я могу импортировать его в основной файл, и код продолжает работать! Вот какой код находится в файле lib.languageVS:

import pygame
from pygame.locals import *
import time
import random
import sys

lang = 0

pygame.init() #inizialization

white = (255,255,255)
black = (0,0,0)
green = (0, 200, 0)
red = (200, 0, 0)
blue = (0, 0, 200)
bright_green = (0, 255, 0)
bright_red = (255, 0, 0)
bright_blue = (0, 0, 255)

gameDisplay = pygame.display.set_mode((800, 600)) #surface
pygame.display.set_caption('Neon Fight') #titutlo

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

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    pygame.display.update()

def english():
    global lang
    lang = 1

def spanish():
    global lang
    lang = 2

def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed()

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

    smallText = pygame.font.Font('freesansbold.ttf', 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x+(w/2)), (y+(h/2)))
    gameDisplay.blit(textSurf, textRect)

def language():

    language = True

    while language == True:

        gameDisplay.fill(white)
        mouse = pygame.mouse.get_pos() 
        #print(mouse)

        #BUTTONS
        button('SPANISH', 350, 325, 100, 50, green, bright_green, spanish)
        button('ENGLISH', 350, 400, 100, 50, blue, bright_blue, english)  

        if lang == 1:
            language = False
        elif lang == 2:
            language = False

        pygame.display.update()

        #quit_x
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT:
                gameExit = True
                pygame.quit() #desinizialization

language()


##OLD_VERSION
# def language():


#     language = True

#     while language:
#         gameDisplay.fill(white)
#         mouse = pygame.mouse.get_pos() 
#         #print(mouse)


#         #BUTTONS
#         button('SPANISH', 350, 325, 100, 50, green, bright_green, spanish)
#         button('ENGLISH', 350, 400, 100, 50, blue, bright_blue, english)  

#         pygame.display.update()





#         #quit_x
#         for event in pygame.event.get(): 
#             if event.type == pygame.QUIT:
#                 gameExit = True
#                 pygame.quit() #desinizialization
#         if lang == 1:
#             pygame.quit()
#         elif lang == 2:
#             pygame.quit()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...