给我一个用python写的飞机大战的代码
时间: 2024-05-17 22:11:42 浏览: 83
python飞机大战代码
好的,以下是一个使用Python和Pygame模块编写的简单的飞机大战游戏代码示例:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((480, 700))
# 设置窗口标题
pygame.display.set_caption("飞机大战")
# 加载游戏背景
bg = pygame.image.load("images/background.png")
# 加载玩家飞机
player_img = pygame.image.load("images/me1.png")
player_rect = player_img.get_rect()
player_rect.centerx = 240
player_rect.bottom = 680
# 加载敌机
enemy_imgs = []
enemy_imgs.append(pygame.image.load("images/e1.png"))
enemy_imgs.append(pygame.image.load("images/e2.png"))
enemy_imgs.append(pygame.image.load("images/e3.png"))
enemies = []
# 加载子弹
bullet_img = pygame.image.load("images/bullet1.png")
bullets = []
# 设置游戏时钟
clock = pygame.time.Clock()
# 设置游戏状态
game_over = False
score = 0
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
# 发射子弹
bullet_rect = bullet_img.get_rect()
bullet_rect.centerx = player_rect.centerx
bullet_rect.bottom = player_rect.top
bullets.append(bullet_rect)
# 移动玩家飞机
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_rect.centerx -= 5
elif keys[pygame.K_RIGHT]:
player_rect.centerx += 5
elif keys[pygame.K_UP]:
player_rect.bottom -= 5
elif keys[pygame.K_DOWN]:
player_rect.bottom += 5
# 移动敌机
if random.randint(0, 50) == 0:
enemy_rect = enemy_imgs[random.randint(0, 2)].get_rect()
enemy_rect.centerx = random.randint(0, 480)
enemy_rect.top = 0
enemies.append(enemy_rect)
for enemy_rect in enemies:
enemy_rect.top += 3
# 移动子弹
for bullet_rect in bullets:
bullet_rect.top -= 5
# 检测碰撞
for enemy_rect in enemies:
if enemy_rect.colliderect(player_rect):
game_over = True
for bullet_rect in bullets:
if bullet_rect.colliderect(enemy_rect):
score += 10
bullets.remove(bullet_rect)
enemies.remove(enemy_rect)
# 绘制游戏场景
screen.blit(bg, (0, 0))
screen.blit(player_img, player_rect)
for enemy_rect in enemies:
screen.blit(enemy_imgs[random.randint(0, 2)], enemy_rect)
for bullet_rect in bullets:
screen.blit(bullet_img, bullet_rect)
# 绘制分数
font = pygame.font.Font(None, 36)
score_text = font.render("Score: " + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(60)
# 结束游戏
pygame.quit()
```
请注意,这只是一个简单的示例,缺少某些功能(如声音和更复杂的敌人AI),但它应该可以帮助您了解如何使用Python和Pygame模块来编写2D游戏。
阅读全文