此文章是关于飞机大战的创建窗口,和英雄机的各种功能!!
1. 下载pygame模块
在Anaconda Prompt (Anaconda3) 中输入“pip install pygame”下载模块
使用pygame:
import pygame
pygame.init()
print("游戏代码!!!")
pygame.quit()
2. 创建游戏
2.1 设置窗口大小
# 窗口大小
screen = pygame.display.set_mode((480, 650))
# 元组中480表示宽度, 650表示高度
2.2修改游戏的名称和图标,使其变成飞机大战
# 修改游戏名称
pygame.display.set_caption("飞机大战")
# 修改游戏图标
icon = pygame.image.load("img/icon.png")
pygame.display.set_icon(icon)
2.3设置游戏背景
# 加载游戏背景
bg_img = pygame.image.load("img/background.png")
3. about英雄飞机
3.1绘制英雄机
3.1.1加载英雄机图片
实现飞机的动态效果,必须是两张图片,使用if...else 语句实现其动态效果。
# 加载英雄机
hero_plane1 = pygame.image.load("img/me1.png")
hero_plane2 = pygame.image.load("img/me2.png")
3.1.2定义英雄机的位置
# 定义英雄机的位置
hero_rect = pygame.rect.Rect(190, 525, 100, 124)
3.1.3定义英雄机的x、y轴
# 定义英雄机的xy轴
hero_PlaneX = hero_rect.x
hero_PlaneY = hero_rect.y
3.1.4 绘制英雄机的图片
在while True循环中进行英雄机的绘制
if hero_imgindex == 0:
# 绘制英雄机
screen.blit(hero_plane1, (hero_PlaneX, hero_PlaneY))
hero_imgindex += 1
else:
screen.blit(hero_plane2, (hero_PlaneX, hero_PlaneY))
hero_imgindex = 0
3.2 更改英雄飞机的坐标位置
为了使以英雄飞机可以上下自由移动(在循环中写入)
# 修改英雄机的值,实现自动飞行
hero_rect.y -= 1
# 让飞机从底部飞出
if hero_rect.bottom <= 0:
hero_rect.y = 650
3.3 事件监听
事件监听主要是键盘事件和鼠标事件,之前游戏不能正常关闭,是因为没有事件监听。
3.3.1 获取所有的事件
# 获取所有事件
event_list = pygame.event.get()
# print(event_list)
3.3.2 实现游戏退出
# 捕获窗口退出事件
for event in event_list:
if event.type == pygame.QUIT: # 加上QUIT就可以正常退出
print("游戏结束!!")
pygame.quit()
# 参数为1是非正常退出,0 是正常退出,终止python程序
exit(0)
3.4 控制英雄机移动
3.4.1 控制英雄机移动
# 控制英雄界面移动
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
hero_PlaneX = hero_PlaneX-5 if hero_PlaneX >= 5 else 0
elif event.key == pygame.K_RIGHT:
hero_PlaneX = hero_PlaneX+5 if hero_PlaneX <= 375 else 380
elif event.key == pygame.K_UP:
hero_PlaneY = hero_PlaneY-5 if hero_PlaneY >= 5 else 0
elif event.key == pygame.K_DOWN:
hero_PlaneY = hero_PlaneY+5 if hero_PlaneY <= 521 else 526
3.4.2 设置灵敏度
通过调用pygame.key.set_repeat(20, 30)函数,20和30的单位都是毫秒。可以使得在玩家按住某个键不放时,系统会在20毫秒后开始重复输入这个键,并且每隔30毫秒重复一次输入。这样可以提高键盘输入的灵敏度
# 设置灵敏度
pygame.key.set_repeat(20, 30)
3.5 绘制英雄子弹
3.5.1 绘制英雄子弹
# 定义英雄机子弹
# 子弹类
class HeroBullet:
def __init__(self, x, y, screen):
self.x = x
self.y = y
self.screen = screen
self.pic = pygame.image.load("img/bullet1.png")
# 画子弹
def draw(self):
self.screen.blit(self.pic, (self.x, self.y))
self.move()
# 子弹移动方法
def move(self):
self.y -= 5
# 英雄机子弹列表
hero_Bulletlist = []
3.5.2 画出英雄机子弹
for bullet in hero_Bulletlist:
bullet.draw()
# 让子弹到最上边的时候消失
3.5.3 定义英雄子弹rect
# 定义英雄子弹rect
hero_bullet_rect = pygame.rect.Rect(bullet.x, bullet.y, 5, 11)
3.6 绘制英雄机爆炸
3.6.1 绘制英雄机爆炸图片
# 加载英雄机爆炸图片
hero_boom_imgs = ["img/me_destroy_1.png",
"img/me_destroy_2.png",
"img/me_destroy_3.png",
"img/me_destroy_4.png"]
3.6.2 英雄机爆炸条件
# 英雄机爆炸条件
hero_is_boom = False
3.6.3 英雄机爆炸图片索引
# 英雄机爆炸图片索引
hero_boom_index = 0
3.6.4 加载并绘制英雄机爆炸图片
# 加载英雄机爆炸图片
hero_boom_img = pygame.image.load(hero_boom_imgs[hero_boom_index])
# 绘制英雄机爆炸图片
screen.blit(hero_boom_img, (hero_PlaneX, hero_PlaneY))
hero_boom_index = hero_boom_index + 1
time.sleep(1)