习题43 基本的面向对象分析和设计

通过面向对象编程(OOP)构建一些东西的流程(常用)(自顶向下)

  1. 把要解决的问题写下来,或者画出来。
  2. 将第一条中的关键概念提取出来并加以研究。
  3. 创建一个类层次结构和对象图。
  4. 用代码实现各个类,并写一个测试来运行它们。
  5. 重复上述步骤并细化代码。

(自底向上)

  1. 取出要解决的问题中的一小块,写些代码让它差不多能工作。
  2. 加上类和自动测试,细化代码让它更为正式。
  3. 把关键概念抽取出来然后研究它们。
  4. 把真正需要实现的东西描述出来。
  5. 回去细化代码,有可能需要全部丢弃重头做起。
  6. 在问题的另外一小块里重复上述流程。
from sys import exit
from random import randint
from textwrap import dedent# 场景
class Scene(object):def enter(self):print("该场景尚未配置。")print("将其子类化并将enter()补充完整。")exit(1)# 引擎
class Engine(object):def __init__(self, scene_map):self.scene_map = scene_map## 在play运行的开始,current-scene和last-scene是不等的,后来使current_scene变化,令其等于始终未变的last_scene,以确保游戏进行到下一个场景def play(self):print(">>>>>>>>>>>start play")current_scene = self.scene_map.opening_scene()          # 返回开始场景的键值对对应的类last_scene = self.scene_map.next_scene('finished')      # 返回Finished()类print(">>>>>>>>>>>>>>>>after play, current_scene:", current_scene, "last_scene:", last_scene)print("^^^^^^^^^^^^^^^ before while, current_scene:", current_scene, "last_scene:", last_scene)while current_scene != last_scene:                      # 若当前场景非Finished()类print("&&&&&&&&&&&&&&&&&&&&&&before n = c, c =", current_scene, "last_scene", last_scene)next_scene_name = current_scene.enter()             # 返回当前场景的enter()函数print("##################after n = c, current_scene:", current_scene, "last_scene:", last_scene, "next_scene_name:", next_scene_name)current_scene = self.scene_map.next_scene(next_scene_name)print(">>>>>>>>>>>>>>>>>> after while, current_scene:", current_scene, "last_scene:", last_scene, "next_scene_name:", next_scene_name)current_scene.enter()## 死亡
class Death(Scene):# 俏皮话quips = ["You died. You kinda suck at this.------你死了,你真的玩的烂透了","Your mom would be proud...if she were smarter.---------你妈妈可能会自豪的…,如果她更聪明一点","Such a luser.--------简直是个失败者","I have a small puppy that's better at this.-------我有一个小狗,它甚至玩的更好些","You're worse than your Dad's jokes.----------你简直比你爸的笑话还要糟糕",]def enter(self):### 为什么第一个调用quips的地方用death第二个用self??????### 应该是第一个指定用哪个类,第二个指定类内方法?# randint(a, b):用于生成一个指定范围内的整数。生成的随机数n: a <= n <= b# 输出前四句中的任意一句print(Death.quips[randint(0, len(self.quips)-1)])## 中央走廊
class CentralCorridor(Scene):def enter(self):print(dedent("""The Gothons of Planet Percal # 25 have invaded your ship and destroyed your entire crew . You are the last survivingmember and your last mission is to get the neutron destructbomb from the Weapons Armory,put it in the bridge,andblow the ship up after getting into an escape pod.You' re running down the central corridor to the Weapons Armory when a Gothon jumps out,red scaly skin , dark grimyteeth , and evil clown costume flowing around his hatefilled body.He ' s blocking the door to the Armory andabout to pull a weapon to blast you.珀卡尔25号行星的哥顿人入侵了你的飞船,摧毁了你的全体船员。你是最后一个幸存的成员,你的最后一个任务是从武器库取出中子毁灭性炸弹,放在舰桥上,进入逃生舱后炸毁飞船。你正沿着通往武器库的中央走廊奔跑,这时一个哥顿人跳了出来,皮肤发红,牙齿发黑,邪恶的小丑服装在他那带帽的身体上飘荡。他堵住了军械库的门,准备拔出武器来炸你."""))action = input(">")if action == "shoot!": print(dedent("""Quick on the draw you yank out your blaster and fire it at the Gothon .His clown costume is flowing andmoving around his body , which throws off your aim.Your laser hits his costume but misses him entirely.This completely ruins his brand new costume his mother bought him ,which makes him fly into an insane rage and blast you repeatedly in the face until you aredead .Then he eats you .快速抽签,即可取出爆破器并向Gothon发射。他的小丑服装在他的身上四处流动,这使你无法瞄准。你的激光打中了他的服装,但完全没有击中他。这完全毁了他母亲买给他的崭新服装,这使他疯狂地飞起来,反复地对着你炸开,直到你死了。然后他吃了你。"""))return 'death'elif action == "dodge!":print(dedent("""Like a world class boxer you dodge , weave , slip and slide right as the Gothon's blaster cranks a laser past your head . In the middle of your artful your foot slips and you bang your head on the mental wall and pass out .You wake up shortly after only to die as the Gothon stomps on your head and eats you就像一个世界级的拳击手,你躲闪、编织、滑动和滑动,就像哥顿的爆破者用激光从你的头上划过一样。 在你的巧妙的中间,你的脚滑倒,你的头撞到精神墙上,昏倒了。你醒来后不久就死了,因为哥顿跺着你的头吃了你"""))return 'death'elif action == "tell a joke":print(dedent("""Lucky for you they made you learn Gothon insults in the academy . You tell the one Gothon joke you know :Lbhe zbgure vf fb sng , jura fur fgf nebhag gur ubhfrfur fgf nebhag gur ubhfr . The Gothon stops , tries not to laugh , then busts out laughing and can't move.While he's laughing you run up and shoot him square inthe head putting him down , then jump through the Weapon Armory door.幸运的是,它们使您在学院里学习了哥德的侮辱。你讲了一个你知道的Gothon笑话:Lbhe zbgure vf fb sng , jura fur fgf nebhag gur ubhfrfur fgf nebhag gur ubhfr .Gothon停了下来,试着不笑,然后突然大笑起来,动弹不得。当他在笑的时候,你跑上前朝他头部开了一枪,把他打倒在地,然后跳过武器库的门。"""))return 'laser_weapon_armory'else:print("DOES NOT COMPUTE!")return 'central_corridor'class LaserWeaponArmory(Scene):def enter(self):print(dedent("""You do a dive roll into the Weapon Armory , crouch and scan the room for more Gothons that might be hiding . It's dead quiet , too quiet . You stand up and run to the far side ofthe room and find the neutron bomb in its container.There's a keypad lock on the box and you need the code toget the bomb out . If you get the code wrong 10 times then the lock closes forever and you can't get the bomb . Thecode is 3 digits你向武器库俯冲,蹲下并扫视房间,寻找更多可能藏匿的哥顿人。这里死气沉沉的,太安静了。 你站起来,跑到房间的另一边,发现中子弹在它的容器里。盒子上有个小键盘锁,你需要密码才能把炸弹取出来。如果你把代码错了10次,那么锁就会永远关闭,你就拿不到炸弹了。密码是3位数字"""))code = "136"guess = input("[keypad]> ")guesses = 0while guess != code and guesses < 10 :print("BZZZZEDDD!")guesses += 1guess = input("[keypad]> ")if guess == code :print(dedent("""The container clicks open and the seal breaks , letting gas out.You grab the neutron bomb and run as fast as you can to the bridge where you must place it in the right spot.容器咔嗒一声打开,密封破裂,释放气体。你抓住中子弹,尽可能快地跑到桥上,你必须把它放在正确的位置。"""))return 'the_bridge'else:print(dedent("""The lock buzzes one last time and then you hear a sickening melting sound as the mechanism is fused together . You decide to sit there , and finally the Gothons blow up the ship from their ship and you die.锁最后一次嗡嗡作响,然后当机械融合在一起时,你会听到一种令人恶心的融化的声音。你决定坐在那里,最后哥特人炸毁了他们的船,你就死定了。"""))return 'death'class TheBridge(Scene):def enter(self):print(dedent("""You burst onto the Bridge with the netron destruct bomb under your arm and surprise 5 Gothons who are trying to take control of the ship . Each of them has an even uglier clown costume than the last . They haven't pulled their weapons out yet , as they see the active bomb under yourarm and don ' t want to set it off .你手臂下夹着尼特龙自毁炸弹冲进舰桥,让5个试图控制飞船的哥特人大吃一惊。他们每个人都有比上一个更丑的小丑服装。他们还没有拿出武器,因为他们看到你腋下的炸弹很活跃,不想引爆它。"""))action = input("> ")if action == "throw the bomb":print(dedent("""In a panic you throw the bomb at the group of Gothons and make a leap for the door . Right as you drop it a Gothon shoots you right in the back killing you . As you die you see another Gothon frantically try to disarm the bomb . You die knowing they will probablyblow up when it goes off .你惊慌失措地把炸弹扔给一群哥特人,然后向门口扑去。就在你掉下去的时候,一个哥顿朝你的后背开枪杀了你。当你死后,你看到另一个哥特人疯狂地试图解除炸弹的武装。你死的时候知道他们很可能会在它爆炸的时候降落。"""))return 'death'elif action == "slowly place the bomb":print(dedent("""You point your blaster at the bomb under your arm and the Gothons put their hands up and start to sweat.You inch backward to the door , open it , and then carefully place the bomb on the floor , pointing your blaster at it . You then jump back through the door ,punch the close button and blast the lock so the Gothons can't get out . Now that the bomb is placed you run to the escape pod to get off this tin can.你用爆能枪指着腋下的炸弹,哥特人举起手开始出汗。你向后退一步,打开门,然后小心地把炸弹放在地板上,用爆炸机对准它。然后你从门里跳回来,按一下关门按钮,然后打开门锁,这样哥特人就不能出去了。既然炸弹放好了,你就跑去逃生舱,从这个罐头罐上下来。"""))return 'escape_pod'else:print("DOES NOT COMPUTE!")return "the_bridge"class EscapePod(Scene):def enter(self):print(dedent("""You rush through the ship desperately trying to make it to the escape pod before the whole ship explodes . It seems like hardly any Gothons are on the ship , so your run is clear of interference . You get to the chamber with the escape pods , and now need to pick one to take . Some of them could be damaged but you don't have time to look.There's 5 pods , which one do you take?您拼命地冲过船,试图在整个船爆炸之前使其到达逃生舱。似乎船上几乎没有哥特人,因此你的奔跑没有干扰。你带着逃生舱进入密室,现在需要选择一个来逃生。其中一些可能已损坏,但您没有时间看。有5个吊舱,您要拿哪一个?"""))good_pod = 3guess = input("[pod #]> ")if int(guess) != good_pod:print(dedent("""You jump into pod ( guess ) and hit the eject button.The pod escapes out into the void of space , then implodes as the hull ruptures , crushing your body into jam jelly.  你跳入吊舱(猜测),然后按弹出按钮。吊舱从太空中逃出来,然后在船体破裂时内爆,把你的身体压成果酱果冻。"""))return 'death'else:print(dedent("""You jump into pod (guess) and hit the eject button.The pod easily slides out into space heading to the planet below . As it flies to the planet , you look back and see your ship implode then explode like a bright star , taking out the Gothon ship at the same time . You won!你跳入吊舱(猜猜)并按下弹出按钮。太空舱很容易滑入太空,向下面的行星前进。当它飞向这个星球时,你回过头来,看到你的飞船内爆,然后像一颗明亮的恒星一样爆炸,同时把哥顿飞船炸掉。你赢了!"""))return 'finished'class Finished(Scene):def enter(self):print("You won! Good job.")return 'finished'class Map(object):scenes = {'central_corridor': CentralCorridor(),'laser_weapon_armory': LaserWeaponArmory(),'the_bridge': TheBridge(),'escape_pod': EscapePod(),'death': Death(),'finished': Finished()}def __init__(self, start_scene):self.start_scene = start_scene              # 确定开始的场景def next_scene(self, scene_name):               val = Map.scenes.get(scene_name)            # 返回scenes字典中所有对应的类return valdef opening_scene(self):return self.next_scene(self.start_scene)        # 返回开始场景在scenes字典中对应的类a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

笨办法学python3 学习笔记 习题43 基本的面向对象分析和设计相关推荐

  1. 笨办法学python3 学习笔记 习题20-21

    习题二十 会话 # 从sys包中导入argv模块 from sys import argv# 将argv解包 script, input_file = argv# 定义print_all()函数,该函 ...

  2. 笨办法学python3 学习笔记 习题42 对象、类及从属关系

    类中的self 在类中定义函数时,第一参数永远是类的本身实例变量self,并且调用时,不用传递该参数.

  3. 笨办法学python__学习笔记

    笨办法学python –20190307 之前开始学习python过多次,每次都以失败告终.其实我有计算机语言的基础,高中时在步步高词典上是basic写过小程序,大学时自学C.不过学C的时候不得要领, ...

  4. 笨办法学Python——学习笔记1

        最近想学gtk,但是gtk在window上编译和运行挺慢的,于是搜索了一下发现了pygtk.在前几天 把环境都配好了,现在想同时学gtk和pygtk,但Python没学过,找到了<笨办法 ...

  5. 《笨办法学》 学习笔记一

    习题1-5 总结: 1.使用Terminal 创建一个目录: 在Terminal中 输入 mkdir mystuff(目录名可随意设置). 使用Terminal 进入这个目录:继续输入 cd myst ...

  6. 读书笔记 笨办法学python3

    读后评价 <笨办法学Python3>是一本适合Python3的初学者实用性书籍,以52个练习题为章节讲述了Python3的基础知识,包括基本语法.控制流程.列表.字典.元组.面向对象(类, ...

  7. 《笨办法学python3》再笨的人都能学会python,附PDF,拿走不谢

    <笨办法学python3>这本书的最终目标是让你起步python编程,虽然说是用"笨办法"学习写程序,但是其实并不是这样的. 所谓的"笨办法"就是指 ...

  8. 笨办法学python 粗略笔记(learn python the hard way)

    笨办法学python 粗略笔记(learn python the hard way) 标签(空格分隔): python # _*_ coding: utf_8 _*_ ''' ### ex1 prin ...

  9. [IT学习]Learn Python the Hard Way (Using Python 3)笨办法学Python3版本

    黑客余弦先生在知道创宇的知道创宇研发技能表v3.1中提到了入门Python的一本好书<Learn Python the Hard Way(英文版链接)>.其中的代码全部是2.7版本. 如果 ...

最新文章

  1. [01]关于TDD、BDD和DDD的一些看法
  2. Macbook外接显示器模糊解决方法
  3. 有进步--第二周作业
  4. AWK 学习手札之一: an AWK tutorial
  5. Distributed Systems笔记-Cryptographic Protocols
  6. 构建LINUX下的入侵检测系统——LIDS 系统管理命令--vlock
  7. 构建eureka高可用服务
  8. java把一段英文拆成单词_java编程题,输入一段英文文章,单词之间都已经用空格分隔,本人想以每5个单词为一行输出,怎么写?请指教...
  9. python正则匹配表达式(1)
  10. 多线程中线程参数的传递,不要使用局部变量
  11. commonJS — 数字操作(for Number)
  12. NB贝叶斯平凡而又神奇的贝叶斯方法
  13. LeetCode for SQL 176. 第二高的薪水 (ifnull limit order by)
  14. 相信大家看了这篇文章对Oracle如何工作有一个形象的了解!
  15. Matlab 2016 超详细安装教程
  16. 苹果平板怎么录屏_使用平板快速设计制作书写类教学视频
  17. steam++(GitHub加速)433端口占用解决方案
  18. 网站ping端口的操作方法和命令介绍
  19. HTML 前后端分离,再谈前后端分离开发和部署
  20. 基于单片机的智能视力保护监控系统设计

热门文章

  1. 怎么剪辑视频,这几个技巧必须学会
  2. 防火墙iptables原理及简单应用
  3. 解决问题:The field file exceeds its maximum permitted size of 1048576 bytes
  4. python爬虫,2020年《财富》中国500强排行榜数据爬取源码
  5. JavaScript数组与对象比较的正确姿势
  6. 一个短线日内交易策略 ——R-Breaker
  7. 提醒一下自己mpc加载字幕的设置
  8. X1 carbon 2015安装win7、win10后触控板驱动安装失败(双指滑动无效、多指操作无效)的另类解决之道
  9. vue 生成二维码工具
  10. STM32F10X SPI操作flash MX25L64读写数据