Reputation: 15
I am making a rogue-like game and was wondering if there was a way to allow a player to drop an item by entering: Drop [Item Name]
Drop
being the command and the item name being one located in your inventory, e.g. if I had a rock that I wanted to get rid of I would input: Drop Rock
.
CO = "Rock"
Inventory = {"Slot 1" : "Empty","Slot 2" : "Empty","Slot 3" : "Empty","Slot 4" : "Empty","Slot 5" : "Empty"}
def DROP():
Slot_Number = int(input("\nInventory Slot to drop: "))
Slot_Number = str(Slot_Number)
Slot_Number = ("Slot " + Slot_Number)
CO = Inventory[Slot_Number]
Inventory[Slot_Number] = "Empty"
Upvotes: 0
Views: 214
Reputation: 15
I took it one step further than @mfitzp and made it all one line of code so that Drop Stick will drop a stick. Here is the code I used:
def DROP(CHOICE):
global NV
NV = CHOICE[5:]
str(NV)
CHOICE = input("\nWhat do you want to do (type Help for list of commands): ")
if CHOICE.startswith("Drop ") or CHOICE.startswith("drop ") or CHOICE.startswith("DROP "):
DROP(CHOICE)
if NV in I:
SN = I.index(NV)
I[SN] = ""
CO = NV
Upvotes: 0
Reputation: 15545
Since you're using numbered slots (rather than e.g. "bag", "pocket") a simpler approach would be to use a list for your inventory. You can index into a list, and find items in a list by value, easily.
I would also suggest you use None
or at least an empty string ""
to represent the empty slot ( as these both equate to False
:
Inventory = ["","","","","","",""]
You can then adapt your function as follows:
def DROP():
Slot_Number = int(input("\nInventory Slot to drop: "))
Inventory[Slot_Number] = ""
Note that because Python indexing is zero-based, if you want to allow the user to enter 1
for the first slot, rather than 0
, you will need to subtract one from the provided value.
def DROP():
Slot_Number = int(input("\nInventory Slot to drop: "))
Inventory[Slot_Number-1] = ""
To print the inventory in a nice list you could use something like the following. The i or "Empty"
cosntruction might be new to you:
for n, i in enumerate(Inventory):
print("%d - %s" % (n+1, i or "Empty"))
In i or "Empty"
we make use of the falsey value of an empty string together with or
shortcutting. If i
is True
the value in i
will be shown, if it is False
(e.g. empty string) the value after the or
will be printed instead. An equivalent without this would be:
for n, i in enumerate(Inventory):
if i:
print("%d - %s" % (n+1, i))
else:
print("%d - Empty" % (n+1))
Finally, an example of a drop_by_name
function, where you use .index()
to find the location of something in your list Inventory
and remove it:
def drop_by_name():
item_name = input('\nEnter the name of the item to drop: ')
if item_name in Inventory:
Slot_Number = Inventory.index(item_name)
Inventory[Slot_Number] = ""
Upvotes: 1