1.游戏基础部分
1.1导入 python 包 pygame
import pygame
1.2创建游戏窗口
pygame.init()
screan = pygame.display.set_mode((480, 500)
1.3 设置切换索引量和创建时钟
shitindex = 0
clock = pygame.time.Clock()
1.4 加载游戏背景
1.4.1游戏背景
bg_img = pygame.image.load("img/background.png")
screan.blit(bg_img, (0, 0))
1.4.2游戏刷新频率
while True:
clock.tick(60)
1.4.3设置窗口姓名
pygame.display.set_caption("飞机大战")
1.4.4设置窗口图标
icon = pygame.image.load("img/icon.png")
pygame.display.set_icon(icon)
2.英雄机的部分
2.1设置英雄机位置
hero_rect = pygame.rect.Rect(189, 374, 102, 126)
2.1.1设置英雄机坐标
hero_PlaneX = hero_rect.x
hero_PlaneY = hero_rect.y
2.2对英雄机的绘制
2.2.1导入英雄机图片
hero_img1 = pygame.image.load("img/me1.png")
hero_img2 = pygame.image.load("img/me2.png")
if shitindex == 0:
screan.blit(hero_img1, (hero_PlaneX, hero_PlaneY))
shitindex += 1
else:
screan.blit(hero_img2, (hero_PlaneX, hero_PlaneY))
shitindex = 0
2.3设置英雄机能从底部飞出
hero_PlaneY -= 1
if hero_PlaneY < 0:
hero_PlaneY = 650
2.4对飞机事件进行监听
event_list = pygame.event.get()
for event in event_list:
2.4.1设置游戏退出
if event.type == pygame.QUIT:
print("游戏结束了......")
pygame.quit()
exit(0)
2.5对飞机左右移动进行监听
if event.type == pygame.KEYDOWN:
2.5.1设置飞机左移动
if event.key == pygame.K_LEFT:
hero_PlaneX = hero_PlaneX - 5 if hero_PlaneX >= 5 else 0
2.5.2设置飞机右移动
elif event.key == pygame.K_RIGHT:
hero_PlaneX = hero_PlaneX + 5 if hero_PlaneX <= 375 else 380
2.5.3设置飞机上移动
elif event.key == pygame.K_UP:
hero_PlaneY = hero_PlaneY - 5 if hero_PlaneY >= 5 else 0
2.5.4设置飞机下移动
elif event.key == pygame.K_DOWN:
hero_PlaneY = hero_PlaneY + 5 if hero_PlaneY <= 521 else 526