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

Pygame多文件开发中小车精灵按键移动无响应问题如何解决

代码核心问题

    1. 主循环中从未调用Car类的move()方法,按键只是修改了movingLeft/movingRight属性,没有执行移动逻辑
    1. move()方法只更新了精灵的rect.x/rect.y坐标,但draw()方法渲染时用的是未同步的self.x/self.y变量,位置不会变化
    1. car.py中重复调用pygame.display.set_mode()创建了新的窗口对象,和autopilot.py的主窗口不共用,渲染逻辑混乱
    1. Car类初始化时没有把传入的x/y赋值给self.rect.x/self.rect.y,rect初始位置和实际渲染位置不匹配
    1. Car实例化时参数传错:Car类__init__接收的第四个参数是speed,但实例化时只传了3个参数,会直接报错

修正后的代码示例

1. car.py 代码

import pygame

WIDTH = 1000
HEIGHT = 400

#car class
class Car(pygame.sprite.Sprite):
    def __init__(self, x, y, scale, speed):
        pygame.sprite.Sprite.__init__(self)

        self.speed = speed
        self.x = x
        self.y = y
        self.moving = True
        self.movingLeft = False
        self.movingRight = False
        self.frame = 0
        self.flip = False
        self.direction = 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()
        # 同步初始坐标到rect
        self.rect.x = x
        self.rect.y = y
        self.update_time = pygame.time.get_ticks()

    #draw car to screen,传入主窗口对象避免冲突
    def draw(self, screen):
        # 用rect的坐标渲染,和移动逻辑同步
        screen.blit(self.image,(self.rect.x, self.rect.y))

    #move car
    def move(self):
        dx = 0
        # 加边界判断防止小车移出窗口
        if self.movingLeft and self.rect.left > 0:
            dx = -self.speed
            self.flip = True
            self.direction = -1
        if self.movingRight and self.rect.right < WIDTH:
            dx = self.speed
            self.flip = False
            self.direction = 1

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

2. autopilot.py 调整后代码

"""
BUGS LIST:
FIXED = No longer a bug in software
-------------------------------------------
FIXED(10-27-21: Having problems with the debris class (def draw_debris) function. The game outputs to the
screen but does not spawn in the cement block sprites from the top as I intended.)
---------------------------------------------------------------------------------------------------------
FIXED(10-28-21: I can now spawn in a cement block at the top of the pygame window except I want to be
able to spawn in multiple of the same cement block along the top at different locations
not just have the same cement block sprite change its location randomly.)
---------------------------------------------------------------------------------------------------------
10-28-21: Having trouble making car sprite move.

"""

import pygame
import debris
import car

pygame.init()

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()

#background img
bg = pygame.image.load('background/street.png').convert_alpha()


#define variables


######################CAR/DEBRIS##########################
# 补全speed参数,第四个值为小车移动速度
car = car.Car(475,200,5, 3)
debris = debris.Debris(1,5)

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

#groups
car_group = pygame.sprite.Group()
car_group.add(car)

debris_group = pygame.sprite.Group()
debris_group.add(debris)


#simulation runs here
run = True
while run:

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

    # 每帧调用小车移动方法
    car.move()

    #update groups
    car_group.update()
    debris_group.update()

    #draw debris
    debris.draw()
    debris.fall()

    #draw car,传入主窗口
    car.draw(screen)

    #if y coordinate is > 0
    if debris.y > 0:
        debris.collide()


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

        #check if key is down
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                run = False
            if event.key == pygame.K_a:
                car.movingLeft = True
            if event.key == pygame.K_d:
                car.movingRight = True
        #check if key is up
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                car.movingLeft = False
            if event.key == pygame.K_d:
                car.movingRight = False

    #update the display,删除重复的flip调用
    pygame.display.update()
    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.28 04:24:03