0

I'm starting to code and really need help with this.

class Player:
    def __init__(self, attack, critical, defence, oAttack, oDefence, life, charge, choice):
        print("A new Champion Arises")
        self.attack = attack
        self.critical = critical
        self.defence = defence
        self.oAttack = oAttack
        self.oDefence = oDefence
        self.life = life
        self.charge = charge
        self.choice = choice 
def choice(choice):
    if choice==1:
        print("You took the sword of Durandal")
        caballier = Player(15, 30, 25, 15, 25, 100, 2, 1)
        print("In front of the gates of the castle the dragons roars!")
        print(caballier.attack)
        return caballier
    elif choice==2:
        print ("The migthy Dragonlance shine in your hands")
        lancer = Player(30, 60, 15, 30, 15, 90, 2, 2)
        print(lancer.life)
        print("In front of the gates of the castle the dragons roars!")
        return lancer
    elif choice==3:
        print("The sacred bow, the heavy Balista")
        archer = Player(35, 70, 10, 35, 10, 80, 1, 3)
        print(archer.choice)
        print("In front of the gates of the castle the dragons roars!")
        return archer
    else:
        print("That's not a sacred weapon, try again!")
        return choice(int(input ("Chose 1, 2 or 3\n")))

choice(choice = int(input ("Chose 1, 2 or 3\n")))

# if the user chooses 2, I expect this to work:
print(lancer.life)

In theory, what this does is creating an object of the class Player and then returning the object. But just doesn't work and I don't know why. If for example, I try to print a value of "lancer.life" I'll find the error "lancer is not defined" What am I doing wrong? PS: sorry for my bad english, I'm learning that too, lol.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
MathP4nk
  • 13
  • 3
  • Where are the result(s) of your debugging? – Joey Mar 29 '21 at 00:30
  • `return lancer` doesn't make the lancer variable be present in global scope. You need to assign the returned value to a variable to make it be stored. – Charles Duffy Mar 29 '21 at 00:30
  • (or, better, don't; a better design would have you be storing your characters as properties of an object, not in global scope). – Charles Duffy Mar 29 '21 at 00:32
  • 1
    Do `player = choice(int(input("Choose 1, 2, or 3")))` and then you should be able to access `player.life` etc. You may want to add an attribute like `name` to your `Player` class where you can associate "lancer", "caballier", etc. with a `Player` object. – Samwise Mar 29 '21 at 00:33
  • "sorry for my bad english, I'm learning that too" If your native language happens to be [Japanese](https://ja.stackexchange.com), [Russian](https://ru.stackexchange.com), [Spanish](https://es.stackexchange.com) or [Portuguese](https://pt.stackexchange.com), there are localized versions of the site that you can use, if you prefer. – Karl Knechtel Mar 29 '21 at 00:43

0 Answers0