python飞机大作战代码
时间: 2023-08-01 20:14:31 浏览: 101
以下是基于Pygame库实现的简单飞机大战游戏代码示例:
```python
import pygame
import random
pygame.init()
# 游戏窗口大小
screen_width = 480
screen_height = 700
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
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 = screen_width // 2
player_rect.bottom = screen_height - 10
# 子弹图像
bullet = pygame.image.load("images/bullet.png")
bullet_rect = bullet.get_rect()
# 敌人图像
enemy_images = [
pygame.image.load("images/enemy1.png"),
pygame.image.load("images/enemy2.png"),
pygame.image.load("images/enemy3.png"),
]
enemy_rects = [enemy.get_rect() for enemy in enemy_images]
# 游戏时钟
clock = pygame.time.Clock()
# 创建敌人精灵组
enemies = pygame.sprite.Group()
# 创建子弹精灵组
bullets = pygame.sprite.Group()
# 得分
score = 0
# 游戏结束标志位
game_over = False
# 游戏主循环
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:
# 发射子弹
b = pygame.sprite.Sprite()
b.image = bullet
b.rect = bullet_rect.copy()
b.rect.centerx = player_rect.centerx
b.rect.bottom = player_rect.top
bullets.add(b)
# 移动玩家飞机
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_rect.left > 0:
player_rect.move_ip(-5, 0)
if keys[pygame.K_RIGHT] and player_rect.right < screen_width:
player_rect.move_ip(5, 0)
# 移动子弹
for b in bullets:
b.rect.move_ip(0, -10)
if b.rect.top < 0:
bullets.remove(b)
# 创建敌人
if random.randint(1, 60) == 1:
enemy = pygame.sprite.Sprite()
enemy.image = random.choice(enemy_images)
enemy.rect = random.choice(enemy_rects).copy()
enemy.rect.centerx = random.randint(
enemy.rect.width // 2, screen_width - enemy.rect.width // 2
)
enemy.rect.bottom = 0
enemies.add(enemy)
# 移动敌人
for e in enemies:
e.rect.move_ip(0, 5)
if e.rect.top > screen_height:
enemies.remove(e)
# 检测碰撞
for b in bullets:
for e in enemies:
if pygame.sprite.collide_rect(b, e):
bullets.remove(b)
enemies.remove(e)
score += 10
for e in enemies:
if pygame.sprite.collide_rect(player, e):
game_over = True
# 绘制图像
screen.blit(background, (0, 0))
screen.blit(player, player_rect)
bullets.draw(screen)
enemies.draw(screen)
# 显示得分
font = pygame.font.Font(None, 36)
text = font.render("得分:" + str(score), True, (255, 255, 255))
screen.blit(text, (10, 10))
# 更新屏幕
pygame.display.update()
# 控制帧率
clock.tick(60)
# 游戏结束
font = pygame.font.Font(None, 48)
text = font.render("游戏结束!", True, (255, 0, 0))
text_rect = text.get_rect()
text_rect.centerx = screen_width // 2
text_rect.centery = screen_height // 2
screen.blit(text, text_rect)
pygame.display.update()
# 等待3秒钟后退出游戏
pygame.time.wait(3000)
pygame.quit()
```
注意:以上代码仅为示例,仍有许多需要改进的地方。
阅读全文