问题描述
我正在构建一个简单的火箭游戏,它需要移动一些精灵。在cloud1下面的代码中,每当我按K_DOWN键时,应该向底部移动-30个像素。我已经尝试了三天,弄清楚代码出了什么问题,但是甚至没有进步。帮助将不胜感激。
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)
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
中的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()
,
对于您的主要游戏循环,请尝试第二次使用Left
而不是Either<?,Integer>
。像这样:
event.key
我注意到的另一个问题是您没有将图像转换为pygame中的rect对象,然后使用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
函数需要一个rect object参数,所以这就是您遇到问题的原因。
.blit
我还建议为您的sprite创建单独的类,以便更轻松地跟踪它们,如果您想创建同一sprite的副本,但仍保留单个class sprite的相同特征,则可以通过导入.blit
中的函数cloud1 = pygame.image.load('asteroid_pic.bmp')
rect = cloud1.get_rect()
screen.blit(cloud1,self.rect)
。