[Python] While loop going infinitely because of a class method that returns wrong values -...

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm just playing around with python concepts such as while loops, classes, methods and return values. The thing is, to make it "more attractive" I'm doing it with a class that's named Pokemon().

    The code looks like this:

    import random

    class Pokemon():
    def __init__(self): #Pokemon attributes
    self.health = 100
    self.damage = 5
    self.__lives = 3 #? //Not used

    def checkalive(self, opponent): #Check if the pokemon's still alive, args: the pokemon and the opponent
    while self.health and opponent.health > 0:
    return True #If both of them alive, return true
    break

    return False #If neither of them alive, return false

    def attack(self, opponent): #Attack function, args: the pokemon and the opponent

    while True:
    check = self.checkalive(opponent) #Check if the pokemons are alive
    while check == True: #In case it returns True go on with the combat
    randomNumber = random.randint(0,5) #Just creating a random number
    if randomNumber == 3: #If that random number equals to 3 (20%) the opponent will defend itself and will counterattack our Pokemon
    self.health -= opponent.damage
    print("Got it wrong! You've got " + str(self.health) + " HP remaining.")

    else: #If not (80%), just go on with the combat
    opponent.health -= self.damage
    print("The opponent now has " + str(opponent.health) + " HP! Your pokemon still has got " + str(self.health) + " HP left.")


    print("End of combat") #Once one of them is dead, end of combat
    break


    Squirtle = Pokemon() #Our pokemon
    Pikachu = Pokemon() #Opponent
    Squirtle.attack(Pikachu)


    I've created two very basic methods. One is checkalive(), just as its name says it just makes sure if the Pokemons involved in a combat are still alive, returning True or False values.

    The other one is attack(), that basically just hurts the Ally Pokemon/Opponent Pokemon depending on a probability of 80%/20%. It is a really simple code and before implementing the checkalive() function it worked perfectly. However, now the while runs an indeterminately amount of times, going below negative health values. I tried to figure what's going on, tried to change the "While" for an "If" condition statement and etc, but still no clue. Any suggestion would be really appreciated.

    [​IMG]

    Continue reading...

Compartilhe esta Página