我开始把这当作一件有趣的事情去尝试。 (下面的内容可能不是答案,但无论如何......发布它)
但让我告诉你一件事:该指南的质量非常“低”(是的,我可能太严厉了,但是嘿!只是一个意见)。即使这是初学者编程,我也看不出有什么理由不引入字典和其他常用工具。
我在第 10 或 11 点停了下来,继续进行目前为止的操作。
基本上目标是根据你给我的网站上的数字搬到厨房。如果您有兴趣了解更多信息或有任何问题,我很乐意回答。
祝你好运 :)
import sys
room_list = []
#2,3,4
room_list.append(["Bedroom 2, You can go north and east.",3,1,None,None])
room_list.append(["South Hall, ...",4,2,None,0])
room_list.append(["Dining Room, ...",5,None,None,1])
room_list.append(["Bedroom 1, ...",None,4,0,None])
room_list.append(["North Hall, ...",6,5,1,3])
room_list.append(["Kitchen, ...",None,None,2,4])
room_list.append(["Balcony, ...",None,None,4,None])
#5
current_room = 0
#6
#print(room_list)
#7
#print(room_list[0])
#8
#print(room_list[current_room])
#9
#print(room_list[current_room][0])
#10
done = False
#10++ Here I started writing my own code... :)
directions = {"North":1,"East":2,"South":3,"West":4}
#11
while not done:
print("\n"+room_list[current_room][0])
q = "0"
valid_choice = False
while not valid_choice:
while not directions.get(q.title()):
if q != "0":
print("Try again...")
q = raw_input("Where do you want to go? (North,East,South or West) Or Quit (Q)")
if q.title() == "Q":
print("You pressed Q. Exit")
sys.exit()
next_move = directions.get(q.title())
next_room = room_list[current_room][next_move]
if next_room:
valid_choice = True
current_room = next_room
else:
print("You can't go that way")
q = "0" # reset question
if current_room == 5:
print("\nYou are in: "+room_list[5][0])
done = True
问:您好,谢谢!如果你不介意我问的话,那是做什么的
方向 = {"北":1,"东":2,"南":3,"西":4} 和
Directions.get(q.title()) 做什么?
Directions = {"North":1,"East":2,"South":3,"West":4} 在本例中是一本字典。它包含键(北、东、南、西)及其相应的值(1、2、3、4)。因此,当您输入 Directions["North"] 时,您实际上得到的值是 1。
然而,还有另一种获取值的方法,那就是使用 Directions.get() 函数。当你这样做并且密钥不存在时None被返回。例如。 Directions.get("monkey") = None,但 Directions.get("East") = 2。当我们使用 while not 循环时,这非常有用。在用户输入有效的内容之前,q 将为 None 并且问题会重复。
最后 q 是从问题返回的字符串。 str.title() 函数返回首字母大写的字符串。例如。 "hellOOO".title() = "Hellooo" 这就是为什么你可以输入 "easT" 并仍然得到 "East",这是使 Directions.get("East") 工作所需的值。
问:还有一个问题(抱歉我对此很陌生),如果我想补充的话
一个退出函数,我该在哪里插入它?我试着把它排成一行
在 else 语句之前,但我收到错误。
I added:
import sys
And
if q.title() == "Q":
print("You pressed Q. Exit")
sys.exit()