Noob Needs Help

Started by
1 comment, last by Low_Man 11 years, 9 months ago
Hello!

I'd like to prefice this by saying that I've only been learning Python 3 for a couple days now and really don't have a clue what I'm doing.

Anyway, the idea here is to have a turn based combat system. There's function that plays through to the end and then loops back to the beginning until someone has 0HP or less. The problem I'm having is that everytime it loops it resets the players health and the enemies health. I know why, it's because I declare the variable at the start of the function.

So what I'd like to know is how do I change the value of the variables "EnemyWHP" and "PlayerWHP"? So, after "EnemyWHP = EnemyWHP - Dice" how do I put whatever value that comes up with, into the "EnemyWHP" variable at the start of the program so that when it loops again, it shows the correct value?

Here's the relevant chunk of code:

[spoiler][source lang="python"]def Combat():

EnemyWHP = '20'
PlayerWHP = '20'
print('\nWhich part of the enemy ship will you target?')
Target = ''
Target = input()
print()

while Target == '3' and EnemyWHP >= '1':
Dice = '0'
Dice = int(Dice)
EnemyWHP = int(EnemyWHP)
PlayerWHP = int(PlayerWHP)

print('You have chosen to target their weapon systems')
time.sleep(2)
print('Your weapons are locked on and preparing to fire')
time.sleep(2)
print('You have fired at their weapon systems and...')
time.sleep(2)
Dice = random.randint(1,3)
Dice = str(Dice)
print('\nYou did ' + Dice + ' damage.')
Dice = int(Dice)
EnemyWHP = EnemyWHP - Dice
EnemyWHP = str(EnemyWHP)
print('The enemy now has ' + EnemyWHP + ' hitpoints left.\n')

print('The enemy ship has charged its weapons')
time.sleep(2)
print('They are locking on.')
time.sleep(2)
print('They fire and...')
time.sleep(2)
Dice = random.randint(1,3)
Dice = str(Dice)
print('\nYou have taken ' + Dice + ' points of damage.')
Dice = int(Dice)
PlayerWHP = PlayerWHP - Dice
PlayerWHP = str(PlayerWHP)
print('You now have ' + PlayerWHP + ' Hitpoints left.\n')

Combat()[/source][/spoiler]
Advertisement
Since EnemyWHP and PlayerWHP are created in the function, they only last the lifetime of that function, and are recreated the next time the function is called (They are "local" to that function). You could make EnemyWHP and PlayerWHP "global" variables by defining them outside of the function, and then when you first use them in the function, declare the variables as global.

EnemyWHP = 20
PlayerWHP = 20

def Combat():
global EnemyWHP //Re-aquire 'EnemyWHP' (so we don't accidentally create a new one with the exact same name).
global PlayerWHP

EnemyWHP = EnemyWHP - 1
Awesome! Thanks, it works perfectly now.

This topic is closed to new replies.

Advertisement