使用python编写一个飞机小游戏
时间: 2023-09-09 09:08:39 浏览: 106
好的,我可以为您提供一个简单的飞机小游戏的代码,您可以在Python中运行它。以下是代码:
```
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏屏幕大小
screen_width = 480
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("飞机大战")
# 加载背景图片
background = pygame.image.load("images/background.png")
# 加载飞机图片
plane_img = pygame.image.load("images/plane.png")
plane_rect = plane_img.get_rect()
plane_width = plane_rect.width
plane_height = plane_rect.height
plane_x = (screen_width - plane_width) // 2
plane_y = screen_height - plane_height - 50
# 加载敌机图片
enemy_img = pygame.image.load("images/enemy.png")
# 加载音效
bullet_sound = pygame.mixer.Sound("sounds/bullet.wav")
bullet_sound.set_volume(0.3)
bomb_sound = pygame.mixer.Sound("sounds/bomb.wav")
bomb_sound.set_volume(0.3)
# 设置字体
font = pygame.font.Font(None, 36)
# 设置游戏变量
score = 0
enemy_list = []
bullet_list = []
frame_count = 0
# 游戏循环
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_SPACE:
bullet_sound.play()
bullet_rect = pygame.Rect(plane_x + plane_width // 2 - 2, plane_y - 20, 4, 20)
bullet_list.append(bullet_rect)
# 绘制背景
screen.blit(background, (0, 0))
# 绘制飞机
screen.blit(plane_img, (plane_x, plane_y))
# 绘制子弹
for bullet_rect in bullet_list:
bullet_rect.y -= 10
pygame.draw.rect(screen, (255, 0, 0), bullet_rect)
if bullet_rect.y < -20:
bullet_list.remove(bullet_rect)
# 绘制敌机
if frame_count % 30 == 0:
enemy_rect = pygame.Rect(random.randint(0, screen_width - 50), -50, 50, 50)
enemy_list.append(enemy_rect)
for enemy_rect in enemy_list:
enemy_rect.y += 5
screen.blit(enemy_img, enemy_rect)
if enemy_rect.colliderect(plane_rect):
running = False
bomb_sound.play()
for bullet_rect in bullet_list:
if bullet_rect.colliderect(enemy_rect):
bullet_list.remove(bullet_rect)
enemy_list.remove(enemy_rect)
score += 1
bomb_sound.play()
# 绘制分数
score_text = font.render("得分:" + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新游戏帧率
pygame.display.update()
frame_count += 1
# 结束Pygame
pygame.quit()
```
在代码中,我们使用Pygame库创建了一个简单的游戏窗口,加载了背景图片、飞机图片和敌机图片,还设置了音效和字体。游戏循环中,我们处理了游戏事件,绘制了游戏中的各个元素,更新了游戏帧率,实现了一个简单的飞机小游戏。
您可以根据自己的需要对代码进行修改和扩展,例如增加多种敌机类型、不同的子弹类型、关卡难度等。希望这个小游戏对您有所帮助!
阅读全文
相关推荐















