使用Python写一个飞机大战小游戏
时间: 2024-03-06 19:20:59 浏览: 186
好的,以下是一个简单的飞机大战小游戏的Python代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小和标题
screen_width = 480
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("飞机大战")
# 加载游戏背景图和飞机图
background_image = pygame.image.load("background.png")
player_image = pygame.image.load("player.png")
enemy_image = pygame.image.load("enemy.png")
# 设置游戏字体和分数
font = pygame.font.SysFont("simhei", 20)
score = 0
# 定义敌机类
class Enemy:
def __init__(self):
self.x = random.randint(0, screen_width - enemy_image.get_width())
self.y = -enemy_image.get_height()
self.speed = random.randint(1, 3)
def move(self):
self.y += self.speed
def draw(self):
screen.blit(enemy_image, (self.x, self.y))
# 定义玩家类
class Player:
def __init__(self):
self.x = (screen_width - player_image.get_width()) / 2
self.y = screen_height - player_image.get_height()
self.speed = 5
def move(self, direction):
if direction == "left":
self.x -= self.speed
elif direction == "right":
self.x += self.speed
if self.x < 0:
self.x = 0
elif self.x > screen_width - player_image.get_width():
self.x = screen_width - player_image.get_width()
def draw(self):
screen.blit(player_image, (self.x, self.y))
# 创建玩家和敌机对象
player = Player()
enemies = []
# 游戏循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.move("left")
elif event.key == pygame.K_RIGHT:
player.move("right")
# 绘制游戏背景和分数
screen.blit(background_image, (0, 0))
score_text = font.render("分数:" + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 绘制玩家和敌机
player.draw()
for enemy in enemies:
enemy.move()
enemy.draw()
# 判断敌机是否与玩家碰撞
if enemy.y + enemy_image.get_height() > player.y and \
enemy.y < player.y + player_image.get_height() and \
enemy.x + enemy_image.get_width() > player.x and \
enemy.x < player.x + player_image.get_width():
running = False
# 判断敌机是否超出屏幕
if enemy.y > screen_height:
score += 10
enemies.remove(enemy)
# 随机生成敌机
if random.randint(1, 50) == 1:
enemies.append(Enemy())
# 刷新屏幕
pygame.display.update()
# 结束游戏并退出pygame
pygame.quit()
```
你需要准备三张图片(分别为游戏背景、玩家飞机和敌机),并将它们命名为 `background.png`、`player.png` 和 `enemy.png`,放在同一目录下。这个游戏实现了玩家控制飞机移动、敌机随机生成、敌机移动和超出屏幕时消失、敌机与玩家碰撞时游戏结束、分数统计等功能。你可以根据自己的需求进行修改和扩展。
阅读全文