用pygame库做一个扫雷小游戏

PyGame——python的游戏引擎

项目地址在这里:Quiser714/MineSweeper: 在win10玩扫雷 (github.com),帮孩子点个⭐吧球球了

pygame的安装

直接pip3 install pygame就可以

进入python尝试import pygame

it works!

从HelloWorld开始学习pygame

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import sys
import pygame

pygame.init() #pygame初始化
pygame.font.init() #pygame.font字体模块初始化

screen = pygame.display.set_mode((400,250)) #创建一个400*250的窗口,注意函数内参数为元组,是一个参数,而非两个

myfont = pygame.font.SysFont("arial",30) #创建一类字体,为自豪为30的“arial”系统字体
helloworld = myfont.render('HelloWorld!', True, (255,255,255)) #用上述字体渲染一个Surface对象

while True:
#轮询事件
for event in pygame.event.get():
if event.type == pygame.QUIT: #点击右上角叉,退出游戏
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: # 按下ESC键,退出游戏
sys.exit()
screen.blit(helloworld, (0,0)) #在屏幕上的0,0位置填充helloworld这个surface
pygame.display.update() #刷新画面

pygame.quit()

运行效果:

程序运行过程分析

从上述代码中可以看出,pygame程序执行的顺序大致为:

各种初始化init定义主窗口screen定义各项surface游戏主循环,不断获取键鼠输入事件(event)根据事件处理数据,并填充(blit)屏幕数据刷新屏幕(update)

这里一些看不懂的地方先不急着弄清楚,后面会讲。

用pyinstaller打包exe可执行文件

看这里