所以这是我在他的基于文本的游戏中使用我的学生代码之一的下一个问题。这个想法是,在游戏中你可以拿起一个项目并把它放在一个选定的口袋里。问题是,当他运行这段代码时,他会提示选择一个口袋放入该项目,但输入提示只是循环使用相同的问题关于放置项目的位置。
想法?
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)
答案 0 :(得分:0)
来自你的代码:
np_broke = inp.split(" ")
...
if inp_broke[1:3] == "shirt pocket":
从split()中切片列表会返回字符串列表,而不是字符串:
>>> inp = "put shirt pocket"
>>> inp_broke = inp.split(" ")
>>> inp_broke[1:3]
['shirt', 'pocket']
答案 1 :(得分:0)
此
if inp_broke[1:3] == "shirt pocket":
不起作用。 inp_broke
是一个(字符串)列表,并不会神奇地组合成一个字符串。
您可以使用str.join
方法:
if " ".join(inp_broke[1:3]) == "shirt pocket":
这会将列表中的单独项组合成一个字符串,由初始字符串(在本例中为单个空格)分隔。
答案 2 :(得分:0)
while go
将永久循环,除非在循环中将False
分配给go
。 pocket_check
方法可以返回一个布尔值,具体取决于它的成功和调用时分配给go
的返回值。