Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Create a Game Loop

00:00 We just introduced the run away option, but it doesn’t really make a lot of sense so far because the script just runs once and finishes after either selection, like "A", "H", or "R".

00:11 I want to change this now by introducing a game loop, and the game loop can often be an infinite loop with a certain break condition. You’ve done those before, so let’s try that out. I want to continue asking for input from the user until—let’s see the conditions—the game continues until the health of either the player or the monster reaches 0 or until the player decides to run away.

00:31 Here we have the first option to end the game loop. So let’s introduce the game loop. I’m going to say while True:

00:38 and then I need to indent all of this. Whoop.

00:44 I guess it’s easier probably if I do this. No. All right, it doesn’t let me do that, so I will just go line by line.

00:54 Now I have an infinite game loop here that keeps asking for an action from the user, prints out the action, and then does things, like either it reduces the health of the monster, or it heals the player’s health, or it allows us to run away.

01:09 But now we have the task that if the player runs away, the game should end. So this is an option for us to break out of the loop. So here I’m going to add the break keyword, which means we now also have a way to get out of this infinite loop.

01:21 If you don’t have this break keyword, this would just keep asking you to input something, but there’s not really a way to get out. Let’s try it out.

01:30 Save. Now we’re in here. Okay, now I’m going to start by healing. Doesn’t do anything for me. I’ll attack the monster. I can reduce the monster’s health, and it keeps asking me for new input. So that’s great.

01:42 And if I press r for run away, then the game actually ends and we’re back to the prompt. Cool. That means we’ve successfully introduced the game loop and also a way to get out of it.

Become a Member to join the conversation.