写一段飞机小游戏的代码
时间: 2023-07-10 21:40:37 浏览: 141
飞机大战程序代码.rar
下面是一个使用Python和Pygame库编写的简单飞机小游戏的代码,玩家控制飞机躲避障碍物并尽可能地获得高分:
```python
import pygame
import random
# 定义游戏区域大小
WIDTH = 480
HEIGHT = 600
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 初始化pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("飞机小游戏")
# 加载图片资源
background_img = pygame.image.load("background.png").convert()
player_img = pygame.image.load("player.png").convert_alpha()
enemy_img = pygame.image.load("enemy.png").convert_alpha()
# 定义游戏对象类
class GameObject:
def __init__(self, x, y, img):
self.x = x
self.y = y
self.img = img
self.width = img.get_width()
self.height = img.get_height()
def draw(self):
screen.blit(self.img, (self.x, self.y))
# 定义玩家类
class Player(GameObject):
def move(self, dx, dy):
self.x += dx
self.y += dy
if self.x < 0:
self.x = 0
elif self.x > WIDTH - self.width:
self.x = WIDTH - self.width
if self.y < 0:
self.y = 0
elif self.y > HEIGHT - self.height:
self.y = HEIGHT - self.height
# 定义敌人类
class Enemy(GameObject):
def move(self):
self.y += 5
if self.y > HEIGHT:
self.reset()
def reset(self):
self.x = random.randint(0, WIDTH - self.width)
self.y = random.randint(-HEIGHT, -self.height)
# 创建游戏对象
background = GameObject(0, 0, background_img)
player = Player(WIDTH//2, HEIGHT-100, player_img)
enemies = []
for i in range(5):
enemy = Enemy(random.randint(0, WIDTH-enemy_img.get_width()), random.randint(-HEIGHT, 0), enemy_img)
enemies.append(enemy)
# 定义游戏循环
running = True
score = 0
font = pygame.font.SysFont("Arial", 32)
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(-5, 0)
elif event.key == pygame.K_RIGHT:
player.move(5, 0)
elif event.key == pygame.K_UP:
player.move(0, -5)
elif event.key == pygame.K_DOWN:
player.move(0, 5)
# 更新游戏对象
for enemy in enemies:
enemy.move()
if enemy.y + enemy.height > player.y and enemy.y < player.y + player.height and enemy.x + enemy.width > player.x and enemy.x < player.x + player.width:
running = False
if enemy.y > HEIGHT:
score += 1
enemy.reset()
score_text = font.render("Score: %d" % score, True, BLACK)
# 绘制游戏场景
background.draw()
player.draw()
for enemy in enemies:
enemy.draw()
screen.blit(score_text, (10, 10))
# 刷新屏幕
pygame.display.flip()
# 游戏结束
gameover_text = font.render("Game Over", True, BLACK)
screen.blit(gameover_text, (WIDTH//2-80, HEIGHT//2-16))
pygame.display.flip()
pygame.time.delay(2000)
# 退出游戏
pygame.quit()
```
在运行游戏之前,需要准备好游戏所需的图片资源,例如背景图、玩家图、敌人图等。将这些图片保存在与游戏代码相同的目录下,并按照代码中的文件名进行命名即可。运行代码后,即可在Pygame窗口中玩这个小游戏。
阅读全文