笨方法学python习题52——创建web游戏

创建web游戏

在这个习题中,我们不会创建一个完整的游戏,相反,我们会为习题42中的游戏创建一个“引擎”(engine),让这个游戏能够在浏览器中运行起来。这会涉及重构习题42中的游戏,混合习题47中的结构,添加自动测试代码,最后创建一个可以运行这个游戏的web引擎。

这是一个很庞大的习题,预计花费时间一周到一个月。最好的方法:一点一点来,每晚完成一点,在进行下一步之前确认上一步已正确完成。

重构习题43中的游戏

在此, 你会再修改一次gothonweb项目(已在两个习题中修改).这种修改的技术叫“重构”。重构是一种编程术语,指的是清理旧代码或为旧代码添加新功能的过程。

在这个习题中你要做的是将习题47中的可测试的房间地图和习题43中的游戏这两种东西合并到一起,创建一个新的游戏结构。游戏内容不变,只是通过“重构”让它有一个更好的结构而已。

第一步:将ex47/game.py的内容复制到gothonweb/map.py中,然后将tests/ex47_tests.py的内容复制到tests/map_tests.py中,然后再次运行nosetests,确认它们还能正常工作。

将习题47的代码复制完毕后,就该开始重构它,让它包含习题43中的地图。我一开始会把基本结构为你准备好,然后你需要去完成map.py和map.tests.py里边的内容。

首先,用Room这个类来构建地图的基本结构。

#map.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.

""")

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,
    '*': generic_death

})

central_corridor.add_paths({
    'shoot!': generic_death,
    'dodge!': generic_death,
    'tell a joke': laser_weapon_armory

})

START = central_corridor

你会发现Room类和地图有一些问题。

1. 我们必须把以前放在if-else结构中的房间描述做成每个房间的一部分。这样房间的次序就不会被打乱了,这对我们的游戏是一件好事。是你后面需要修改的东西。

2. 原版游戏中我们使用了专门的代码来生成一些内容,如炸弹的激活键码、舰舱的选择等,这次游戏时先使用默认值好了,不过后面附加练习,会要求你加入这些功能。

3. 我为游戏中所有错误决策的失败结尾写了一个generic_death,你需要去补全这个函数。需要把原版游戏中所有的场景都加进去,并确保代码能正确运行。

4. 我添加了一种新的转换模式,以‘*’为标记,用来在游戏引擎中实现“捕获所有操作”的功能。

下面你要写的是自动测试tests/map_test.py

# map_tests.py

from nose.tools import *

from gothonweb.map import *

def test_room():

    gold = Room("GoldRoom",

                            """This room has gold in it you can grab. There's a

                            door to the north.""")

    assert_equal(gold.name, "GoldRoom")

    assert_equal(gold.paths, [])

def test_room_paths():

    center = Room("Center", "Test room in the center.")

    north = Room("North", "Test room in the north.")

    south = Room("South", "Test room in the south.")

    center.add_paths({'north':north, 'south':south})

    assert_equal(center.go('north'), north)

    assert_equal(center.go('south'), south)

def test_map():

    start = Room("Start", "You can go the west and down a hole.")

    west = Room("Trees", "There are trees here, you can go east.")

    down = Room("Dungeon", "It's dark down here, you can go up.")

    start.add_paths({'west': west, 'down': down})

    west.add_paths({'east': start})

    down.add_paths({'up': start})

    assert_equal(start.go('west'), west)

    assert_equal(start.go('west').go('east'), start)

    assert_equal(start.go('down').go('up'), start)

def test_gothon_game_map():

    assert_equal(START.go('shoot!'), generic_death)

    assert_equal(START.go('dodge!'), generic_death)

    room = START.go('tell a joke')

    assert_equal(room, laser_weapon_armory)

以上是完成地图,并且让自动测试可完整地检查整个地图。这包括将所有的generic_death对象修正为游戏中实际的失败结尾。让你的代码成功运行起来,并让你的测试越全面越好后面会对地图做一些修改,到时这些测试将用来确保修改后的代码还可正常工作。

会话和用户跟踪

 在web应用程序运行的某个位置,你需要追踪一些信息,并将这些信息和用户的浏览器关联起来。在HTTP协议的框架中,web环境是“无状态”的,意味着你的每一次请求和你的其他请求都是相互独立的。如果你请求了页面A,输入了一些数据,然后点击一个页面B的链接,那你发给页面A的数据就全部消失了。

解决这个问题的方法就是为web应用程序建立一个很小的数据存储,给每个浏览器进程赋予一个独一无二数字,用来跟踪浏览器所做的事。这个存储通常用数据库或者存储在磁盘上的文件实现。在lpthw.web这个小框架中实现这样的功能是很容易的,例如:

# session.sample.py

import web

web.config.debug = False

urls = (

        "/count", "count",

        "/reset", "reset"

)

app = web.application(urls, locals())

store = web.session.DiskStore('sessions')

session = web.session.Session(app, store, initializer={'count': 0}

class count:

    def GET(self):

        session.count += 1

        return str(session.count)

class reset:

    def GET(self):

        session.kill()

        return ""

if __name__ == "__main__":

    app.run()

为实现这个功能,需创建一个sessions/文件夹作为程序的会话存储位置,创建好以后运行这个程序,然后检查/count页面,刷新一下这个页面,看计数会不会累加上去。关掉浏览器以后,程序就会“忘掉”之前的位置,这也是我们的游戏所需要的功能。有一种方法可让浏览器永远记住一些信息,不过会让测试和开发变得更难。如果你回到/reset页面,然后再访问/count页面,你可以看到你的计数器被重置了,因为你已经关掉了这个会话。

你需要点时间弄懂这段代码,注意会话开始时count的值是如何设为0的,另外再看看sessions/下面的文件。看能不能打开。下面是我打开一个Python会话并解码的过程:

>>> import pickle

>>> import base64

>>> base64.b64decode(open("sessions/XXXXX").read())

"(dpl\nS'count'\np2\nI1\nsS'ip'\np3\nV127.0.0.1\np4\nsS'session_id'\np5\ns'XXXX'\np6\ns."

>>>

>>> x = base64.b64decode(open("sessions/XXXXX").read())

>>>

>>> pickle.loads(x)

{'count': 1, 'ip': u'127.0.0.1', 'session_id': 'XXXXX'}

所以,会话其实就是使用pickle和base64这些库写到磁盘上的字典。存储和管理会话的方法很多,大概和Python的web框架那么多,所以了解它们的工作原理并不是很重要。当然如果你需要调试或者清空会话,知道点原理还是有用的。

创建引擎

你应该已经写好了游戏地图和它的单元测试代码。现在要你制作一个简单的游戏引擎,用来让游戏中的各个房间运转起来,从玩家收集输入,并且记住玩家所在的位置。我们将用到你刚学到的会话来制作一个简单的引擎,让它可以:

1. 为新用户启动新的游戏;

2. 将房间展示给用户;

3. 接收用户的输入;

4. 在游戏中处理用户的输入;

5. 显示游戏的结果,继续游戏,直到玩家角色死亡为止。

为了创建这个引擎,你需要将bin/app.py搬过来,创建一个功能完备的、基于会话的游戏引擎。这里的难点是,我会先使用基本的HTML文件创建一个非常简单的版本,接下来将由你完成它。基本引擎是下面的样子:

# app.py

import web

from gothonweb import map

urls = (

    '/game', 'GameEngine',

    '/', 'Index',

)

app = web.application(urls, globals())

# little hack so that debug mode works with sessions

if web.config.get('__session') is None:

    store = web.session.DiskStore('sessions')

    session = web.session.Session(app. store, initializer=['room': None])

    web.config._session = session

else:

    session = web.config._session

render = web.template.render('templates/', base="layout")

class Index(object):

    def GET(self):

        # this is used to "setup" the session with starting values

        session.room = map.START

        web.seeother("/game")

class GameEngine(object):

    def GET(self):

        if session.room:

            return render.show_room(room=session.room)

        else:

            #why is there here? do you need it?

            return render.you_died()

def POST(self):

    form=web.input(action=None)

    # there is a bug here, can you fix it?

    if session.room and form.action:

        session.room = session.room.go(form.action)

    web.seeother("/game")

if __name__ == "__main__":

    app.run()

在这个脚本里你可以看到更多的新东西,不过了不起的事情是,整个基于网页的游戏引擎只要一个小文件就可以做到了。这段脚本里最有技术含量的就是将会话带回来的那几行,这对于调试模式下的代码重载是必须的,否则每次刷新网页,会话就会消失,游戏也不会再继续。

再运行bin/app.py之前,你需要修改PYTHONPATH环境变量。要运行一个最基本的Python程序,你就得学会环境变量,用Python的人就喜欢这样:

在终端输入下面的内容:

export PYTHONPATH=$PYTHONPATH: .

如果用的是Windows,那就在powershell中输入以下内容:

$env:PYTHONPATH = "$env:PYTHONPATH;."

你只要针对每一个shell会话输入一次就可以了,不过如果你运行Python代码时看到了导入错误,那就需要去执行一下上面的命令,或者是因为你上次执行的有错才导致导入错误的。

接下来需要删掉templates/hello_form.html和templates/index.html, 然后重新创建上面代码中提到的两个模板。下面是一个非常简单的templates/show_room.html,供你参考。

# show_room.html

$def with (room)

<h1> $room.name </h1>

<pre>
$room.description

</pre>

$if room.name == "death":
    <p><a href="/">Play Again?</a></p>
$else:
    <p>
    <from action="/game" method="POST">
        - <input type="text" name="action"> <input type="SUBMIT">
    </from>
    </p>

以上用来显示游戏中房间的模板。接下来你需要在用户跑到地图的边界时,用一个模板告诉用户,他的角色的死亡信息,即templates/you_died.html这个模板。

# you_dead.html

<h1>You Died!</h1>

<p>Looks like you bit the dust.</p>

<p><a href="/">Play Again</a></p>

准备好这些文件就可以做下面的事情了。

1. 再次运行代码tests/app_tests.py, 这样就可以测试这个游戏。由于会话的存在,你可能顶多只能实现几次点击,不过你应该可以做出一些基本的测试来。

2. 删除sessions/*下的文件,再重新运行一遍游戏,确认游戏是从一开始运行的。

3. 运行python bin/app.py脚本,试着玩一下你的游戏。

你需要和往常一样刷新和修正你的游戏,慢慢修改游戏的HTML文件和引擎,直到实现游戏需要的所有功能为止。

期末考试

到目前为止你写的游戏并不是很好,这只是你的第一版代码而已,你现在的任务就是让游戏更加完善,实现下面功能。

1. 修正代码中所有我提到和没提到的bug,如果你发现了新bug你可以告诉作者。

2. 改进所有的自动测试,以便可以测试更多的内容,知道你可以不用浏览器就能测到所有的内容为止。

3. 让HTML页面看上去更美观一点。

4. 研究一下网页登录系统,为这个程序创建一个登录界面,这样人们就可以登录这个游戏,并且可以保存游戏高分。

5. 完成游戏地图,尽可能把游戏做大,功能做全。

6. 给用户一个“帮助系统“, 让他们可以查询每个房间可执行哪些命令。

7. 为游戏添加新功能,想到什么功能就添加什么功能。

8. 创建多个地图,让用户可选择他们想玩的一张地图来进行游戏。你的bin/app.py应该可以运行给它的任意地图,这样你的引擎就可支持多个不同的游戏。

9. 最后,使用在习题48和习题49中学到的东西来创建一个更好的输入处理器。你手头已经有了大部分必要的代码,只需要改进语法,让它和你的输入表单及游戏引擎挂钩即可。

常见问题回答

我在游戏中用了会话(session),不能用nosetests测试?

你需要阅读并了解带reloader的会话:http://webpy.org/cookbook/session_with_reloader.

我看到了ImportError?

错误路径、错误python版本,PYTHONPATH没设置对,漏了__init__.py文件,拼写错误都检查一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值