我想我把这个问题命名得很糟糕,但我真的想不出更好的东西。对此感到抱歉(另外,英语不是我的第一语言,所以对我的语法错误感到抱歉)。
在“Learn Python The Hard Way”的 ex45 中,我必须制作一个文本游戏,在某些条件下,例如每个房间使用一节课。我使用 ex44 中的代码(几乎与下面的代码相同)作为原型,因为我真的无法理解最后三行如何工作以及如何与所有内容交互。我认为对于像我这样的编程新手来说太多了,我什至尝试逐行写下来,遵循每一步。
另外,我还尝试制作变量current_scene
,因此如果您在变量中引入未考虑的答案if
,则重复该场景。
from sys import exit
from random import randint
class Engine(object):
def __init__(self, map_scenes):
self.map_scenes = map_scenes
def play(self):
current_scene = self.map_scenes.open_scene()
while True:
print "\n---------"
next_scene_name = current_scene.text()
current_scene = self.map_scenes.next_scene(next_scene_name)
class Scene(object):
def texto(self):
print "Parent class for scenes"
exit(1)
class Death(Scene):
types = [
"You're death.",
"You pass away."
]
def text(self):
print Death.types[randint(0, len(self.types)-1)]
exit(1)
class Again(Scene):
repeat = [
"Can you repeat?",
"Try again.",
"One more time."
]
def text(self):
print Again.repeat[randint(0, len(self.repeat)-1)]
print current_scene # =/
class Intro(Scene):
def text(self):
print "The intro scene"
return 'start'
class Start(Scene):
def text(self):
print "The first scene"
print "Where do you want to go?"
next = raw_input("> ")
if next == "bear":
return 'bear'
elif next == "valley":
return 'valley'
elif next == "death":
return 'death'
else:
return 'again'
class Bear(Scene):
def text(self):
print "The second scene."
print "And so on..."
exit(1)
class Valley(Scene):
def text(self):
print "Alternative second scene."
print "And so on..."
exit(1)
class Map(object):
scenes = {
'intro': Intro(),
'start': Start(),
'bear': Bear(),
'valley': Valley(),
'again': Again(),
'death': Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def open_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('intro')
a_game = Engine(a_map)
a_game.play()
我真的希望我已经很好地解释了自己,我在这个练习中卡住了好几天,似乎我根本没有做任何进展。