So, at the moment, we fight our ogre and win or loose one strength. But what if it is a fight to the death? Ogres don't usually just walk away. Firstly, we could do with giving our ogre something to lose - i.e. some player_strength of its own. Then we could do with repeating the fight until either the player or ogre is dead.
Adjust the code to look like this:
decision = input("You come to a junction. Turn left or right [L,R]: ")
if decision == "L" or decision == "l":
print("You turn left and see a terrible ogre!")
ogre_strength = 2
while player_strength > 0 and ogre_strength > 0:
print("You FIGHT!")
print("SMASH!")
time.sleep(500)
print("BASH!")
time.sleep(500)
print("Oo!")
time.sleep(500)
random_number = random.randint(10)
if player_strength > random_number:
print("You won! Gain one strength!")
player_strength = player_strength + 1
ogre_strength = ogre_strength - 1
else:
print("You lost! Lose one strength!")
player_strength = player_strength - 1
ogre_strength = ogre_strength + 1
if player_strength < 1:
print("Oh no! You died!")
sys.exit()
Two things have changed here. Hopefully you can spot that we've now given the ogre some strength to lose. The other thing that is going on is a while-loop.
Loops allow you to repeat code. While-loops let you repeat code all the time some condition is true. In this sense, they're a bit like an if-statement, but what they decide is whether to repeat. You build them like this:
while condition == true:
do something in a block.
when it is not true, carry on
Look at the code above - can you see how it continues the fight until one or other person is dead? Why do we set the ogre_strength before the loop rather than inside it? Try adding the changes to your code and see how it runs.
[Home > Part 2 > Next]