用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.font.init()
screen = pygame.display.set_mode((400,250))
myfont = pygame.font.SysFont("arial",30) helloworld = myfont.render('HelloWorld!', True, (255,255,255))
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: sys.exit() screen.blit(helloworld, (0,0)) pygame.display.update() pygame.quit()
|
运行效果:
程序运行过程分析
从上述代码中可以看出,pygame程序执行的顺序大致为:
各种初始化init
→定义主窗口screen
→定义各项surface
→游戏主循环,不断获取键鼠输入事件(event)
→根据事件处理数据,并填充(blit)屏幕数据
→刷新屏幕(update)
这里一些看不懂的地方先不急着弄清楚,后面会讲。
用pyinstaller打包exe可执行文件
看这里