我对编程很新,我正在尝试创建一个非常简单的地下城游戏。我有大部分工作,但我有一个小问题。这是我的代码:
print("Welcome to Matt's Dungeon!")
user = ""
stop = "q"
while user != "q":
first = input("You are in the kitchen. There are doors to the south (s) and east (e). ")
if first == "s":
print("You entered the furnace and fry yourself to death!")
break
elif first == "q":
break
elif first == "e":
second = input("You are in the hallway. There are doors to the west (w), south (s), and east (e). ")
if second == "w":
first == "s"
elif second == "q":
break
elif second == "e":
print("You are in the library. You found the princess! You are a hero!")
break
elif second == "s":
third = input("You are in the living room. There are doors to the west (w) and north (n). ")
if third == "w":
print("You entered the furnace and fry yourself to death!")
break
elif third == "n":
first == "e"
elif third == "q":
break
print("Goodbye!")
我遇到的问题是,如果用户在客厅输入“n”,我希望它回到走廊,但程序总是把它送回原来的厨房。但是,如果用户在走廊中输入“w”,则工作正常并将其返回到前一个房间,即厨房。关于我如何解决这个问题的任何想法?提前感谢您的帮助!
答案 0 :(得分:0)
您可以使用由代表房间的钥匙和您可以去的地方列表的值组成的dictionary。
例如:
# these match up to indexes for the list in the dict directions
NORTH = 0
EAST = 1
WEST = 2
SOUTH = 3
directions = {
"living room": ["dining room", None, None, "bedroom"]
}
# the current room, represented by the keys you create
current_room = "living room"
# an example imput
direction = "n"
if direction == "n":
possible_room = directions[current_room][NORTH]
if possible_room:
current_room = possible_room
一些非常草率的示例代码,但它得到了我的观点。提出一个程序的一般想法是研究如何存储数据,例如在Python中使用字典。
Python有很多值得研究的数据类型。
我会让你现在修复代码,因为你已经获得了解决问题的新视角。
答案 1 :(得分:0)
你的缩进搞砸了。
将first = input("You are in the kitchen. There are doors to the south (s) and east (e). ")
放在while循环之前。
答案 2 :(得分:0)
让我们忽略你可能错误复制的缩进问题。
你的控制流程非常混乱。基本上让我们来看看你的基本结构:
while True:
first = input("You are in kitchen")
# additional program logic
你能明白为什么,无论你在这里做的其余逻辑是怎么回事,你都会在continue
之后回到厨房吗?
获得实际需要的结构的一个选择是按顺序编程。这是一个设计游戏的可能方式的伪代码示例,其中一些设计部分是故意未指定的。我提供这个可以让你思考如何以一种有意义的方式设计游戏。
class Room():
def __init__(self,north,south,east,west):
self.north=north
self.south=south
self.east=east
self.west=west
kitchen = Rooms(None, 'hallway', 'library', None)
#initialization of other rooms are left as excercise to the reader
current_room = kitchen
while True:
print "You are in the %s" % current_room
move=raw_input("Where do you want to go")
if move=='q':
print "bye"
if move=='e':
current_room = current_room.east
#much logic is left as an exercise to the reader