Reputation: 23
I am currently creating my first "big" python project. In the game you are a wizard who has to fight a monster using abilities. If you reach 0 HP you lose. If the monster reaches 0 HP you win.
My question is:
I've created a menu which can be operated by the keys 1, 2, 3 and 4.
This is the code:
menu = int(input('''
Press 1 to battle!
Press 2 to get to the shop
Press 3 to get to the upgrades
Press 4 to exit the game'''))
buying = int(input('''
(1)Buy an apple!
(2)Buy a cake!
(3)Buy a MedPack!'''))
if menu == 1:
print("You can use your Abilities with A, B and C")
print(" ")
while health_player >= 0:
spells = input("Press a for an attack, b for a fire ball or C for a Thunder!"
if spells == "A":
damage_monster = random.randrange(10, 30)
health_monster -= damage_monster
print("The monster lost", damage_monster, "HP and still has", health_monster, "/200 left.")
damage = random.randrange(10, 30)
health_player -= damage
print("You lost", damage, "HP and still have", health_player, "/200 left.")
print(" ")
... followed by other menu options:
elif menu == 2:
print('''
-----------------------
Welcome to the shop!
Buy an apple to get a part of your health back!
''')
elif menu == 3:
pass
elif menu == 4:
sys.exit()
However, the menu option selection isn't working as expected. The shop always comes up even if I press 1, 3 or 4. How can I fix this?
Hope you can understand and help me. :)
Thanks in advance!
Upvotes: 0
Views: 110
Reputation: 9711
Answer completely re-written in light of new information and code.
If I understand your issue correctly:
- Why am I being prompted to buy something if I don't select '2' from the menu?
This is because the 'buying' input
prompt immediately follows the 'menu' input
prompt. As shown below. Since this game is written in script for, the code runs top to bottom.
menu = int(input('''
Press 1 to battle!
Press 2 to get to the shop
Press 3 to get to the upgrades
Press 4 to exit the game'''))
buying = int(input('''
(1)Buy an apple!
(2)Buy a cake!
(3)Buy a MedPack!'''))
I suggest you move the 'buying' prompt inside the elif menu == 2
block.
As shown here:
if menu == 1:
# Do battle stuff ...
elif menu == 2:
print('''
-----------------------
Welcome to the shop!
Buy an apple to get a part of your health back!
''')
# Move your 'buying' prompt here:
buying = int(input('''
(1)Buy an apple!
(2)Buy a cake!
(3)Buy a MedPack!'''))
elif menu == 3:
# Do menu 3 stuff ...
elif menu == 4:
sys.exit()
I've tested this logic and it appears to be working correctly. Give it a go ...
1) Have a look into string formatting. This will give you some power and control over your on-screen prompts.
2) Consider writing your game in functions
, or if you want to take it a step further, classes
, rather than as a script. This will give you a lot more flexibility. Give it a try!
Upvotes: 1