Open a new window with pygame [duplicate]

2019-09-04 11:50发布

问题:

This question already has an answer here:

  • Pygame level/menu states 2 answers

I am making an arcade style game where if a player sprite collides with an enemy it should close the game screen and execute the Game over screen.py file which is the script for the Game Over Screen as the name suggests. My code which I used to try and do this is as follows:

def sprite_collide():
    global p_rect
    global e_rect
    if p_rect.colliderect(e_rect):
        execfile('Game Over Screen.py')

I have only just started making the game over screen so the code is as follows:

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

pygame.init() #initializes pygame window
pygame.display.set_caption('KeyCast') #titlebar caption

GOSURF=pygame.display.set_mode((900,600),0,32) #sets main surface

gobackground = pygame.image.load('Game Over.png') #background image for game

"""--------------------------------------------------------------------------"""
while True:

    def quitgame():
        """exits programme without any errors"""
        for event in pygame.event.get(): #quitting process
            if event.type==QUIT: #if player selects 'exit button' on window
                pygame.quit() #pygame quit
                sys.exit() #system quit
    quitgame()

    def Surface():
        GOSURF.blit(gobackground,(0,0)) #background image

    Surface()

    pygame.display.update()

However, whenever the sprite collides with the enemy I get the error message "NameError: global name 'GOSURF' is not defined""". Not sure what to do here.

Note: I have used a different name for the pygame surface in the game over screen which is GOSURF, whereas the original surface in the game script is just SURF.

回答1:

If you mean making multiple windows at the same time. You can't do that. It's a limitation of SDL (the underlying C library).

In your case you have to declare GOSURF global to reach it from your function.

def Surface():
    global GOSURF
    GOSURF.blit(gobackground,(0,0)) #background image


回答2:

Declared any new variables in the Game screen script as global within the script and it now works! Here's the bit I added, see the original question for full code:

gobackground = pygame.image.load('Game Over.png') #background image for game

global GOSURF
global gobackground

"""--------------------------------------------------------------------------"""
while True:

Will just continue to make variables global as I add them to the script.