效果


- 绿色的F表示右键点击插旗的地方
- 红色的格子表示点击到了地雷
原理
主时间循环
基本上GUI应用都会有一个主循环,用来接收各种事件,并按照时间类型进行不同的处理。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
while True: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: if game.is_over(): init_game(30) continue pos = event.pos if event.button == 1: game.clicked(pos) elif event.button == 3: game.right_clicked(pos) # 获取当前那个格子被点击了 if event.type == pygame.QUIT: sys.exit(0) pygame.display.update() |
主要自定义处理类
- class Game
- class Square
Game
表示一次游戏。当前游戏中所有的地雷分布;保存所有的格子信息;以及每个格子周围的地雷数量。Game点击后需要判断是否是否游戏结束。
如何获胜:
- 所有的雷都被标注
- 已经没有空白的格子可以点了
Square
表示一个格子,初始化的时候会传入是否包含地雷的信息,格子作为一圈的地雷数量。
Square本身含有一个状态机,根据点击状态和点击方式画出各种样式(空白,带数字,F,红色)等。
主循环中的事件会传给Game,最终根据位置传个某个Square。
PyGame
pygame.Screen 使用pygame.display.set_mode返回一个画布,然后可以将各种Rect,font之类的放到这画布上。
|
1
|
pygame.display.set_mode((total_width, total_height)) |
pygame.Rect 输出格子
pygame.font 输出字体
重点方法
- pygame.Screen.blit 将绘制的内容叠放到屏幕上。
|
1
2
3
4
|
self.face = pygame.Surface((self.rect.width, self.rect.height))self.face.fill('white')game.get_screen().blit(self.face, (self.rect.left, self.rect.top))pygame.draw.rect(self.surface, 'gray', self.rect, 1) |
- pygame.display.update 刷新页面
