正如这个站点上的许多其他提问者所做的那样,我正在使用的艰苦方式来学习Python。
我在第36课上,在第35课中,我们根据他带领我们完成的游戏,创建了我们自己的BBS风格的文本游戏。
http://learnpythonthehardway.org/book/ex36.html
http://learnpythonthehardway.org/book/ex35.html
我想提高游戏的“难度”,所以我把迷宫弄得更复杂了。有些房间有多扇门,而不是每个房间都有一个入口。其中一些门没有任何结果,但有些房间可以从地图上的多个房间进入。
因此,在monster_room中,播放器可以通过monkey_room或empty_room进入。问题是,无论播放器从哪里输入,monster_room都运行相同的代码。由于我首先建立了empty_room,门的选择和结果是基于那个房间。
以下是monster_room代码:
def monster_room():
print "You have stumbled into a dark room with a giant, but friendly, monster."
print "There are four doors:"
print "One straight ahead, one to your right, one to your left, and the one you just entered through."
print "Which door would you like to choose?"
door = raw_input("> ")
if "left" in door:
dead("The door magically recedes into the wall behind you and you find yourself forever trapped in a black room with no doors, no windows, and no hope of escape.")
elif "right" in door:
monkey_room()
elif "straight" in door:
dead("You step into the abyss and fall through nothingness to your certain death.")
else:
print "You found a magical shortcut to the Treasure Room!"
treasure_room()好吧,很简单,对吧?但是,如果有人从猴子的房间进入,门的位置是不同的。左边会通向空旷的房间,右通向深渊,直到永远被困住,回到原来的道路上,你依然是一条神奇的捷径。
我知道我可以创建一个monster_room_2,或者一些只能从monkey_room输入的东西,并在“正确的地方”设置所有的门,但我想可能有一种方法可以让游戏根据发送它们的函数提供选项。这有意义吗?
任何帮助都将不胜感激。
发布于 2014-08-11 18:42:49
您可以为当前的房间设置一个全局值,然后使用它。
CURRENT_ROOM = "whatever"
def monster_room():
global CURRENT_ROOM
if CURRENT_ROOM = "monkey":
"""Display monkey room choices"""
else:
"""display other room choices"""
# don't forget to set your global to the room selected:
CURRENT_ROOM = new_room如果您愿意,当然可以使用函数而不是字符串:
CURRENT_ROOM = monkey_room但是,全局变量是一种代码气味。使用类和/或将当前空间作为变量传入会更好。
我会做这样的事:
class Game:
def __init__(self):
self.current_room = self.initial_room
def initial_room(self):
...
def monster_room(self):
...
def monkey_room(self):
...
def display_room(self):
self.current_room()因此,在游戏“循环”中,您可以创建一个Game实例,并使用它来帮助跟踪您当前的位置以及诸如此类的事情。
https://stackoverflow.com/questions/25249933
复制相似问题