写一个飞机大战的游戏代码
时间: 2023-12-01 15:34:20 浏览: 75
好的,我可以尝试为您提供一个基于 Python 语言的飞机大战游戏代码,以下是代码实现:
```python
import pygame
import random
# 设置屏幕宽高
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800
# 创建游戏窗口
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("飞机大战")
# 加载游戏图片
background_img = pygame.image.load("images/background.png").convert()
player_img = pygame.image.load("images/player.png").convert_alpha()
bullet_img = pygame.image.load("images/bullet.png").convert_alpha()
enemy_img = pygame.image.load("images/enemy.png").convert_alpha()
# 创建玩家飞机类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = player_img
self.rect = self.image.get_rect()
self.rect.centerx = SCREEN_WIDTH // 2
self.rect.bottom = SCREEN_HEIGHT - 10
self.speed = 5
def update(self):
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT] and self.rect.left > 0:
self.rect.x -= self.speed
elif keys_pressed[pygame.K_RIGHT] and self.rect.right < SCREEN_WIDTH:
self.rect.x += self.speed
if keys_pressed[pygame.K_UP] and self.rect.top > 0:
self.rect.y -= self.speed
elif keys_pressed[pygame.K_DOWN] and self.rect.bottom < SCREEN_HEIGHT:
self.rect.y += self.speed
def fire(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
# 创建子弹类
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = bullet_img
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.speed = -10
def update(self):
self.rect.y += self.speed
if self.rect.bottom < 0:
self.kill()
# 创建敌机类
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, -40)
self.speed = random.randint(1, 4)
def update(self):
self.rect.y += self.speed
if self.rect.top > SCREEN_HEIGHT:
self.kill()
# 创建精灵组
all_sprites = pygame.sprite.Group()
player = Player()
bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group()
all_sprites.add(player)
# 设置游戏循环
running = True
clock = pygame.time.Clock()
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.fire()
# 添加敌机
if random.randint(0, 100) < 2:
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# 检测子弹是否击中敌机
hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
# 更新精灵组
all_sprites.update()
# 绘制游戏背景
screen.blit(background_img, (0, 0))
# 绘制所有精灵
all_sprites.draw(screen)
# 更新屏幕显示
pygame.display.flip()
pygame.quit()
```
您可以将代码保存为 `plane.py` 文件,然后在终端中运行 `python plane.py` 命令启动游戏。祝您游戏愉快!
阅读全文