**ex40- 44都是类的知识 **
我们讲讲用python编程,特别是面向对象编程的一些基本步骤:
- 把要解决的事情写下或画出来
- 把解决事情的关键或步骤列举出来
- 为这些关键点创建关系图
- 创建类和测试用的例子来运行类
- 重复并完善代码
可以看出,这个步骤是自上而下的。下面通过实例教学,有兴趣的可以跟着书本一步步完成一个游戏
The Analysis of a Simple Game Engine
我想做一个游戏,叫““Gothons from Planet Percal #25”,一款小型太空探险游戏
1、 把要解决的事情写下或画出来
这个游戏是这样子的:“外星人入侵了一艘宇宙飞船,我们的英雄必须穿过一个迷宫般的房间打败他们,这样他才能进入一个逃生舱逃到下面的星球。游戏有点像密室逃脱,通过文本与玩家互动,有各种各样的死亡方式。进入一个房间会有房间的描述,并根据互动进入下一个房间”
接下来,我要描述各种场景:
Death —— 玩家死亡
Central Corridor —— 这是起始点 ,有一个gothon 站在那里,玩家需要说一个笑话打败它游戏才能继续运行
Laser Weapon Armory —— 一个武器库,玩家在这里可以拿到终极武器,中子弹,在逃后前炸毁飞船。但有密码需要破译
The Bridge —— 这是玩家放炸弹时与gothon战斗的场景
Escape Pod —— 逃生舱,只有玩家进入正确的逃生舱时
2、 把解决事情的关键或步骤列举出来
现在我有足够的信息可以创建实例和他们的类,首先创建列表:
- Alien
- player
- ship
- maze
- room
- scene
- gothon
- escape pod
- planet
- map
- engine
- death
- central corridor
- laser weapon armory
- the bridge
3、为这些关键点创建关系图
4、创建类和测试用的例子来运行类
class Scene(object):
def enter(self):
pass
class Engine(object):
def __init__(self,scene_map):
pass
def play(self):
pass
class Death(Scene):
def enter(self):
pass
class CentralCorridor(Scene):
def enter(self):
pass
class LaserWeaponArmory(Scene):
def enter(self):
pass
class TheBridge(Scene):
def enter(self):
pass
class EscapePod(Scene):
def enter(self):
pass
class Map(object):
def __init__(self,start_scene):
pass
def next_scene(self,scene_name):
pass
def opening_scene(self):
pass
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
5、 重复和完善代码
回顾整个代码,确保代码照顾了方方面面,有需要就回到第2步,第3步,再想解决方案,不停地重复,不停的完善。
这个编码过程,是典型的自上而下的。先构思整体,再慢慢完善局部。当然也可以自下而上,把局部都弄好了,再组合成整体。这需要良好的基础。
接下来作者上代码了,我就不抄了