vendredi 24 juin 2016

How to increment a variable contained within a class in python from outside of its class?


I have a fairly simple python question, as I am pretty new to the language. I started writing a quick program just for practice, but have now become frustrated because I cannot get it to work. import random import sys class Meta: turncounter = 1 class Enemy: life = 10 wis = 1 str = 3 def heal(self): healscore = self.wis + random.randrange(1, 7, 1) self.life += healscore print "Enemy healed for " + str(healscore) + ".n" self.checklife() Meta.turncounter += 1 def attack(self, player): damage = self.str + random.randrange(1, 5, 1) player.life -= damage print "You took " + str(damage) + " damage.n" Player.checklife(player) Meta.turncounter += 1 def checklife(self): if self.life <= 0: print "The enemy is dead.n" sys.exit(0) else: print "Enemy's HP: " + str(self.life) + ".n" class Player: life = 50 wis = 3 str = 5 def heal(self): healscore = self.wis + random.randrange(1, 7, 1) self.life += healscore print "You healed for " + str(healscore) + ".n" Meta.turncounter += 1 def attack(self, enemy): damage = self.str + random.randrange(1, 5, 1) enemy.life -= damage print "You did " + str(damage) + " damage.n" Enemy.checklife(enemy) Meta.turncounter += 1 def checklife(self): if self.life <= 0: sys.exit("You died!") else: print "HP: " + str(self.life) + ".n" paladin = Player() hollow = Enemy() turnmeta = Meta.turncounter % 2 move = random.randrange(1, 3, 1) print turnmeta print move while turnmeta == 0: if move == 1 and paladin.life <= 10: paladin.heal() print turnmeta elif move != 0 or (move == 1 and hollow.life > 15): paladin.attack(hollow) print turnmeta while turnmeta > 0: if move == 1 and hollow.life <= 15: print turnmeta elif move != 0 or (move == 1 and hollow.life > 15): hollow.attack(paladin) print turnmeta As you can see, this program isn't particularly complex; it is just meant to be something to generally understand python syntax and loops and such. For some reason, whenever I run the program, instead of the turncounter incrementing and the paladin / hollow having a back and forth, the turncounter stays locked in at 1, causing the hollow to attack until the paladin dies, instantly ending the program.

Aucun commentaire:

Enregistrer un commentaire