Reputation: 25
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
Upvotes: 1
Views: 147
Reputation: 4903
I've answered a similar question https://stackoverflow.com/a/14644220/1481060 and suggested using the standard module cmd
that handles these sorts of command-loops.
It should give you the ability to add verbs like kill, look etc...to your game.
--
You may also want to model your Game as Objects so that you don't keep too many variables around as I can imagine that when something gets hit
the health goes down as does the damage and stamina etc etc.
Upvotes: 0
Reputation: 11925
There are a few ways to handle this.
I think a simple solution would be with an exception.
try:
choice = int(choice)
except:
choice = None
It just tries to cast the choice
into an int type. If it fails, the except block is run, and sets choice to None, so the if/elif blocks will not run.
OK, not the simplest, @jimhark has a simpler approach.
It seems in this case, there is little value in converting the input to an integer.
Upvotes: 0
Reputation: 5046
You have:
choice = raw_input("*>>*")
choice = int(choice)
# . . .
if choice == 1:
# . . .
elif choice == 2:
The simplest fix is to use:
choice = raw_input("*>>*")
# . . .
if choice == '1':
# . . .
elif choice == '2':
raw_input
returns 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).
Upvotes: 1