帮我写一个飞机大战的python代码
时间: 2023-05-17 11:05:18 浏览: 112
飞机大战Python代码
好的,以下是一个简单的飞机大战的 Python 代码:
```python
import pygame
import random
# 初始化 Pygame
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_img = pygame.image.load("images/player.png")
player_rect = player_img.get_rect()
player_rect.centerx = screen_width // 2
player_rect.bottom = screen_height - 10
# 加载敌机图片
enemy_img = pygame.image.load("images/enemy.png")
# 设置字体
font = pygame.font.SysFont(None, 48)
# 设置游戏时钟
clock = pygame.time.Clock()
# 设置游戏分数
score = 0
# 定义敌机类
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = enemy_img
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, screen_width - self.rect.width)
self.rect.y = random.randint(-100, -self.rect.height)
self.speed = random.randint(1, 3)
def update(self):
self.rect.y += self.speed
if self.rect.top > screen_height:
self.kill()
# 创建敌机组
enemy_group = pygame.sprite.Group()
# 创建玩家飞机精灵
player = pygame.sprite.Sprite()
player.image = player_img
player.rect = player_rect
# 创建所有精灵组
all_sprites_group = pygame.sprite.Group()
all_sprites_group.add(player)
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 绘制背景
screen.blit(background, (0, 0))
# 更新玩家飞机位置
player.rect.centerx = pygame.mouse.get_pos()[0]
if player.rect.left < 0:
player.rect.left = 0
elif player.rect.right > screen_width:
player.rect.right = screen_width
# 创建敌机
if random.randint(1, 60) == 1:
enemy = Enemy()
enemy_group.add(enemy)
all_sprites_group.add(enemy)
# 更新敌机位置
enemy_group.update()
# 绘制所有精灵
all_sprites_group.draw(screen)
# 检测玩家飞机和敌机的碰撞
if pygame.sprite.spritecollide(player, enemy_group, True):
running = False
# 绘制分数
score_text = font.render("Score: " + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.update()
# 设置游戏帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
希望这个代码能够帮到你!
阅读全文