python 类的实战


#
/usr/bin python #-*- coding:UTF-8 -*- ################################################################## #功能:本文件主要演示类 #日期:2018/07/25 #作者:fanpl ################################################################## #从语言到代码,自顶向下的面向对象练习 #引擎类,只要是 from sys import exit from random import randint #场景类 class Scence(object): def enter(self): print("这是一个父类的场景,并没有实现具体的什么功能,需要具体的场景去实例化") exit(0) #场景-死亡 class Death(Scence): Toyou = [ "你输了", "你将在这里结束你的旅程", "欢迎下次继续挑战" ] def enter(self): print("这里是死亡场景") print(Death.Toyou[randint(0,len(self.Toyou)-1)]) exit(1) #场景-中央走廊 class CenterCorridor(Scence): def enter(self): print("这里是中央走廊场景,需要讲个笑话才能通过,下面请开始你的旅程") action = input(">>>") if action =='射击!': print("死啦") return 'death' elif action == '避开!': print("我要的不是这个,还是死啦") return 'death' elif action =='讲笑话': print("哈哈哈,真开心,你可以通过啦") return 'laser_weapon_armory' else: print("不知道你干了个啥,重来") return 'center_corridor' #场景-激光武器库 class LaserWeaponArmory(Scence): def enter(self): print("这里是激光武器库,你需要找到中子弹,在乘坐救生船离开时,用它把飞船炸掉") print("但是要拿到中子弹,你需要输入三位数字密码,输错10次后,将永远锁住,不得打开") # code = "%d%d%d" %(randint(1,9),randint(1,9),randint(1,9)) code = '888' print("请输入密码:") guess = input("[keywd]>>>>") guesses = 0 while guess != code and guesses < 10: print("密码错误,请重新输入:") guesses += 1 guess = input("[keywd]>>>>") if guess == code: print("你猜中了密码,请带走中子弹,并在乘坐救生船离开时,炸掉飞船") return 'the_bridge' else: print("不好意思,您将止步于此") return 'death' #场景-主控仓 class TheBridge(object): def enter(self): print("这里是主控仓,在离开飞创主控仓时,记得埋中子弹,以炸毁飞船") print("请输入你的操作:") action = input(">>>>") if action == "丢掉炸弹": print("干嘛丢掉呀,不理解,算了,你死了") return "death" elif action == "埋好炸弹": print("干的漂亮") return "escape_pod" else: print("弄啥嘞") return "the_bridge" #逃生舱 class EscapePod(object): def enter(self): print("这里就是逃生舱了,但是有两个逃生舱,猜中的才能安全离开哟,1还是2呢?") # good_pod = randint(1,3) good_pod = 1 guess = input(">>>") if int(guess) != good_pod: print("不好意思,您没猜中,将走入地狱") return 'death' else: print("恭喜恭喜,经过千难万阻,你终于走向胜利") exit(0) #地图类:主要 有查看当前位置,进入下一个场景 class Map(object): scenes = { 'center_corridor':CenterCorridor(), 'laser_weapon_armory':LaserWeaponArmory(), 'the_bridge':TheBridge(), 'escape_pod':EscapePod(), 'death':Death() } def __init__(self,start_scene): print('%s is a new scene' %start_scene) self.start_scene = start_scene def next_scene(self,scene_name): return Map.scenes.get(scene_name) def opening_scene(self): return self.next_scene(self.start_scene) class Engine(object): def __init__(self,scene_map): print('%s is the map of the engine' %scene_map) self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() while True: # print("##################################################################") next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) a_map = Map('center_corridor') a_game = Engine(a_map) a_game.play()

输出结果:

 

posted @ 2018-07-31 20:52  pretend_smile  阅读(250)  评论(0)    收藏  举报