python 飞机大战游戏
时间: 2023-09-21 16:04:42 浏览: 80
使用python实现飞机大战游戏
5星 · 资源好评率100%
好的,以下是一个简单的 Python 飞机大战游戏示例代码:
```python
import pygame
import sys
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小和标题
screen_width = 480
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('飞机大战')
# 加载背景图片
bg_img = pygame.image.load('images/background.png').convert()
# 加载飞机图片和位置
player_img = pygame.image.load('images/player.png').convert_alpha()
player_rect = player_img.get_rect()
player_rect.left = (screen_width - player_rect.width) // 2
player_rect.top = screen_height - player_rect.height - 50
# 加载敌机图片和位置
enemy_img = pygame.image.load('images/enemy.png').convert_alpha()
enemy_rect = enemy_img.get_rect()
enemy_rect.left = random.randint(0, screen_width - enemy_rect.width)
enemy_rect.top = -enemy_rect.height
enemy_speed = 1
# 加载子弹图片和位置
bullet_img = pygame.image.load('images/bullet.png').convert_alpha()
bullet_rect = bullet_img.get_rect()
bullet_speed = 5
bullet_list = []
# 加载字体
font = pygame.font.Font(None, 36)
# 设置计分和生命值
score = 0
life = 3
# 游戏主循环
while True:
# 处理游戏退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 处理键盘事件
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_LEFT]:
player_rect.left -= 5
elif key_pressed[pygame.K_RIGHT]:
player_rect.left += 5
elif key_pressed[pygame.K_SPACE]:
bullet_list.append([player_rect.left + player_rect.width // 2 - bullet_rect.width // 2, player_rect.top - bullet_rect.height])
# 移动敌机和子弹
enemy_rect.top += enemy_speed
for b in bullet_list:
b[1] -= bullet_speed
# 检测敌机和子弹是否碰撞
for b in bullet_list:
if enemy_rect.colliderect(pygame.Rect(b[0], b[1], bullet_rect.width, bullet_rect.height)):
bullet_list.remove(b)
enemy_rect.left = random.randint(0, screen_width - enemy_rect.width)
enemy_rect.top = -enemy_rect.height
enemy_speed += 0.1
score += 10
# 检测敌机是否碰撞到玩家
if enemy_rect.colliderect(player_rect):
life -= 1
enemy_rect.left = random.randint(0, screen_width - enemy_rect.width)
enemy_rect.top = -enemy_rect.height
enemy_speed = 1
# 绘制背景、玩家、敌机、子弹、分数和生命值
screen.blit(bg_img, (0, 0))
screen.blit(player_img, player_rect)
screen.blit(enemy_img, enemy_rect)
for b in bullet_list:
screen.blit(bullet_img, (b[0], b[1]))
score_text = font.render('Score: ' + str(score), True, (255, 255, 255))
life_text = font.render('Life: ' + str(life), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
screen.blit(life_text, (screen_width - life_text.get_width() - 10, 10))
# 更新屏幕
pygame.display.update()
# 检测生命值是否为0,如果是则结束游戏
if life == 0:
gameover_text = font.render('Game Over', True, (255, 0, 0))
screen.blit(gameover_text, ((screen_width - gameover_text.get_width()) // 2, (screen_height - gameover_text.get_height()) // 2))
pygame.display.update()
pygame.time.delay(3000)
pygame.quit()
sys.exit()
```
在运行之前,需要先准备好游戏所需的图片资源,并将其放在与代码同级的 images 文件夹中。此外,还需要安装 Pygame 库。
阅读全文