笨办法学Python3 ex52 习题52

学习第52课有一个星期了, 这一课有点绕, 不过还是通过大量的print来分析程序如果动作的, 一行一行的分析后, 渐渐明白了工作原理,特别是.globals(). 

下面是planisphere.py代码

class Room(object):

	def __init__(self, name, description):
		self.name = name
		self.description = description
		self.paths = {}

	def go(self, direction):
		return self.paths.get(direction, None)

	def add_paths(self, paths):
		self.paths.update(paths)



central_corridor = Room("Central Corridor",
"""
The Gothons of Planet Percal #25 have invaded your ship and destroyed
your entire crew. You are the last surviving member and your last mission
is to get the neutron destruct bomb from the Weapons Armory, put it in the 
bridge, and blow 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 grimy teeth, and evil clown costume
flowing around his hate filled body. He's blocking the door to the Armory and about
to pull a weapon to blast you.
""")

laser_weapon_armory = Room("Laser Weapon Armory",
""" 
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 fvgf nebhaq qur ubsjf, fuia sjf elj  lsjf owejf lsfjl.
The Gothon stops, tries not to laugh, the busts out laughing and can't move. While he's laughing
you run up and shoot him square in the head putting him down , then jump through the Weapon
Armory door.

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 of the room and
find the neutron bomb in its container. There's a keypad lock on the box and you need the code to 
get the bomb out. If you get the code wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits.
""")

the_bridge = Room("The Bridge",
"""
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.

You burst onto the Bridge with the netron destruct bomb under your arm and surprise 5Gothons 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 your arm and don't want to set it off.
""")

escape_pod = Room("Escape Pod",
"""
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 eacape pod to get off this tin can.

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?
""")

the_end_winner = Room("The End",
"""
You jump into pod 2 and hit the eject button. The pod easily slides out into space heading to the planet below. 
As if 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 win!
""")

the_end_loser = Room("The End",
"""
You jump into a random pod 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.
""")

shoot_death = Room("The End",
"""
you shoot your self!
""")

dodge_death = Room("The End",
"""
you dodge to wrong side, get hit by a machine!
""")

number_death = Room("The End",
"""
please, call your mother then fall down into a hole!
""")

escape_pod.add_paths({
    '2': the_end_winner,
    '*': the_end_loser
})

generic_death = Room("death", "You died.")

the_bridge.add_paths({
    'throw the bomb': generic_death,
    'slowly place the bomb': escape_pod
})

laser_weapon_armory.add_paths({
    '0132': the_bridge,
    'i don`t know': number_death
})

central_corridor.add_paths({
    'shoot!': shoot_death,
    'dodge!': dodge_death,
    'tell a joke': laser_weapon_armory
})




START = 'central_corridor'

def load_room(name):  #  globals().get(name)返回了一个类, 还有参数  central_corridor = Room("Central Corridor",'XXXXXXXXXX')
	                                         #其实retrun就是返回了这个实例对象   central_corridor, 不是字符串


	"""
	There is a potential security problem here.
	Who gets to set name? Can that expose a variable?
	"""
	return globals().get(name)  # global() 就是把这个.py文件里所有变量都以字典形式拿到,包含生成的实例,实例对象如下面这样
                                # {'laser_weapon_armory' : <__main__.Room object at 0x00000292DE7A29A0>}
def name_room(room):
	"""
	Sam possible security problem. Can you trust room?
	What`s a better solution than this globals lookup?
	"""
	for key ,valure in globals().items():  # item()就是把每个字典转成了小元组,方便key,value来取出
		if valure == room:
			# print (key)
			return key


# print(name_room(laser_weapon_armory))   #'laser_weapon_armory', <__main__.Room object at 0x00000292DE7A29A0>
# print(globals())
# print(load_room(name_room(central_corridor)))
# load_room(name_room(central_corridor))
# print(load_room(name_room(central_corridor)).go('tell a joke')())
# print(globals())

下面是app.py

from flask import Flask, render_template, session, redirect, url_for, request
from gothonweb import planisphere

app = Flask(__name__)

@app.route('/')
def index():
	# this is used to "setup" the session with starting values
	session['room_name'] = planisphere.START
	# print(session)    #查看session到底是什么, 原来是一个字典<SecureCookieSession {'room_name': 'central_corridor'}>
	return redirect(url_for('game'))   #url_for('game')  返回 game 函数上面路由括号里面参数 '/game',相当于redirect('/game')
#  redirect()就是重新导向  '/game'  也就是127.0.0.1:5000/game, 简单来说打开127.0.0.1:5000,实际打开的是127.0.0.0:5000/game

@app.route('/game', methods=['GET', 'POST'])
def game():
	# print(session.get('room_name'))  #查看sesstion中 key 为room_name的 value 是什么: central_corridor
	# print(type(session.get('room_name')))   #    <class 'str'>
	room_name = session.get('room_name')   # central_corridor
	print("room name A:", room_name)

	if request.method == 'GET':   # 第一次打开页面,从上面的路由'/', 定向到'/game',一定会走GET
		print('走的GET')          #  每一次提交完页面刷新后,先走一次GET, 提交完走POST,再走一次GET,
		if room_name:

			room = planisphere.load_room(room_name)   # central_corridor = Room("Central Corridor",'adfasdfasd')3
			print(type(room))
			return render_template("show_room.html", room=room)

		else:
			return render_template('you_died.html')    # 走不到这里

	else:
		print('走的POST')
		action = request.form.get('action')  # requst.form.get('action')能拿到网页端input name='action'的输入信息
		# print(action)   form.get拿到tell a joke
		if room_name and action:

			# print('Post room_name :',room_name)
			room = planisphere.load_room(room_name)   # central_corridor
			next_room = room.go(action) # next_room 拿到网页端input name='action'的输入信息去planisphere.py
			print(next_room)
			# 里面查找, 因为对应各room名字早已经添加了一些字典 例如:  central_corridor.add_paths({
																#     'shoot!': generic_death,
																#     'dodge!': generic_death,
																#     'tell a joke': laser_weapon_armory
																# })
																#如果输入是tell a joke, go函数会返回对应的房间
			if not next_room:
				session['room_name'] = planisphere.name_room(room)

			
			else:
				session['room_name'] = planisphere.name_room(next_room)    #{'next_room' : 'laser_weapon_armory '}

			print("session['room_name']:::", session ,'rome name B:',room_name)
		return redirect(url_for('game'))  #room=next_room返回给网页刚拿到新房间名


app.secret_key = 'asdfasdf21654asdgf156a6dsg'

if __name__ == "__main__":
	app.run()

 下面是show_room.html

{% extends "layout.html" %}

{% block content %}

<h1>{{ room.name }}</h1>

<pre>
{{ room.description }}
</pre>

{%  if room.name in ['death', 'The End'] %}
    <p><a href="/">Play Again</a></p>

{% else %}
    <p>
    <form action="/game" method="POST">
        - <input type="text" name="action"> <input type="submit">
    </form>
    </p>
{% endif %}

{% endblock %}

 下面是layout.html

<html>
    <head>

        <title>Gothons From Planet percal #25 From layou.html</title>
    </head>
    <body>


    {% block content %}

    {% endblock %}
    </body>
</html>

 下面是you_died.html , 因为session['room_name']永远都能拿到数据, 所以room_name不为空, 也就永远无法走到这里,除非 planisphere.py里面的START里面赋值为空,这样开始的页面就死掉了,没意义了.

{% extends 'layout.html' %}

{% block content %}
<h2> 我是you_died.html {{ room.name }} </h2>

    <pre>
    {{ room.description }}
    </pre>
{% endblock %}

ZED在书中说要用generic death写一个函数把所有死法写里面, 不太明白如何折腾,有人知道的可以回复.

 

 下面是app.py

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值