在编写一个基于文本的角色扮演游戏时,尝试实现 NPC 交易系统,包括易货、偷窃和购物。易货和偷窃系统工作正常,但购买物品时会出现问题。尽管已尝试将整数变量限制为一次购买,但仍然无效。
2、解决方案
问题在于 for-loop 在满足条件后继续运行,尽管它包含 break 语句。解决方法是使用 continue 语句,以便在找到要购买的物品后立即继续下一个迭代,而不是中断整个循环。
以下是修改后的 selltoplayer() 函数:
def selltoplayer(self, player):
inv = self.readableinv() #Give us a viewable inventory
print("What would you like? I have the following items in stock:\n{0}".format(inv)) #display said inv
purchaseitem = input("Type the name of the item that you wish to purchase:\n") #Get the requested item
timespurchased = 0
for item in self.inventory: #search each item in the inventory
if timespurchased < 1:
if item.name == purchaseitem: #once the correct item is found...
ImportantCalculations.determinevalue(player, item) #get the item's value
if player.money >= item.buyvalue: #and make sure that the player can afford it.
confirm = input("So, you would like to purchase {0} for {1} Karics?\n".format(item.name,
item.buyvalue))
#Just a simple confirmation
if confirm.lower() == 'y' or confirm.lower() == 'yes': #If the player would like the item
print("Thanks for your purchase!") #the merchant is kind
player.inventory.append(item) #put the item in the player's inventory
self.inventory.remove(item) #take the item out of the merchant's inventory
player.money -= item.buyvalue #withdraw the proper amount of money from the player's stores
pinv = player.readableinv() #Readable inventory for player
print(pinv) #Debug line to make sure that the item was properly transferred
print(player.money) #Debug line to make sure that the money was properly transferred
timespurchased += 1
continue # Instead of break, use continue to move to the next iteration
elif confirm.lower() == 'n' or confirm.lower() == 'no': #If the player made a mistake
print("Oh, okay.") #Try to guilt the player out of leaving
exitsell = input("Would you like to browse again (A) or exit (B)?\n") #ask if they want to
#purchase something different or leave
if exitsell.lower() == 'a': #resell items
self.rselltoplayer(player)
elif exitsell.lower() == 'b': #exit
print("Thanks for stopping by!")
break
else:
print("Sorry, I don't speak gibberish. I'll see you around!")
break
else:
print("Sorry, I don't speak gibberish. I'll see you around!")
break
else:
print("I'm sorry, but you cannot afford this...")
self.rselltoplayer(player)
else:
break