python创建一个简单的飞机大战小游戏,其中玩家需要控制飞机发射子弹来消灭敌机,同时躲避敌机的攻击。
分析:
代码示例
python
import pygame
import random
# 初始化pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((480, 720))
# 加载背景图片
background = pygame.image.load("background.png")
# 加载敌机图片
enemy = pygame.image.load("enemy.png")
# 加载主角飞机图片
player = pygame.image.load("player.png")
# 加载子弹图片
bullet = pygame.image.load("bullet.png")
# 加载爆炸图片
explosion = pygame.image.load("explosion.png")
# 初始化变量
score = 0
player_x = 200
player_y = 550
enemy_x = random.randint(0, 450)
enemy_y = 0
bullet_x = player_x + 32
bullet_y = player_y - 20
bullet_speed = 10
explosion_flag = False
enemy_speed = 5
enemies = [[0, 0]]
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= 5
elif event.key == pygame.K_RIGHT:
player_x += 5
elif event.key == pygame.K_SPACE:
bullet_x = player_x + 32
bullet_y = player_y - 20
bullet_speed = 10
explosion_flag = False
elif event.key == pygame.K_UP:
enemy_y += enemy_speed
elif event.key == pygame.K_DOWN:
enemy_y -= enemy_speed
elif event.key == pygame.K_ESCAPE:
pygame.quit()
exit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player_x = 200
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
enemy_y = random.randint(0, 450) - 50
if event.key == pygame.K_SPACE:
bullet_speed = 0
# 绘制背景图和角色图等
screen.blit(background, (0, 0))
screen.blit(player, (player_x, player_y))
for i in range(len(enemies)):
screen.blit(enemy, (enemies[i][0], enemies[i][1]))
screen.blit(bullet, (bullet_x, bullet_y))
if explosion_flag:
screen.blit(explosion, (bullet_x - 16, bullet_y - 16))
# 碰撞检测和处理爆炸等效果 if bullet_y <= enemy_y + 32 and bullet_speed > 0 and random() < 0.3:
if bullet_y <= enemy_y + 32 and bullet_speed > 0 and random() < 0.3:
score += 1000 / len(enemies) / len(enemies[i]) * (bullet_speed + 1) / (enemy_y - bullet_y + 20) / len(enemies) / len(enemys[i]) * (bullet_speed + 1) / (enemy_y - bullet_y + 20) / len(enemies) / len(enemys[i]) * (bullet_speed + 1) / (enemy_y - bullet_y + 20) / len(enemies) / len(enemys[i]) * (bullet_speed + 1) / (enemy_y - bullet_y + 20) / len(enemies) / len(enem
运行结果