python小游戏飞机大战
时间: 2023-08-27 09:06:30 浏览: 89
好的,下面是一个简单的Python飞机大战游戏的代码示例:
```python
import pygame
import random
# 定义常量
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800
FRAME_RATE = 60
BULLET_SPEED = 10
ENEMY_SPEED = 5
# 初始化Pygame
pygame.init()
# 初始化游戏窗口
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")
bullet_image = pygame.image.load("bullet.png")
enemy_image = pygame.image.load("enemy.png")
# 定义游戏对象类
class GameObject:
def __init__(self, x, y, image):
self.x = x
self.y = y
self.image = image
def draw(self, screen):
screen.blit(self.image, (self.x, self.y))
# 定义玩家类
class Player(GameObject):
def __init__(self):
super().__init__(SCREEN_WIDTH // 2 - 25, SCREEN_HEIGHT - 100, player_image)
self.bullets = []
def move_left(self):
self.x -= 5
if self.x < 0:
self.x = 0
def move_right(self):
self.x += 5
if self.x > SCREEN_WIDTH - 50:
self.x = SCREEN_WIDTH - 50
def shoot(self):
bullet = GameObject(self.x + 22, self.y - 30, bullet_image)
self.bullets.append(bullet)
def update(self):
for bullet in self.bullets:
bullet.y -= BULLET_SPEED
if bullet.y < 0:
self.bullets.remove(bullet)
def draw(self, screen):
super().draw(screen)
for bullet in self.bullets:
bullet.draw(screen)
# 定义敌人类
class Enemy(GameObject):
def __init__(self):
x = random.randint(0, SCREEN_WIDTH - 50)
super().__init__(x, -50, enemy_image)
def update(self):
self.y += ENEMY_SPEED
# 初始化游戏对象
player = Player()
enemies = []
# 定义游戏循环
clock = pygame.time.Clock()
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()
elif event.key == pygame.K_SPACE:
player.shoot()
# 更新游戏对象
player.update()
for enemy in enemies:
enemy.update()
# 添加敌人
if random.randint(0, 60) == 0:
enemy = Enemy()
enemies.append(enemy)
# 检测碰撞
for enemy in enemies:
if (enemy.x >= player.x and enemy.x <= player.x + 50 and
enemy.y >= player.y and enemy.y <= player.y + 64):
running = False
for bullet in player.bullets:
if (bullet.x >= enemy.x and bullet.x <= enemy.x + 50 and
bullet.y >= enemy.y and bullet.y <= enemy.y + 30):
player.bullets.remove(bullet)
enemies.remove(enemy)
# 绘制游戏界面
screen.blit(background_image, (0, 0))
player.draw(screen)
for enemy in enemies:
enemy.draw(screen)
pygame.display.update()
# 控制游戏帧率
clock.tick(FRAME_RATE)
# 退出游戏
pygame.quit()
```
在这个例子中,我们使用了Pygame库来创建游戏界面和处理游戏事件。我们定义了`GameObject`类来表示游戏对象,包括玩家、子弹和敌人。`Player`类继承自`GameObject`类,并添加了移动和射击的方法。`Enemy`类也继承自`GameObject`类,但是它只能向下移动。在游戏循环中,我们处理玩家的移动和射击操作,更新游戏对象的状态,检测碰撞并绘制游戏界面。当玩家与敌人相撞时,游戏结束。
这只是一个简单的示例,你可以根据自己的需求来设计更复杂的游戏逻辑和界面。
阅读全文