I need to be able to pause the whole game, but only my car sprite pauses when I press the p key on my keyboard

Viewed 37

I implemented a pause feature in my game in the while loop at the end of my code, but the problem is that only my car sprite pauses. I have tried a bunch of different ways setting up my pause code but none of the ways I arrange it seems to pause the whole game.

I want to be able to pause my whole game when I press the p key on my keyboard, not just my car sprite. Can someone please tell me how I can fix this code? The code that will pause the whole game will be nice. Please, the rearranged code that will pause the whole game will help. Also I don't just want the answer, I want a quick explanation of why only my car sprite would pause instead of the whole game.

My code:

import random
import pygame
import pygame.freetype

pygame.init()

#screen settings
WIDTH = 1000
HEIGHT = 400

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("AutoPilot")
screen.fill((255, 255, 255))

#fps
FPS = 120
clock = pygame.time.Clock()

#load images
bg = pygame.image.load('background/street.png').convert_alpha() # background
bullets = pygame.image.load('car/bullet.png').convert_alpha()
debris_img = pygame.image.load('debris/cement.png')

#define game variables
shoot = False

#player class
class Player(pygame.sprite.Sprite):
    def __init__(self, scale, speed):
        pygame.sprite.Sprite.__init__(self)

        self.bullet = pygame.image.load('car/bullet.png').convert_alpha()
        self.bullet_list = []
        self.speed = speed
        #self.x = x
        #self.y = y
        self.moving = True
        self.frame = 0
        self.flip = False
        self.direction = 0
        self.score = 0

        #load car
        self.images = []
        img = pygame.image.load('car/car.png').convert_alpha()
        img = pygame.transform.scale(img, (int(img.get_width()) * scale, (int(img.get_height()) * scale)))
        self.images.append(img)
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.update_time = pygame.time.get_ticks()
        self.movingLeft = False
        self.movingRight = False
        self.rect.x = 465
        self.rect.y = 325

    #draw car to screen
    def draw(self):
        screen.blit(self.image, (self.rect.centerx, self.rect.centery))

    #move car
    def move(self):
        #reset the movement variables
        dx = 0
        dy = 0

        #moving variables
        if self.movingLeft and self.rect.x > 33:
            dx -= self.speed
            self.flip = True
            self.direction = -1
        if self.movingRight and self.rect.x < 900:
            dx += self.speed
            self.flip = False
            self.direction = 1

        #update rectangle position
        self.rect.x += dx
        self.rect.y += dy

    #shoot
    def shoot(self):
        bullet = Bullet(self.rect.centerx + 18, self.rect.y + 30, self.direction)
        bullet_group.add(bullet)

    #check collision
    def collision(self, debris_group):
        for debris in debris_group:
            if debris.health > 0 and pygame.sprite.spritecollide(debris, bullet_group, True):
                debris.health -= 1
                if debris.health <= 0:
                    self.score += 1

    #player stats/score
    def stats(self):
        myfont = pygame.font.SysFont('comicsans', 30)
        scoretext = myfont.render("Score: " + str(self.score), 1, (0,0,0))
        screen.blit(scoretext, (100,10))

#bullet class
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, direction):
        pygame.sprite.Sprite.__init__(self)

        self.speed = 5
        self.image = bullets
        self.rect = self.image.get_rect()
        self.rect.center = (x,y)
        self.direction = direction

    def update(self):
        self.rect.centery -= self.speed
        #check if bullet has gone off screen
        if self.rect.centery < 1:
            self.kill()

#debris class
class Debris(pygame.sprite.Sprite):
    def __init__(self,scale,speed):
        pygame.sprite.Sprite.__init__(self)

        self.scale = scale
        self.x = random.randrange(100,800)
        self.speed_y = 10
        self.y = 15
        self.speed = speed
        self.vy = 0
        self.on_ground = True
        self.move = True
        self.health = 4
        self.max_health = self.health
        self.alive = True
        self.velocity = random.randrange(1,2)
        self.speed_x = random.randrange(-3,3)
        self.moving_down = True
        self.is_destroyed = False

        #load debris
        self.image = debris_img
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(100, 800)
        self.rect.y = random.randrange(-150, -100)
        self.rect.center = (self.x,self.y)

        #load explosion
        self.img_explosion_00 = pygame.image.load('explosion/0.png').convert_alpha()
        self.img_explosion_00 = pygame.transform.scale(self.img_explosion_00, (self.img_explosion_00.get_width() * 2,
                                                                               self.img_explosion_00.get_height() * 2))
        self.img_explosion_01 = pygame.image.load('explosion/1.png').convert_alpha()
        self.img_explosion_01 = pygame.transform.scale(self.img_explosion_01, (self.img_explosion_01.get_width() * 2,
                                                                               self.img_explosion_01.get_height() * 2))
        self.img_explosion_02 = pygame.image.load('explosion/2.png').convert_alpha()
        self.img_explosion_02 = pygame.transform.scale(self.img_explosion_02, (self.img_explosion_02.get_width() * 2,
                                                                               self.img_explosion_02.get_height() * 2))
        self.img_explosion_03 = pygame.image.load('explosion/3.png').convert_alpha()
        self.img_explosion_03 = pygame.transform.scale(self.img_explosion_03, (self.img_explosion_03.get_width() * 2,
                                                                               self.img_explosion_03.get_height() * 2))
        #explosion list
        self.anim_explosion = [self.img_explosion_00,
                               self.img_explosion_01,
                               self.img_explosion_02,
                               self.img_explosion_03]
        self.anim_index = 0
        self.frame_len = 20 #frames before explosion animation disappears


    #spawn new debris
    def spawn_new_debris(self):
        self.rect.x = random.randrange(100, 800)
        self.rect.y = random.randrange(-150, -100)
        self.velocity = random.randrange(1, 2)
        self.speed_x = random.randrange(-3, 3)

    #respawn debris when they go of the screen
    def boundaries(self):
        if self.rect.left > WIDTH + 10 or self.rect.right < -10 or self.rect.top > HEIGHT + 10:
            self.spawn_new_debris()

    #update image
    def update(self):
        self.rect.y += self.velocity
        self.rect.x += self.speed_x
        self.boundaries()
        if self.health <= 0:
            max_index = len(self.anim_explosion) - 1
            if self.anim_index > max_index:
                self.kill()
            else:
                if self.frame_len == 0:
                    self.image = self.anim_explosion[self.anim_index]
                    self.anim_index += 1
                    self.frame_len = 20
                else:
                    self.frame_len -= 1

    #make debris fall down
    def falldown(self):
        self.rect.centery += self.velocity
        if self.moving_down and self.rect.y > 350:
            self.kill()

######################CAR/DEBRIS##########################

player = Player(1,5)

##########################################################

#groups
bullet_group = pygame.sprite.Group()
debris_group = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()

for x in range(100):
    d = Debris(1, 5)
    debris_group.add(d)
    all_sprites.add(d)

#game runs here
run = True
paused = False
while run:

    #draw street
    screen.blit(bg, [0, 0])

    #update groups
    bullet_group.update()
    bullet_group.draw(screen)

    debris_group.update()
    debris_group.draw(screen)

    #draw car
    player.draw()
    player.move()
    player.collision(debris_group)
    player.stats()

    #update all sprites
    all_sprites.update()
    all_sprites.draw(screen)

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

        #pause game
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_p:
                paused = not paused

        if paused == True:
            continue

        #check if key is down
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                run = False
            if event.key == pygame.K_a:
                player.movingLeft = True
            if event.key == pygame.K_d:
                player.movingRight = True
            if event.key == pygame.K_SPACE:
                player.shoot()
                shoot = True

        #check if key is up
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                player.movingLeft = False
            if event.key == pygame.K_d:
                player.movingRight = False

    #update the display
    pygame.display.update()
    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()
1 Answers

Move your

for event in pygame.event.get():

right below the while loop, and move your

    if paused:
        continue

below the for loop, like so:

run = True
paused = False
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        #pause game
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_p:
                paused = not paused

        #check if key is down
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                run = False
            if event.key == pygame.K_a:
                player.movingLeft = True
            if event.key == pygame.K_d:
                player.movingRight = True
            if event.key == pygame.K_SPACE:
                player.shoot()
                shoot = True

        #check if key is up
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                player.movingLeft = False
            if event.key == pygame.K_d:
                player.movingRight = False

    if paused:
        continue
                
    #draw street
    screen.blit(bg, [0, 0])

    #update groups
    bullet_group.update()
    bullet_group.draw(screen)

    debris_group.update()
    debris_group.draw(screen)

    #draw car
    player.draw()
    player.move()
    player.collision(debris_group)
    player.stats()

    #update all sprites
    all_sprites.update()
    all_sprites.draw(screen)

    #update the display
    pygame.display.update()
    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()

The reason only your car sprite paused when you pressed the q key is because, as you can see in your original code here:

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

        #pause game
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_p:
                paused = not paused

        if paused == True:
            continue

you put the

        if paused == True:
            continue

inside the for loop, not the while loop, so the lines that move the car would be blocked, but the rest of the code within the while loop will still get executed.

Related