简体   繁体   中英

Import loop only works twice, gives pygame.error Display surface quit

I am in a beginner python class and we are working on our final projects. For my game however I wanted to be able to restart the game within itself. I did this by using imports to launch a new script to then re-run my game. However whenever I try to do it more than once my window breaks, or the code does not import the next file. My game is kinda long so I've created a very short program to give an example of my issue.

(This being the file yin.py)

import pygame

BLACK = (0, 0, 0) 
pygame.init()
SIZE = [300, 300]
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()

done = False
while not done:

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            import yang
            done = True
    
    screen.fill(BLACK)

    pygame.display.flip()
    clock.tick(30)

pygame.quit()

(and this file yang.py)

import pygame

WHITE = (255, 255, 255) 
pygame.init()
SIZE = [300, 300]
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()

done = False
while not done:

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            import yin 
            done = True
    
    screen.fill(WHITE)

    pygame.display.flip()
    clock.tick(30)

pygame.quit()

I've tried doing multiple things but so far I have gotten nowhere, it still is giving me display not initialized even though I have 'pygame.init()'. My teacher isn't responding to my emails and I have an encroaching deadline. Any help will be appreciated. :p

The "import" statement only imports once. If the name already exists, it doesn't import again. You should put your code into a function. Then, you can call the function as many times as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM