You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame游戏按下p键仅汽车精灵暂停,如何实现全局暂停

仅汽车精灵暂停的原因

你当前的paused状态判断仅放在事件循环内部,仅跳过了玩家移动、射击相关的按键事件处理,而事件循环外的子弹移动、障碍物下落、碰撞检测、精灵更新等核心游戏逻辑,无论是否暂停都会正常执行。你看到的汽车停止只是因为暂停后不再响应汽车的移动按键,其余游戏逻辑完全不受影响,所以出现仅汽车暂停的现象。

修复方案

将暂停判断提升到主循环的游戏逻辑层,暂停时直接跳过所有游戏逻辑的更新、渲染逻辑,仅保留退出、暂停切换的事件响应,保证全局冻结所有游戏逻辑完全停止。

修复后完整代码
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:
    # 统一处理所有事件,无论是否暂停都响应退出和暂停切换
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        elif event.type == pygame.KEYDOWN:
            # 暂停切换不受暂停状态影响
            if event.key == pygame.K_p:
                paused = not paused
            # 其余按键仅非暂停状态下响应
            if not paused:
                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

        # 按键抬起事件仅非暂停状态下响应
        elif event.type == pygame.KEYUP and not paused:
            if event.key == pygame.K_a:
                player.movingLeft = False
            if event.key == pygame.K_d:
                player.movingRight = False

    # 暂停状态下直接跳过所有游戏逻辑更新
    if not paused:
        #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()

内容的提问来源于stack exchange,提问作者J.R. BEATS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:15:03