为什么当我在pygame中按下一个特定的键时,我的精灵没有移动

2024-10-02 00:43:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个简单的火箭游戏,它需要移动一些精灵。在下面的代码中,每次按下K_向下键时,cloud1都应该向底部移动-30像素。3天来,我一直在试图找出代码的错误,但一点进展都没有。非常感谢您的帮助

import pygame
pygame.init()

DISPLAY_HEIGHT = 700
DISPLAY_WIDTH = 900

screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption('Rocket Game')

clock = pygame.time.Clock()
FPS = 60


#colors
WHITE = (255,255,255)
BLACK = (0,0,0)
SKY_BLUE = (102,178,255)

cloud1 = pygame.image.load('cloud.png')
cloud1_X, cloud1_Y = 100, 50
cloud1_Y_change = 30


def cloud1_display(x, y):
    screen.blit(cloud1, (x, y))

running = True
while running:
    screen.fill(SKY_BLUE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                cloud1_Y += cloud1_Y_change

    cloud1_display(cloud1_X, cloud1_X)
    clock.tick(FPS)
    pygame.display.update()


    
    

Tags: 代码eventifdisplaywidthscreenpygamerunning
2条回答

对于主游戏循环,第二次尝试使用event.key而不是event.type。像这样:

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

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            cloud1_Y += cloud1_Y_change

我注意到的另一个问题是,您没有在pygame中将图像转换为rect对象,然后使用.blit将其显示在屏幕上。.blit函数需要一个rect对象参数,这就是您遇到问题的原因

cloud1 = pygame.image.load('asteroid_pic.bmp')
rect =  cloud1.get_rect()
screen.blit(cloud1, self.rect)

我还建议为您的精灵创建单独的类,以便更容易跟踪它们,如果您希望创建同一个精灵的副本,但仍保留单个类精灵的相同特征,可以通过从pygame.sprite导入函数Group来实现

有两个问题。首先,您的代码没有检查event.key中的pygame.K_UP。但是您的代码也在(x, x)绘制云,而不是(x, y)

更正代码:

while running:
    screen.fill(SKY_BLUE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:       # <<  HERE
                cloud1_Y += cloud1_Y_change

    cloud1_display(cloud1_X, cloud1_Y)         # <<  AND HERE
    clock.tick(FPS)
    pygame.display.update()

相关问题 更多 >

    热门问题