用python写一个飞机大战游戏
时间: 2023-05-28 11:07:07 浏览: 84
很抱歉,作为AI语言模型,我无法编写游戏,但我可以给您提供一个基本的游戏框架供参考:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 游戏界面大小
screen = pygame.display.set_mode((480, 700))
# 游戏标题
pygame.display.set_caption("飞机大战")
# 加载游戏背景
background = pygame.image.load("images/background.png")
# 加载玩家飞机图片
player = pygame.image.load("images/player.png")
player_rect = player.get_rect()
player_rect.centerx = 240 # 玩家飞机初始位置
player_rect.bottom = 650
# 设置玩家飞机移动速度
player_speed = 5
# 加载敌机图片
enemy1 = pygame.image.load("images/enemy1.png")
enemy1_rect = enemy1.get_rect()
# 设置敌机初始位置和移动速度
enemy1_rect.left = random.randint(0, 430)
enemy1_rect.top = -50
enemy1_speed = 2
# 加载子弹图片
bullet = pygame.image.load("images/bullet.png")
bullet_rect = bullet.get_rect()
# 设置子弹初始状态和速度
bullet_state = "ready"
bullet_speed = 5
# 加载游戏音效
pygame.mixer.music.load("sounds/game_music.wav")
pygame.mixer.music.play(-1)
bullet_sound = pygame.mixer.Sound("sounds/bullet.wav")
enemy_down_sound = pygame.mixer.Sound("sounds/enemy_down.wav")
game_over_sound = pygame.mixer.Sound("sounds/game_over.wav")
# 设置游戏字体
font = pygame.font.Font(None, 36)
# 设置游戏分数和生命值
score = 0
life = 3
# 游戏循环
while True:
# 监听退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 监听键盘事件
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_LEFT] and player_rect.left > 0:
player_rect.left -= player_speed
if key_pressed[pygame.K_RIGHT] and player_rect.right < 480:
player_rect.left += player_speed
if key_pressed[pygame.K_UP] and player_rect.top > 0:
player_rect.top -= player_speed
if key_pressed[pygame.K_DOWN] and player_rect.bottom < 700:
player_rect.top += player_speed
if key_pressed[pygame.K_SPACE]:
if bullet_state == "ready":
bullet_sound.play()
bullet_rect.centerx = player_rect.centerx
bullet_rect.bottom = player_rect.top
bullet_state = "fire"
# 移动敌机
enemy1_rect.top += enemy1_speed
if enemy1_rect.top > 700:
enemy1_rect.left = random.randint(0, 430)
enemy1_rect.top = -50
# 移动子弹
if bullet_state == "fire":
bullet_rect.bottom -= bullet_speed
if bullet_rect.top < 0:
bullet_state = "ready"
# 判断子弹和敌机是否碰撞
if bullet_state == "fire" and enemy1_rect.colliderect(bullet_rect):
enemy_down_sound.play()
bullet_state = "ready"
enemy1_rect.left = random.randint(0, 430)
enemy1_rect.top = -50
score += 10
# 判断敌机和玩家飞机是否碰撞
if enemy1_rect.colliderect(player_rect):
game_over_sound.play()
life -= 1
enemy1_rect.left = random.randint(0, 430)
enemy1_rect.top = -50
if life == 0:
pygame.quit()
exit()
# 显示游戏元素
screen.blit(background, (0, 0))
screen.blit(player, player_rect)
screen.blit(enemy1, enemy1_rect)
if bullet_state == "fire":
screen.blit(bullet, bullet_rect)
score_text = font.render("得分:" + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
life_text = font.render("生命:" + str(life), True, (255, 255, 255))
screen.blit(life_text, (10, 50))
# 刷新屏幕
pygame.display.update()
```
阅读全文