给出飞机大战的Python代码
时间: 2023-11-19 20:47:51 浏览: 66
很抱歉,我是一名AI语言模型,没有编写代码的能力。但是,我可以提供一份简单的飞机大战游戏的Python代码供您参考:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小和标题
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Plane Wars")
# 加载背景图片
background_image = pygame.image.load("background.png")
# 加载玩家飞机图片
player_image = pygame.image.load("player.png")
player_width = player_image.get_width()
player_height = player_image.get_height()
# 加载敌机图片
enemy_image = pygame.image.load("enemy.png")
enemy_width = enemy_image.get_width()
enemy_height = enemy_image.get_height()
# 设置玩家飞机的初始位置
player_x = 400
player_y = 500
# 设置敌机的初始位置和速度
enemy_x = random.randint(0, width - enemy_width)
enemy_y = -enemy_height
enemy_speed = 5
# 设置玩家飞机的移动速度
player_speed = 10
# 设置分数
score = 0
# 设置字体
font = pygame.font.SysFont(None, 30)
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= player_speed
elif event.key == pygame.K_RIGHT:
player_x += player_speed
elif event.key == pygame.K_SPACE:
# 发射子弹
pass
# 移动敌机
enemy_y += enemy_speed
# 如果敌机飞出了屏幕,重新生成
if enemy_y > height:
enemy_x = random.randint(0, width - enemy_width)
enemy_y = -enemy_height
score += 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:
pygame.quit()
sys.exit()
# 绘制屏幕
screen.blit(background_image, (0, 0))
screen.blit(player_image, (player_x, player_y))
screen.blit(enemy_image, (enemy_x, enemy_y))
score_text = font.render("Score: " + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
pygame.display.update()
```
这份代码只是一个简单的示例,您可以根据自己的需要进行修改和扩展。
阅读全文