In Python, it is generally the case that functions need to come before the code that uses them in a file.
At the top of your code, after the import statements, add the following code:
def fight():
global player_strength
global ogre_strength
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()
This is our function. You can see it starts with a declaration line:
def fight():
def
defines the
function. fight
is its name. We'll come to the parentheses "()" shortly. The colon ":" starts a
block - all the code indented after it is inside the function, just as with if-statements and loops.
You'll also notice the following lines:
global player_strength
global ogre_strength
You can see they mention the two variables we set up earlier. Variables in Python have scope, that is, areas where they are alive and can be used. Any variables made inside a function only exist within that function. A side effect of this is if we do:
player_strength = player_strength - 1
inside the function, that makes us an entirely new variable with the same name, but completely different
to the player_strength outside the function. To make sure the version inside the function is the one
created outside, we use the global
keyword.
Now we need to get our code to run!
[Home > Part 3 > Next]