I am trying to simplify this code for an Oregon trail game:
if choice==1:
oxen+=amount
elif choice==2:
food+=amount
elif choice==3:
clothing+=amount
elif choice==4:
ammo+=amount
elif choice==5:
parts+=amount
I would like to be able to do something more with this "feel":
shop_list=[oxen, food, clothing, ammo, parts]
shop_list[choice]+=amount
Is there any way to implement something similar? Mind that I would like to keep the values stored as their own variable, not only as values inside of a list.
I tried the previous idea, and had results that would not work as expected, only changing the value in the list, Not the global variable.
You can achieve your preferred behavior using a dictionary to store the state. In the following code snippet the possible choices are stored in a tuple.
choice, amount = 1, 3
choice_options = ("oxen", "food", "clothing", "ammo", "parts")
shop_state = {
"oxen": 0,
"food": 0,
"clothing": 0,
"ammo": 0,
"parts": 0
}
shop_state[choice_options[choice - 1]] += amount
print(shop_state)
Output:
{'oxen': 3, 'food': 0, 'clothing': 0, 'ammo': 0, 'parts': 0}