根据习题描述,自己写了个移动火箭代码,程序运行无问题,但是不能移动火箭,习题各位大神能指点下代码哪里有问题。代码如下:
import pygame
import sys
def screen_main():
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('移动火箭')
bg_color = (193, 215, 192)
# 加载图片
image = pygame.image.load(r'images\timg.jpg')
# 获取图片的矩形区域
img_rect = image.get_rect()
# 获取窗口的矩形区域
screen_rect = screen.get_rect()
# 将窗口的矩形x坐标赋值给图片的矩形x坐标
img_rect.centerx = screen_rect.centerx
# 将窗口的矩形y坐标赋值给图片的矩形y坐标
img_rect.centery = screen_rect.centery
# 定义移动标志
moving_down = False
moving_up = False
moving_left = False
moving_right = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.type == pygame.K_DOWN:
moving_down = True
elif event.type == pygame.K_UP:
moving_up = True
elif event.type == pygame.K_LEFT:
moving_left = True
elif event.type == pygame.K_RIGHT:
moving_right = True
elif event.type == pygame.KEYUP:
if event.type == pygame.K_DOWN:
moving_down = False
elif event.type == pygame.K_UP:
moving_up = False
elif event.type == pygame.K_LEFT:
moving_left = False
elif event.type == pygame.K_RIGHT:
moving_right = False
if moving_left:
img_rect.centerx -= 1
if moving_right:
img_rect.centerx += 1
if moving_down:
img_rect.centery+= 1
if moving_up:
img_rect.centery -= 1
screen.fill(bg_color)
# 在屏幕上绘制image图片,第二个参数为目标参数
screen.blit(image, img_rect)
pygame.display.flip()
screen_main()