pgzero:用 Python 进行游戏开发

开发 后端 游戏开发
今天要和大家分享的pgzero(pygame zero)是在pygame基础上做了进一步的封装,使得设计一款游戏十分的方便,特别适合少儿编程领域的教学, 与scratch相得益彰。

[[404459]]

1. pgzero

python在各个领域都有着丰富的第三方库,pygame是python在游戏领域的应用库,可以用来开发各种不同的游戏。但是对于初学者来说,还是存在一定的门槛。

而今天要和大家分享的pgzero(pygame zero)是在pygame基础上做了进一步的封装,使得设计一款游戏十分的方便,特别适合少儿编程领域的教学, 与scratch相得益彰。

  •  pgzero的安装   
  1. pip install pygame  
  2. pip install pgzero 

2. 游戏设计的过程

我们可以简单梳理下开发一款简单游戏需要的过程:

  •  游戏的故事设计
  •  游戏的场景绘制(背景图片和声音)
  •  游戏的角色
  •  如何控制角色
  •  如何判断成功与失败
  •  游戏的关卡设计

3. pgzero基础

pgzero游戏开发的过程如下:

  •  游戏屏幕区域screen pgzero中游戏界面窗口设置由全局变量和内置对象screen来完成:
    •   窗口外观:WIDTH , HEIGHT 和TITLE
    •   窗口清楚:screen.clear()
    •   窗口背景颜色:screen.fill((red, green, blue))
    •   在窗口绘制图像:screen.blit(image, (left, top))
    •   在窗口绘制几何图案:screen.draw.line screen.draw.circle screen.draw.rect
  •  游戏角色Actor pgzero中所有以图片显示的元素都是Actor类来定义。   
  1. # 'alien' 表示alien图片,默认是images/alien.png  
  2.     # (50, 50) 定义了Actor在窗口上显示的位置  
  3.     alien = Actor('alien', (50, 50)) 
  • Actor的位置:

Actor重要属性和方法:

  •  其他属性同pygame.Rect
    •   外观:image, 如alien.image = 'alien_hurt'
    •   位置: piex坐标值:x,y, 设置位置:pos,left/right/top/bottom
    •   角度:angle
    •   绘制f方法:draw()
    •   距离方法: Actor.distance_to(target)
    •   角度方法:Actor.angle_to(target)
  •  游戏渲染绘制draw
  •  游戏状态的更新update
  •  游戏外部事件的触发控制on_xxx_xxx pgzero提供了常用的鼠标和键盘事件

键盘的按键信息是通过keyboard内置对象获取的,鼠标是mouse来获取的,如: 

  1. keyboard.a  # The 'A' key  
  2.   keyboard.left  # The left arrow key  
  3.   keyboard.rshift  # The right shift key  
  4.   keyboard.kp0  # The '0' key on the keypad  
  5.   keyboard.k_0  # The main '0' key   
  6.   mouse.LEFT  
  7.   mouse.RIGHT  
  8.   mouse.MIDDLE 

详见

  •   https://pygame-zero.readthedocs.io/en/stable/hooks.html#mouse.WHEEL_DOWN
  •   键盘事件:on_key_down, on_key_up
  •   鼠标事件:on_mouse_down, on_mouse_up, on_mouse_move

其他重要元素

  •  声音 sounds:支持wav和ogg, 资源对象目录默认为./sounds
  1. # 播放声音./sounds/drum.wav  
  2.  sounds.drum.play() 
  •  音乐 music: 支持mp3, 主要是时间较长的音频文件。资源对象目录默认为./music 
  1. # 播放声音./music/drum.mp3  
  2.   music.play('drum') 
  •  动画效果Animations,如移动角色到某个位置   
  1. # animate(object, tween='linear'duration=1on_finished=None, **targets)  
  2.    animate(alien, pos=(100, 100)) 

详见:

https://pygame-zero.readthedocs.io/en/stable/builtins.html#Animations

4. pgzero游戏例子

了解了pgzero的基本使用情况,下面来举一个例子,将游戏编写制作的过程串起来。

我们来模拟手机上的一款游戏FlappyBird。游戏简单操作说明 

  1. 在《FlappyBird》这款游戏中,玩家只需要用一根手指来操控,点击触摸屏幕,小鸟就会往上飞,不断的点击就会不断的往高处飞。放松手指,则会快速下降。所以玩家要控制小鸟一直向前飞行,然后注意躲避途中高低不平的管子。 [3]  
  2. 1、在游戏开始后,点击屏幕,要记住是有间歇的点击屏幕,不要让小鸟掉下来。  
  3. 2、尽量保持平和的心情,点的时候不要下手太重,尽量注视着小鸟。  
  4. 3、游戏的得分是,小鸟安全穿过一个柱子且不撞上就是1分。当然撞上就直接挂掉,只有一条命。 

pgzero游戏代码结构: 

  1. import pgzrun  
  2. # 全局变量和初始化信息  
  3. TITLE = 'xxx'  
  4. WIDTH = 400  
  5. HEIGHT = 500  
  6. # 绘制游戏元素  
  7. def draw(): 
  8.     pass  
  9. # 更新游戏状态  
  10. def update():  
  11.     pass  
  12. # 处理键盘事件  
  13. def on_key_down():  
  14.     pass  
  15. # 处理键盘事件  
  16. def on_mouse_down():  
  17.     pass  
  18. # 执行  
  19. pgzrun.go()  
  1. import pgzrun  
  2. import random  
  3. TITLE = 'Flappy Bird'  
  4. WIDTH = 400  
  5. HEIGHT = 500  
  6. # These constants control the difficulty of the game  
  7. GAP = 130  
  8. GRAVITY = 0.3  
  9. FLAP_STRENGTH = 6.5  
  10. SPEED = 3  
  11. # bird   
  12. bird = Actor('bird1', (75, 200))  
  13. bird.dead = False  
  14. bird.score = 0  
  15. bird.vy = 0  
  16. storage = {}  
  17. storage['highscore'] = 0  
  18. def reset_pipes():  
  19.     # 设置随机的高度  
  20.     pipe_gap_y = random.randint(200, HEIGHT - 200)  
  21.     pipe_top.pos = (WIDTH, pipe_gap_y - GAP // 2)  
  22.     pipe_bottom.pos = (WIDTH, pipe_gap_y + GAP // 2)  
  23. pipe_top = Actor('top', anchor=('left', 'bottom'))  
  24. pipe_bottom = Actor('bottom', anchor=('left', 'top'))  
  25. reset_pipes()  # Set initial pipe positions.  
  26. def update_pipes():  
  27.     # 不断的移动柱子  
  28.     pipe_top.left -SPEED  
  29.     pipe_bottom.left -SPEED  
  30.     if pipe_top.right < 0:  
  31.         reset_pipes()  
  32.         if not bird.dead:  
  33.             bird.score += 1  
  34.             if bird.score > storage['highscore']:  
  35.                 storage['highscore'] = bird.score  
  36. def update_bird():  
  37.     # 小鸟下降  
  38.     uy = bird.vy  
  39.     bird.vy += GRAVITY  
  40.     bird.y += (uy + bird.vy) / 2  
  41.     bird.x = 75  
  42.     # 根据小鸟死亡切换小鸟的造型  
  43.     if not bird.dead:  
  44.         if bird.vy < -3:  
  45.             bird.image = 'bird2'  
  46.         else:  
  47.             bird.image = 'bird1'  
  48.     # 判断小鸟死亡: 是否触碰柱子  
  49.     if bird.colliderect(pipe_top) or bird.colliderect(pipe_bottom):  
  50.         bird.dead = True  
  51.         bird.image = 'birddead'  
  52.     # 小鸟超过边界 初始化  
  53.     if not 0 < bird.y < 720:  
  54.         bird.y = 200  
  55.         bird.dead = False  
  56.         bird.score = 0  
  57.         bird.vy = 0  
  58.         reset_pipes()   
  59. def update():  
  60.     update_pipes()  
  61.     update_bird()  
  62. # 按下任意键, 小鸟上升  
  63. def on_key_down():  
  64.     if not bird.dead:  
  65.         bird.vy = -FLAP_STRENGTH  
  66. #   
  67. def draw():  
  68.     # 背景图片  
  69.     screen.blit('background', (0, 0))  
  70.      # 加载小鸟/柱子  
  71.     pipe_top.draw()  
  72.     pipe_bottom.draw()  
  73.     bird.draw()  
  74.     # 显示分数和最佳  
  75.     screen.draw.text(  
  76.         str(bird.score),  
  77.         color='white'
  78.          midtop=(WIDTH // 2, 10),  
  79.         fontsize=70 
  80.         shadow=(1, 1)  
  81.     )  
  82.     screen.draw.text(  
  83.         "Best: {}".format(storage['highscore']),  
  84.         color=(200, 170, 0),  
  85.         midbottom=(WIDTH // 2, HEIGHT - 10),  
  86.         fontsize=30 
  87.         shadow=(1, 1)  
  88.     )  
  89. pgzrun.go() 

5. 总结

本文分享了基于pygame封装版的pgzero开发python游戏的过程,希望对您有帮助。总结如下:

  •  pgzero开发三剑客:draw() / update() / on_xxx_xxx()
  •  pgzero内置对象:screen负责窗口设置,Actor负责图像显示,sounds负责短音频,music负责长音频bgm,动画效果有animate
  •  pgzero资源目录:./images/xxx.png ./music/xxx.mp3  ./sounds/xxx/wav

6. 参考资料

https://pygame-zero.readthedocs.io/en/stable/ 

 

责任编辑:庞桂玉 来源: Python中文社区 (ID:python-china)
相关推荐

2021-06-07 23:57:59

Python 游戏Pgzero

2010-03-12 13:32:02

python2.6

2010-03-03 15:06:52

Android 游戏开

2019-09-23 09:11:02

Python文本编辑器操作系统

2010-02-01 14:48:43

2020-07-23 09:15:25

Python机器学习聚类分析

2010-02-03 14:15:18

Python 开发

2022-06-27 08:59:40

Python游戏代码

2021-04-09 20:49:44

PythonOCR图像

2017-02-20 09:10:05

2024-01-15 07:47:09

井字棋游戏编程练习Python

2011-11-14 09:13:06

2012-01-17 12:39:09

JavaSwing

2012-04-12 11:11:15

HTML5APIWEB

2019-11-20 12:30:21

Python编程语言语音识别

2013-05-21 11:20:37

Android游戏开发View手势识别

2022-01-27 14:12:49

Python游戏脚本

2021-12-30 10:55:54

Python游戏脚本

2009-06-11 09:19:38

netbeans实例J2ME游戏

2010-03-08 17:03:22

Python脚本
点赞
收藏

51CTO技术栈公众号