可以帮我写一个飞机大战小游戏吗
时间: 2023-10-06 20:10:13 浏览: 46
当然可以!以下是一个简单的飞机大战小游戏的示例代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口大小
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("飞机大战")
# 加载背景音乐
pygame.mixer.music.load("background_music.wav")
pygame.mixer.music.play(-1) # 播放背景音乐,-1代表循环播放
# 加载飞机图片
player_img = pygame.image.load("player.png")
player_width = 80
player_height = 60
# 加载敌机图片
enemy_img = pygame.image.load("enemy.png")
enemy_width = 60
enemy_height = 45
# 设置玩家初始位置
player_x = window_width // 2 - player_width // 2
player_y = window_height - player_height - 10
# 设置敌机初始位置和速度
enemy_x = random.randint(0, window_width - enemy_width)
enemy_y = -enemy_height
enemy_speed = 3
# 初始化分数
score = 0
font = pygame.font.Font(None, 36)
# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
clock.tick(60) # 控制游戏帧率为60帧
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动玩家飞机
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= 5
if keys[pygame.K_RIGHT] and player_x < window_width - player_width:
player_x += 5
# 移动敌机
enemy_y += enemy_speed
# 判断敌机是否超出屏幕
if enemy_y > window_height:
enemy_x = random.randint(0, window_width - enemy_width)
enemy_y = -enemy_height
score += 1
# 绘制游戏场景
window.fill((255, 255, 255)) # 白色背景
# 绘制玩家飞机
window.blit(player_img, (player_x, player_y))
# 绘制敌机
window.blit(enemy_img, (enemy_x, enemy_y))
# 绘制分数
score_text = font.render("Score: " + str(score), True, (0, 0, 0)) # 黑色
window.blit(score_text, (10, 10))
# 判断是否碰撞
if player_x < enemy_x + enemy_width and player_x + player_width > enemy_x and player_y < enemy_y + enemy_height and player_y + player_height > enemy_y:
running = False
pygame.display.flip() # 更新屏幕显示
# 游戏结束
pygame.quit()
```
请注意,这只是一个简单的示例代码,您可以根据自己的需求和喜好进行修改和扩展。同时,您还需要准备飞机和敌机的图片资源,并将图片文件名替换为相应的文件。祝您玩得愉快!