【发布时间】:2020-04-01 14:17:42
【问题描述】:
我正在制作一款基于房间的文字冒险游戏。如果您运行代码,如果您进入房间边界(即从卧室 2 开始,然后到卧室 1,反之亦然),它会起作用,但是一旦您走出边界,就会出现错误:
>>> print(room_list[int(current_room)][0])
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
删除int() 后,我得到一个不同的错误:
TypeError: list indices must be integers or slices, not str
如何修复它以保留 None 类型?或者只是让代码工作。下面是我的代码。
def main():
done = False
room_list = []
current_room = 0
# Append rooms to different numbers
room = ["\nYou are in bedroom 2.\nThere is a passage north and east.", "3", "1", None, None] # Room name, N, E S, W
room_list.append(room)
room = ["\nYou are in at southern hall.\nThere is a passage north and east.", "4", "2", None, "0"]
room_list.append(room)
room = ["\nYou are in the dining room.\nThere is a passage north and west.", "5", None, None, "1"]
room_list.append(room)
room = ["\nYou are in bedroom 1.\nThere is a passage east and south.", None, "4", "0", None]
room_list.append(room)
while not done:
print(room_list[int(current_room)][0])
answer = input('What direction? ')
# Check for correct direction and check if exists
if answer == "n":
next_room = room_list[int(current_room)][1]
current_room = next_room
if next_room == None:
print("You can't go that way. ")
elif answer == "e":
next_room = room_list[int(current_room)][2]
current_room = next_room
if next_room == None:
print("You can't go that way. ")
elif answer == "s":
next_room = room_list[int(current_room)][3]
current_room = next_room
if next_room == None:
print("You can't go that way. ")
elif answer == "w":
next_room = room_list[int(current_room)][4]
current_room = next_room
if next_room == None:
print("You can't go that way. ")
elif answer == "q":
done = True
else:
print("Invalid destination, try again.")
main()
【问题讨论】:
-
好吧,因为
current_room(或next_room)是None...你应该在if语句之后移动current_room = next_room,在else子句下
标签: python python-3.x nonetype