写一个Python开发的小游戏(飞机大战)
时间: 2024-02-03 22:03:28 浏览: 66
好的,下面是一个简单的Python开发的飞机大战小游戏代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
WIDTH, HEIGHT = 480, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置游戏标题
pygame.display.set_caption("飞机大战")
# 加载游戏图片
background_img = pygame.image.load("background.png")
player_img = pygame.image.load("player.png")
enemy_img = pygame.image.load("enemy.png")
bullet_img = pygame.image.load("bullet.png")
# 设置游戏音效
bullet_sound = pygame.mixer.Sound("bullet.wav")
enemy_sound = pygame.mixer.Sound("enemy.wav")
gameover_sound = pygame.mixer.Sound("gameover.wav")
# 设置游戏字体
font = pygame.font.SysFont("Arial", 32)
# 定义游戏对象
class GameObject:
def __init__(self, x, y, img):
self.image = img
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def draw(self, surface):
surface.blit(self.image, self.rect)
# 定义玩家飞机对象
class Player(GameObject):
def __init__(self, x, y, img):
super().__init__(x, y, img)
self.speed = 5
self.bullets = []
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT]:
self.rect.x += self.speed
if keys[pygame.K_SPACE]:
self.fire()
def fire(self):
bullet = Bullet(self.rect.x + 35, self.rect.y)
self.bullets.append(bullet)
bullet_sound.play()
# 定义敌机对象
class Enemy(GameObject):
def __init__(self, x, y, img):
super().__init__(x, y, img)
self.speed = 3
def update(self):
self.rect.y += self.speed
# 定义子弹对象
class Bullet(GameObject):
def __init__(self, x, y):
super().__init__(x, y, bullet_img)
self.speed = 10
def update(self):
self.rect.y -= self.speed
# 定义游戏主函数
def main():
# 创建玩家飞机对象
player = Player(200, 600, player_img)
# 创建敌机列表
enemies = []
for i in range(5):
enemy = Enemy(random.randint(0, 400), -100 * i, enemy_img)
enemies.append(enemy)
# 创建子弹列表
bullets = []
# 设置游戏分数
score = 0
# 开始游戏循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新玩家飞机
player.update()
# 更新子弹
for bullet in player.bullets:
bullet.update()
if bullet.rect.y < -20:
player.bullets.remove(bullet)
# 更新敌机
for enemy in enemies:
enemy.update()
if enemy.rect.y > HEIGHT:
enemies.remove(enemy)
# 检测子弹和敌机的碰撞
for bullet in player.bullets:
for enemy in enemies:
if bullet.rect.colliderect(enemy.rect):
player.bullets.remove(bullet)
enemies.remove(enemy)
enemy_sound.play()
score += 10
# 检测玩家飞机和敌机的碰撞
for enemy in enemies:
if player.rect.colliderect(enemy.rect):
gameover_sound.play()
running = False
# 绘制游戏画面
screen.blit(background_img, (0, 0))
player.draw(screen)
for bullet in player.bullets:
bullet.draw(screen)
for enemy in enemies:
enemy.draw(screen)
score_text = font.render("Score: {}".format(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新游戏画面
pygame.display.update()
# 退出游戏
pygame.quit()
if __name__ == "__main__":
main()
```
你可以根据自己的需要对代码进行修改和扩展。
阅读全文