import pygame
pygame.init()
# 设置游戏窗口大小
screen_width = 480
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("打飞机游戏")
# 加载游戏背景图片
bg_img = pygame.image.load("background.png")
# 设置玩家飞机
player_img = pygame.image.load("player.png")
player_rect = player_img.get_rect() # 矩形大小和位置
player_rect.centerx = screen_width // 2 # 初始位置为屏幕中央
player_rect.bottom = screen_height - 20 # 初始位置在底部
player_speed = 5 # 飞机移动速度
# 设置敌方飞机
enemy_img = pygame.image.load("enemy.png")
enemy_rect = enemy_img.get_rect()
# TODO:随机生成敌机位置
# 设置子弹
bullet_img = pygame.image.load("bullet.png")
bullet_rect = bullet_img.get_rect()
bullet_rect.centery = player_rect.top # 子弹发射位置在飞机顶部
bullet_speed = 10 # 子弹射速
# 游戏循环
while True:
# 监听游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT: # 关闭游戏窗口
pygame.quit()
sys.exit()
# 玩家移动
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT]:
player_rect.x -= player_speed
if keys_pressed[pygame.K_RIGHT]:
player_rect.x += player_speed
# 子弹发射
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_SPACE]:
pass # TODO:发射子弹
# 敌方飞机移动
# 碰撞检测
# 绘制游戏界面
screen.blit(bg_img, (0, 0))
screen.blit(player_img, player_rect)
screen.blit(enemy_img, enemy_rect)
screen.blit(bullet_img, bullet_rect)
# 刷新游戏界面
pygame.display.update()