我如何返回到更高的一行并用Python执行它?

2024-04-25 22:35:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个相当新的编程和尝试创建一个非常简单的地下城游戏。我有大部分的工作,但我有一个小问题。这是我的密码:

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”,则可以正常工作,并将其返回到前一个房间,即厨房。有什么办法可以解决这个问题吗?提前感谢您的帮助!你知道吗


Tags: andthetoinyouinputarefirst
3条回答

让我们忽略缩进问题,这可能是您复制不正确的。你知道吗

你的控制流程一团糟。基本上让我们看看你的基本结构:

while True:
  first = input("You are in kitchen")     
  # additional program logic

你能理解为什么,不管你在这里做的剩余逻辑发生了什么,你总是会在continue之后回到厨房吗?你知道吗

要得到您真正想要的结构,一个选择是少一点顺序地编程。下面是一个psuedocode示例,介绍了设计游戏的一种可能方法,其中一些部分故意未指定。我提供这个是为了让你思考如何设计一个有意义的游戏。你知道吗

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

您可以使用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有很多值得研究的数据类型。你知道吗

我现在就让你去修改代码,因为你已经获得了解决问题的新视角。你知道吗

你的压痕弄乱了。你知道吗

first = input("You are in the kitchen. There are doors to the south (s) and east (e). ")放在while循环之前。你知道吗

相关问题 更多 >