Python Forum
Best Practice to Pass a Variable Between Two Classes?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Best Practice to Pass a Variable Between Two Classes?
#1
Hey every body,

I got motivated the other day and started working on a long time project of mine. I've always wanted to code my very own Dungeons and Dragons Auto Dice Roller. SO, this is my latest attempt. I'm just a noob so be nice:) I wanted to figure out how to pass a variable between classes. I thought this would be a fun way to do that. Please feel free to tear it apart or point out any optimizations or better practices. Please advise with any : thoughts, concerns, etc..

import random

def wrapper():
    print("=" * 60)
    print("=" * 60)
def logo():
    print("*" * 60)
    print("MIPYTHON.com | Dungeons and Dragons Random Combat Bot")
    print("*" * 60)


class character(object):

     def __init__(self,name,intro,initiative,movement,attack,defense,damage,hitpoints):
        self.name = name
        self.intro = intro
        self.initiative = initiative
        self.movement = movement
        self.attack = attack
        self.defense = defense
        self.damage = damage
        self.hitpoints = hitpoints



     def main(self):

        pass

     def initiative_roll(self):
        space = "  "
        self.initiative = self.initiative + random.randint(1,10)
        print(self.name + space + "Initative Roll:")
        print("Rolls: % for Initiative") % self.initiative
        return self.initiative

     def move_roll(self):
        space = "  "
        self.movement = (self.movement) + random.randint(1,10)
        print(self.name + space + "Move Roll:")
        print(self.name + "Rolls: " + space + str(self.movement))
        #print(self.movement) #% self.movement
        #return str(self.name) + " Moves :  "
        return self.movement

     def attack_roll(self):

        space = "  "
        self.attack = self.attack + random.randint(1,99)
        #print("\n Rolls a % To Attack!") % int(self.attack) + random.randint(0,10)
        #return int(self.attack) + random.randint(0,10)
        #print(self.name + "Moves : " + self.movement )
        #print(self.name + "Rolls For Attack:")
        print(self.name + space + "Attack Roll:")
        print(self.name)
        print("Rolls: %" + space + " for Attack") % self.attack
        return self.attack

     def defense_roll(self):
        space = "  "
        self.defense = self.defense + random.randint(1,99)
        print(self.name + space + "Defense Roll:")
        print(self.name)
        print("Rolls: % for Defense") % self.defense
        #print(self.defense)
        return self.defense

     def damage_roll(self):
        return self.damage

class roll_system(object):

     def __init__(self):
        pass
        #self.combat_resolving = combat_resolving
        #self.wound_handeling = wound_handeling

     def main(self):
        pass

     def combat_system(self):
        #print(wrapper())
        print(logo())
        #print(wrapper())
        if player.initiative_roll() >= enemy.initiative_roll():

           #player.attack_roll()  METHOD FROM CHARACTER CLASS
           #enemy.defense_roll()  METHOD FROM CHARACTER CLASS

           if player.attack_roll() >= enemy.defense_roll():
               #print(wrapper())
               print("Player hits Enemy For: ")
               print(player.damage_roll())
               print(enemy.name)
               #print(enemy.hitpoints - player.damage_roll())
               enemy_damage_taken = enemy.hitpoints - player.damage_roll()
               print(enemy_damage_taken)
               return enemy_damage_taken
               #return  enemy.hitpoints - player.damage_roll()
           else:
               print("Player misses Enemy")

        else:
           #enemy.attack_roll()
           #player.defense_roll()

           if enemy.attack_roll() >= player.defense_roll():
               #print(wrapper())
               print("Enemy hits Player For:")
               print(enemy.damage_roll())
               print(player.name)
               #print(player.hitpoints - enemy.damage_roll())
               player_damage_taken = player.hitpoints - enemy.damage_roll()
               print(player_damage_taken)
               return player_damage_taken
               #return player.hitpoints - enemy.damage_roll()

           else:
               print("Enemy Misses Player")

###  INSTANTIATE CHARACTER CLASSES
###  name,intro,initiative,movement,attack,defense,damage,hitpoints BONUSES
player = character("Player","Player Intro",3,5,3,3,random.randint(1,10),30)
enemy = character("Enemy","Enemy Intro",3,5,3,3,random.randint(1,10),30)


###   INSTANTIATE ROLL_SYSTEM CLASS TO HANDLE RANDOM ROLLS
#combat = roll_system((player.attack_roll(),enemy.attack_roll()),())
combat = roll_system()
combat.combat_system()
### RUNS TWICE
combat.combat_system()


"""run = True
while run == True:
    #combat.combat_system()
    combat = input("Combat Y or N ?>>>")
    combat.combat_system()
    if combat == "N":
        run = False
    else:
        combat.combat_system()"""


"""while player.hitpoints >= 0 :
    combat.combat_system()
    go_again = input("Continue Y or N?>>> ")

    if go_again == "Y" or go_again == "y":
        combat.combat_system()
    else:
        print("YOU ARE DEAD")
else:
    print("You are Dead")"""

#print(player.intro)
#print(enemy.intro)
#player.initiative_roll()
#player.move_roll()
#player.attack_roll()
#player.defense_roll()

#player.initiative_roll()
#enemy.initiative_roll()
#player.initiative_roll()
#enemy.initiative_roll()



#print(player.move())
#print(player.movement)

#if __name__ == '__main__':
    # main()
Reply
#2
Can you reproduce your question with <20 lines of code? Ideally <10.
Reply
#3
I looked at regular expressions but I don't really understand it yet. From the books I've read. They all seem say to keep the variables as descriptive as possible. It helps me at least to remember what the script is supposed to do lol.
Reply
#4
Quote:
        print("Rolls: % for Defense") % self.defense

You use that several times. What is it supposed to do? None % int should be throwing errors.
Reply
#5
I think maybe that is an old concatenation method from python 2? IIRC that was how Zed shaw taught it in "Learn Python the Hard Way", that was the python 2.X version though. It seems to be valid. Probably not best practice. You can see how I was butchering some of those print statements lol.

I also noticed that my rolls are adding themselves together rather then re rolling.
Reply
#6
What version python are you using? It gives me an error when I use it on 3.6...
>>> val = "spam"
>>> print("and your little % too") % val
and your little % too
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'
Reply
#7
My bad I forgot the s after the % . I was a little rusty :)
print("Rolls: %s for Defense") % self.defense
Apparently it works in Ninja IDe running Python 2.7 without the s after the %.
Reply
#8
(Apr-10-2018, 01:41 PM)MIPython Wrote: Apparently it works in Ninja IDe running Python 2.7
That would only work in python 2.x. In 3.x, formatting using the mod operator was removed completely.
Reply
#9
(Apr-09-2018, 01:35 PM)MIPython Wrote: I looked at regular expressions but I don't really understand it yet. From the books I've read. They all seem say to keep the variables as descriptive as possible. It helps me at least to remember what the script is supposed to do lol.

I don't see what RegEx has to do with micseydel's suggestion to reduce the amount of code needed to illustrate your question. At least the one in the title, because you extend it in the post afterwards asking for general comments and feedback. No one ask you to NOT use descriptive names. But for start you may remove all commented code.
As for the script/style
- see PEP8, e.g. class names should be Capitalized.
- remove things like
     def main(self):
 
        pass
 def __init__(self):
        pass
- remove things like space = " " and later yse. Instead use proper formatting, e.g. .format or 3.6+ f-strings
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
(Apr-11-2018, 07:46 AM)buran Wrote:
(Apr-09-2018, 01:35 PM)MIPython Wrote: I looked at regular expressions but I don't really understand it yet. From the books I've read. They all seem say to keep the variables as descriptive as possible. It helps me at least to remember what the script is supposed to do lol.

I don't see what RegEx has to do with micseydel's suggestion to reduce the amount of code needed to illustrate your question. At least the one in the title, because you extend it in the post afterwards asking for general comments and feedback. No one ask you to NOT use descriptive names. But for start you may remove all commented code.
As for the script/style
- see PEP8, e.g. class names should be Capitalized.
- remove things like
     def main(self):
 
        pass
 def __init__(self):
        pass
- remove things like space = " " and later yse. Instead use proper formatting, e.g. .format or 3.6+ f-strings

Good points I forgot how to add a "space" in a simple way. All the data prints bunched together.

Quote:I don't see what RegEx has to do with micseydel's suggestion to reduce the amount of code needed to illustrate your question. At least the one in the title, because you extend it in the post afterwards asking for general comments

Yeah just realized I should have shortened the code for simplicity sake. That first comment went over my head for a minute, sry...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Morse Code Practice Script sparkz_alot 14 8,489 Feb-06-2018, 02:03 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020