Handle Invalid Input
So, first little fix is to just remove these two calls to
print() and clean out the text input a little bit more. But there’s also a bigger issue in this code. I’m going to run it, and then you might have noticed that as well.
00:51 So far, attacking works, healing works, and running works too. I’m not going to do it right now, but the problem is that if I enter anything else than the selected options, the game doesn’t quite work as expected.
01:06 What happens is the monster still gets a chance to attack me, but I can’t do anything. I don’t heal, I don’t attack, and I don’t really run away either. So I’m kind of stuck in this position where I keep getting beat up by a monster without being able to do anything about it. Help!
01:25 And there is no way to get out of this. So there’s a little bug in here, right? And it’s a bit subtle because the game keeps going. So, you might not even notice it right away, like I didn’t notice it up to taking a break.
What we forgot to add here is to handle other inputs than the expected ones, and we did set up the structure for that. So I have this
elif structure, and I think we even talked about then adding an
else clause later on that would just catch the rest, anything that isn’t unexpected output, but we didn’t implement it. Let’s go ahead and do this now.
Please choose A, H, or R." So I’m telling them this is not going to work by saying there’s an invalid action and then also giving them a way out. Instead, they should press
02:36 I also need to prevent the monster from attacking because, well, maybe you want a hard version of the game where if the user inputs an invalid character, the monster still gets to attack. But in this case, I want to make it a little more user-friendly, I guess, or just easy mode.
I’m going to use the other looping keyword,
continue, underneath here, which means that if this
else clause catches, the
continue statement is going to bring us back to the beginning of the
while loop, which means the user has another chance to input a character.
So in that case, if the user inputs anything except
R, they’re going to get a useful message and get redirected back to the beginning of the loop, where they have another chance. Let’s try that out.
Become a Member to join the conversation.