so I’m learning Python with ‘Learn Python The Hard Way’,
I am currently writing a simple text adventure.
my problem is in the ‘combat’ part of the code (provided below). only the numbers 1 and 2 are meant to be pressed by the user. if a different int is pressed, it correctly throws up ‘sorry don’t understand’, but if a letter is pressed, it freaks out and exits saying, (quite rightly) that it was expecting an int. obviously my question is, how do I set it to expect both, and throw up the error when a letter is pressed?
Thanks in advance 🙂
while True:
player_dmg = randint(1, 10)
enemy_dmg = randint(1, 10)
if enemy_hp < 0:
os.system('clear')
print "[ENEMY NUTRALISED]"
print
print hit_e
raw_input()
return 'forth_area'
elif player_hp < 0:
return 'death'
else:
print "[COMBAT OPTIONS]"
print "1. Attack"
print "2. Defend"
print
choice = raw_input("*>>*")
choice = int(choice)
print
if choice == 1:
enemy_hp = enemy_hp - player_dmg
print "[ENEMY STATUS: %d]" % enemy_hp
print "[DAMAGE DONE: %d]" % player_dmg
print
player_hp = player_hp - enemy_dmg
print "[DAMAGE RECIVED: %d]" % enemy_dmg
print "[CURRENT STATUS: %d]" % player_hp
elif choice == 2:
enemy_hp = enemy_hp - player_dmg / 2
print "[ENEMY STATUS %d]" % enemy_hp
print "[DAMAGE DONE %d]" % player_dmg
print
player_hp = player_hp - enemy_dmg
player_hp = player_hp + 3
print "[DAMAGE RECIVED: %d]" % enemy_dmg
print "[CURRENT STATUS: %d]" % player_hp
print
else:
print no_understand
You have:
The simplest fix is to use:
raw_inputreturns a string. Why convert it to a number? Just test for text'1'and'2', etc. It also makes it easier to add character commands (like'q'for quit).