pygame screen not loading

Viewed 78

my error:

pygame 2.1.0 (SDL 2.0.16, Python 3.10.0)
Hello from the pygame community. >https://www.pygame.org/contribute.html
Traceback (most recent call last):
 File "c:\Users\Tameem\PycharmProjects\pythonProject\Games\Pygame_first_game.py", line 200, in <module>
   main()
 File "c:\Users\Tameem\PycharmProjects\pythonProject\Games\Pygame_first_game.py", line 194, in main
   main()
 File "c:\Users\Tameem\PycharmProjects\pythonProject\Games\Pygame_first_game.py", line 180, in main
   draw_winner(winner_text)
 File "c:\Users\Tameem\PycharmProjects\pythonProject\Games\Pygame_first_game.py", line 124, in draw_winner
   WIN.blit(draw_text, (WIDTH/2 -  draw_text.get_width()/2,  HEIGHT/2 - draw_text.get_height()/2))
pygame.error: display Surface quit

my code:

import pygame
import os

from pygame import display
pygame.font.init()

from pygame import event #opereting system


WIDTH, HEIGHT = 900, 500 #this is to make the WINDOW
WIN = pygame.display.set_mode((WIDTH, HEIGHT)) #your telling python that you want a window with this height and width
pygame.display.set_caption("Maisa Ahmed") #it sets a name for the game

DARK_GREEN = (00, 64, 00)
BLACK = (0, 0, 0)
BLOOD_RED = (136, 8, 8)
YELLOW = (255, 255, 0)
WHITE = (255, 255, 255)

health_font = pygame.font.SysFont("comicsans", 40)
winner_font = pygame.font.SysFont("comicsans", 100)

boarder = pygame.Rect(WIDTH//2-5, 0, 10, HEIGHT) # so i-5 because you want to draw it from 0 , 0 (left)
FPS = 60 #to contol how many times your game refersh per second
SPACESHIP_WIDTH , SPACESHIP_HEIGHT = 55,40
velocity = 5
Bullet_velocity = 7
MAX_BULLETS = 5

YELLOW_HITS = pygame.USEREVENT + 1 
RED_HITS = pygame.USEREVENT + 2

#importing images 

YELLOW_SPACESHIP_IMAGE = pygame.image.load(
    os.path.join('Assets', 'spaceship_yellow.png')) # assets to go in the that folder and which file

YELLOW_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(
    YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90) #so now the space ship is smaller and has rotated 



RED_SPACESHIP_IMAGE = pygame.image.load(
    os.path.join('Assets', "spaceship_red.png"))

RED_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(RED_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)),270)

background = pygame.transform.scale(pygame.image.load(
    os.path.join('Assets', 'space.png')), (WIDTH, HEIGHT)) #Mom.jpg




def draw_window(red ,yellow, red_bullets, yellow_bullets, red_health, yellow_health): #the order in which you draw matters
    WIN.blit(background, (0,0))
    #WIN.fill(DARK_GREEN) #to fill color to the WINDOW
    pygame.draw.rect(WIN, BLACK, boarder)

    red_health_text = health_font.render("health: " + str(red_health),1,WHITE )
    yellow_health_text = health_font.render("health: " + str(yellow_health),1,WHITE )
    
    WIN.blit(red_health_text, (WIDTH - red_health_text.get_width() - 10, 10))
    WIN.blit(yellow_health_text, (10, 10))
    
    

    WIN.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y))# you use blit when you want draw a surface on the screen (basically used to put the images/texts on the screen)
    WIN.blit(RED_SPACESHIP, (red.x, red.y)) #  are cordinates



    for bullet in red_bullets:
        pygame.draw.rect(WIN, BLOOD_RED, bullet)

    for bullet in yellow_bullets:
        pygame.draw.rect(WIN, YELLOW, bullet)

    pygame.display.update() #you have to update the WINDOW to show anychanges



def yellow_movement(keys_pressed, yellow):
        if keys_pressed[pygame.K_a] and yellow.x - velocity > 0: # left not allowing to cross the boarder
            yellow.x -= velocity
        if keys_pressed[pygame.K_d] and yellow.x + velocity + yellow.width < boarder.x: # right not allowing to cross the boarder
            yellow.x += velocity
        if keys_pressed[pygame.K_w] and yellow.y - velocity > 0: # up not allowing to cross the boarder
            yellow.y -= velocity
        if keys_pressed[pygame.K_s] and yellow.y + velocity + yellow.height < HEIGHT - 10: # down not allowing to cross the boarder
            yellow.y += velocity
def red_movement(keys_pressed, red):
        if keys_pressed[pygame.K_LEFT] and red.x - velocity > boarder.x + boarder.width: # left
            red.x -= velocity
        if keys_pressed[pygame.K_RIGHT] and red.x + velocity + red.width < WIDTH: # right
            red.x += velocity
        if keys_pressed[pygame.K_UP] and red.y - velocity > 0:# up
            red.y -= velocity
        if keys_pressed[pygame.K_DOWN] and red.y + velocity + red.height < HEIGHT - 10:  # down
            red.y += velocity
        

def handle_bullets(yellow_bullets, red_bullets, yellow, red):
    for bullet in yellow_bullets:
        bullet.x += Bullet_velocity

        if red.colliderect(bullet):
            pygame.event.post(event.Event(RED_HITS))
            yellow_bullets.remove(bullet)
        elif bullet.x > WIDTH:
            yellow_bullets.remove(bullet)


    for bullet in red_bullets:
        bullet.x -= Bullet_velocity

        if yellow.colliderect(bullet):
            pygame.event.post(event.Event(YELLOW_HITS))
            red_bullets.remove(bullet)
        elif bullet.x < 0:
            red_bullets.remove(bullet)

def draw_winner(text):
    draw_text = winner_font.render(text, 1, WHITE)
    WIN.blit(draw_text, (WIDTH/2 -  draw_text.get_width()/2,  HEIGHT/2 - draw_text.get_height()/2))

    pygame,display.update
    pygame.time.delay(5000)



def main():
    red = pygame.Rect(700, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)
    yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) # x,y , width , height 

    red_bullets = []
    yellow_bullets = []

    red_health = 10
    yellow_health = 10

    clock = pygame.time.Clock() # create a clock object which can be used to keep track of time
    run = True
    while run: #event loop
        clock.tick(FPS) #ensures that you will never go above the FPS you set the game on
        for event in pygame.event.get():
            if event.type == pygame.QUIT: #.QUIT to end pygame in the loop
                run = False
                pygame.quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LCTRL and len(yellow_bullets) < MAX_BULLETS:

                    bullet = pygame.Rect(
                        yellow.x + yellow.width, yellow.y + yellow.height//2 - 2,10,5) # so it goes from the middle 
                    yellow_bullets.append(bullet)

                if event.key == pygame.K_RCTRL and len(red_bullets) < MAX_BULLETS:

                    bullet = pygame.Rect(
                        red.x, red.y + red.height//2 - 2,10,5) # so it goes from the middle 
                    red_bullets.append(bullet)

            
            if event.type == RED_HITS:
                red_health -= 1

            if event.type == YELLOW_HITS:
                yellow_health -= 1


        winner_text = ''
        if red_health <= 0:
            winner_text = "Yellow WINS!"

        if yellow_health <= 0:
            winner_text = "Red WINS!"

        if winner_text == '':

            draw_winner(winner_text)
            break
        
      
        keys_pressed = pygame.key.get_pressed() # this tells us what keys are being clicked every 1
        yellow_movement(keys_pressed, yellow)
        red_movement(keys_pressed, red)

        handle_bullets(yellow_bullets, red_bullets, yellow, red)



        draw_window(red, yellow, red_bullets, yellow_bullets, red_health, yellow_health) #you took the yellow and red to the Drawing funcations 

    main()
    #pygame.quit .quit to end pygame in general


if __name__ == "__main__": #doesnt matter

    main()

the code was working fine until i added the winning messages , if you anyone has a fix please tell me.

2 Answers

The problem is that you call pygame.quit() in the application loop. You have to call pygame.quit() after the application loop:

def main():
    # [...]

    run = True
    while run: #event loop
        clock.tick(FPS) 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False 
                # pygame.quit()              <--- DELETE

        # [...]

    pygame.quit()                          # <--- INSERT  

Note, when pygame.quit() is executed, all PyGame modules will be uninstalled. Every further call to a PyGame function throws an exception.

I'd like to draw your attention to the block that, per comments, you just added.

        winner_text = ''
        if red_health <= 0:
            winner_text = "Yellow WINS!"

        if yellow_health <= 0:
            winner_text = "Red WINS!"

        if winner_text == '':

            draw_winner(winner_text)
            break

This will break out of the game loop the first time a non-winning condition is encountered, so probably directly at the start. You probably intended quite the opposite.

You might also want to make this compatible with the overall looping mechanism via the run variable, so either universally leave the loop via setting run=False or universally use the break keyword. This then leads to the point of the other answer, the clean-up should happen for all ways that the main loop can be exited, so best centralized after the loop.

Related