我正在制作一个简单的火箭游戏,它需要移动一些精灵。在下面的代码中,每次按下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()
对于主游戏循环,第二次尝试使用
event.key
而不是event.type
。像这样:我注意到的另一个问题是,您没有在pygame中将图像转换为rect对象,然后使用
.blit
将其显示在屏幕上。.blit
函数需要一个rect对象参数,这就是您遇到问题的原因我还建议为您的精灵创建单独的类,以便更容易跟踪它们,如果您希望创建同一个精灵的副本,但仍保留单个类精灵的相同特征,可以通过从
pygame.sprite
导入函数Group
来实现有两个问题。首先,您的代码没有检查
event.key
中的pygame.K_UP
。但是您的代码也在(x, x)
绘制云,而不是(x, y)
更正代码:
相关问题 更多 >
编程相关推荐