[python]代码库
import pygame
import time
from pygame.locals import *
# 初始化pygame
pygame.init()
# 初始化音乐
pygame.mixer.init()
# 加载背景音乐
#pygame.mixer.music.load("bg.mp3")
# 设定背景音乐循环播放
#pygame.mixer.music.play(-1)
# 定义颜色变量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 设置屏幕大小
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置窗口标题
pygame.display.set_caption('飞机游戏')
# 载入背景图
background = pygame.image.load('bg.png').convert()
# 载入飞机图片
planeImg = pygame.image.load('plane.png').convert_alpha()
# 载入子弹图片
bulletImg = pygame.image.load('bullet.png').convert_alpha()
# 载入敌机图片
enemyImg = pygame.image.load('seaking.png').convert_alpha()
# 定义Clock对象,用于操作时间
clock = pygame.time.Clock()
# 定义玩家的初始位置
planeX = 200
planeY = 540
# 定义子弹默认位置
bulletX = 0
bulletY = -50
# 定义子弹是否“射击”的变量
bullet_fired = False
# 定义敌机初始位置
enemyX = 100
enemyY = 30
# 主循环
while True:
# 设置刷新帧率
clock.tick(60)
# 加载背景
screen.blit(background, (0, 0))
# 检测事件
for event in pygame.event.get():
# 用户点击关闭按钮
if event.type == QUIT:
exit()
# 用户按下键盘
elif event.type == KEYDOWN:
# 空格键控制 “子弹射击”
if event.key == K_SPACE:
bullet_fired = True
# 增加背景音效
# pygame.mixer.music.stop()
# pygame.mixer.music.load("bg.mp3")
# pygame.mixer.music.play(-1)
# 绘制玩家飞机
screen.blit(planeImg, (planeX, planeY))
# 控制玩家飞机移动(左右方向键控制)
pressed_keys = pygame.key.get_pressed()
if pressed_keys[K_LEFT]:
planeX -= 5
elif pressed_keys[K_RIGHT]:
planeX += 5
# 定义子弹的位置
if bullet_fired == True:
screen.blit(bulletImg, (planeX + 17, planeY - 20))
bulletY -= 5
if bulletY < -50:
bullet_fired = False
bulletY = -50
# 定义敌机的位置
screen.blit(enemyImg, (enemyX, enemyY))
enemyY += 3
if enemyY > 600:
enemyX = enemyY = 0
# Boolean 检测是否击中敌机
if (bullet_fired == True and enemyY > 0 and bulletY <= enemyY + 35 and
bulletX + 3 >= enemyX and bulletX - 3 <= enemyX + 90):
enemyY = 0
bullet_fired = False
bulletY = -50
# 更新屏幕
pygame.display.update()