【发布时间】:2015-01-15 13:56:26
【问题描述】:
所以这是我的下一个问题,我的一个学生在他的基于文本的游戏中的代码。这个想法是,在游戏中,您可以拿起一个物品并将其放入选定的口袋中。问题是,当他运行此代码时,他会得到提示去捡口袋以放入物品,但随后输入提示只是循环显示有关将物品放在哪里的相同问题。
想法?
class grab():
#Checks the player's pockets for items.
def pocket_check(inventory, pocket, thing, input, state, list, room):
if inventory[pocket] != None:
print("You find that your %s is stuffed full.")%(input)
if inventory[pocket] == None:
inventory[pocket] = thing
del room["Items"][thing]
state["Strain"] += list[thing]["Weight"]
print("You put the %s in your %s.")%(thing, input)
#Takes items and putting them in the player's inventory
def grab(inventory, thing, list, state, room):
go = True
while go:
if list != "WEAPON" and state["Strain"]+list[thing]["Weight"] <= state["Strength"]:
inp = input("Where will you put it?").lower()
inp_broke = inp.split(" ")
if inp_broke[0] == "stop":
go = False
elif inp_broke[0] != "put":
inp = input("Where will you PUT it?").lower()
inp_broke = inp.split(" ")
elif inp_broke[0] == "put":
if inp_broke[1:3] == "shirt pocket":
pocket_check(inventory, "Shirt Pocket", thing, "shirt pocket", state, list, room)
if inp_broke[1:4] == "left front pocket":
pocket_check(inventory, "Left Front Pocket", thing, "left front pocket", state, "ITEM", room)
if inp_broke[1:4] == "right front pocket":
pocket_check(inventory, "Right Front Pocket", thing, "right front pocket", state, "ITEM", room)
if inp_broke[1:3] == "back pocket":
pocket_check(inventory, "Back Pocket", thing, "back pocket", state, "ITEM", room)
【问题讨论】:
-
在空间分割时要小心:
inp.split(" ")。任何(意外)双倍空格都将导致inp_broke中的值为空。改用默认的空格分割:inp_broke = inp.split(). -
你应该鼓励 PEP 8 命名标准——比如以大写字母开头的类名。
-
你应该让玩家用椰子当口袋。然后再给他一个酸橙。成就获得:将酸橙放入椰子中。
-
您可以在循环外使用
break,而不是使用go = False(然后您的循环就是while True:。这更常见。
标签: python loops python-3.x input