How to organize my code. Classes, functions, etc? [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm struggling to figure out how to organize things here.
I'm building a race game. There are players and race courses. Player have attributes like name, age, etc. Race courses also have a set of attributes, including difficulty. One thing I want to do is, when a player runs a course their energy level drops based on difficulty of the course. What I'm confused about is, because difficulty is an attribute of the course, and energy level is an attribute of the player, how can I affect the two?
Take the code for example...
class Player():
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
def run(self):
#code to run course here, reduces energy level when running course. Energy level is reduced based on player ability
class Course():
def __init__(self, name, difficulty)
self.name = name
self.difficulty = difficulty
player1 = Player("Bob", 90)
course1 = Course("Advanced Track", 15)
Maybe I am going about this all wrong? Does course need to be a class?
Thanks for any input.

How can I affect the two?
This you can achieve by passing an object of type Course to the run function like so:
class Player():
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
def run(self, course):
#use course.difficulty to reduce self.energy_level
class Course():
def __init__(self, name, difficulty)
self.name = name
self.difficulty = difficulty
player1 = Player("Bob", 90)
course1 = Course("Advanced Track", 15)
player1.run(course1) # this will pass course1 to the run function and run will reduce the energy level according to the difficulty of course1

You can make course a member of the player class
class Player():
course = null;
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
self.course1 = Course("Advanced Track", 15)
def run(self):
#code to run course here, reduces energy level when running course. Energy level is reduced based on player ability
#change self.energy based on self.course1.difficulty
Of course this is an oversimplification. You need to add methods to open new courses, and not hardcode this in the constructor.

Related

What is the best way to structure relationships stored across classes?

I am attempting to build a game environment in python that I can then utilize for a reinforcement learning application. To accomplish this, I see that applying an OOP approach will integrate best with common Reinforcement Learning methodologies. I am new to OOP, however, and have some questions regarding the class relationships. Here are my class definitions:
class Game:
def __init__(self, n_players, avg_hands_blinds, starting_chips, table_cnt, verbose):
self.n_players = n_players * table_cnt
self.starting_chips = starting_chips
self.table_cnt = table_cnt
self.tables = []
for table in range(self.table_cnt):
self.tables.append(Table(int(n_players/table_cnt)))
self.players = []
for i, player in enumerate(range(self.n_players)):
table_no = int(i/table_cnt)
self.players.append(Player(i, starting_chips, table_no))
def __repr__(self):
self.out_list = []
self.out_list.append(f'Number of players: {self.n_players}')
return self.out_list
class Tables:
def __init__(self, n_players):
self.n_players = n_players
self.table_hands = []
class Player:
def __init__(self, player_no, starting_chips, table_no):
self.player_no = player_no
self.table_no = table_no
self.chips = Chips(starting_chips)
def __repr__(self):
return f'player_no: {self.player_no} table_no: {self.table_no} chips: {self.chips}'
My question relates to how I should store information about the table assignments. For example, I have defined Player instances at the game level to facilitate awareness of their overall status in a game. During the game, players will need to be reassigned to different tables to re-balance tables as players are knocked out.
At the same time, each Table instance will need to have an "awareness" of which players are sitting at the table (to execute Hand instances, for example).
My question is this: how do I enable both transfer of players between tables and enable my Table instances to conduct operations on the relevant players?

(Classname) has no attribute (attribute)

I'm trying to create a DnD style dungeon crawler game. I'm using the 5E SRD and other publicly available information as the base for my characters and gameplay.
Currently I'm working on the character generator, and it seems to be going well, but I've hit a roadblock when trying to assign the racial bonuses. I've got the races set up as their own subclasses, each with it's unique bonuses. When I try to assign the appropriate bonuses based on the character's race I get a (Classname)has no attribute (attribute) error.
python
class Race:
def __init__(self, race):
self.name = race
self.racial_str_bonus = 0
self.racial_char_bonus = 0
class Dragonborn(Race):
def __init__(self):
super()
self.name = "Dragonborn"
self.racial_str_bonus = +2
self.racial_char_bonus = +1
def get_racial_bonus(race):
race = race
racial_str_bonus = 0
racial_char_bonus = 0
if race == "Dragonborn":
racial_str_bonus = Dragonborn.racial_str_bonus
racial_char_bonus = Dragonborn.racial_char_bonus
return racial_str_bonus, racial_char_bonus
class BaseCharacter:
def __init__(self, racial_str_bonus, racial_char_bonus):
self.racial_str_bonus = racial_str_bonus
self.racial_char_bonus = racial_char_bonus
#classmethod
def generate_player_character(cls):
cls.race = input("Race: ")
get_racial_bonus(cls.race)
BaseCharacter.generate_player_character()
What I'm looking for is something along the line of:
'''
Race: Dragonborn
print(my_player_char.racial_str_bonus)
2
'''
Where am I goofing up?
Thanks, everyone for the feedback. In cleaning up the code to get it minimally reproducible, I figured out the issue. Per Jonrsharpe's note, I corrected the inhertance invocation to 'super().init(self)'. Once that was correct, I realized that the way they had been defined, I had to include parentheses in the property call: "Dragonborn().racial_str_bonus".
Thanks again, and I will remember to improve my submissions in the future.

Python returning from class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
class Customer: #at this part ı defined the class for the customers in the file
def __init__(self, Name, Surname, Age, Balance):
self.name = Name;
self.sname = Surname;
self.age = Age;
self.balance = Balance;
def __str__(self):
return("Hello, "+str(self.name)+" "+str(self.sname)+" You have "+ str(self.balance)+" dollars in your account.");
Hello, you can see my class above
My aim - ask users name/surname and get the str part in the class.
I'm getting informations about customers from csv file.
ans = input("name")
ans2 = input("surname")
a = Customer(ans,ans2)
print(a)
With this part I've tried to do part that I explained above but I could'nt make the code work.
You have to define all the other attributes the class instance supposed to have that is Name, Surname, Age, Balance where you have only given Name and Surname. Python will also expect all other attributes you have given in __init__
Take this for example:
Age = input("age") #add these to take input too
Balance = input("balance") #add these to take input too
a = Customer(ans,ans2, Age, Balance)
Well, if your values sometimes supposed to be empty, make some values not necessary as in example:
class Customer:
def __init__(self, Name, Surname, Age=None, Balance=None): # specify the values which would be left as blank
self.name = Name;
self.sname = Surname;
self.age = Age;
self.balance = Balance;
# another code here
Then, if you pass only part of data to class constructor, you'll still get a working class instance without any errors:
>>> a = Customer('Name', 'Surname')
>>> a.Name
'Name'
>>> a.Surname
'Surname'
>>> a.Age
>>> # we got None here
Of course, you can use keyboard input too to enter the values, which is not provided by your csv data file by using the input() function.

Python Class Location Variables [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I wanted to decrease the players health but I was unsure if I was able to do this, sorry if this question is unclear but I am a new coder and am slowly get a grasp on how classes work. I think I need to make this more clear as I can.
class Health(object):
#health of player and enemy
#input of the both health so it is able to
#be a preset for more combat
def __init__(self, player, enemy):
self.player = player
self.enemy = enemy
class Attack_Type(object):
#making a attack type blueprint
#combat attacks can be modified
def melee(self, target):
#100% chance of landing hit
if target == player:
Health.player -= 1
return Health.player
elif target == enemy:
Health.enemy -= 1
return Health.enemy
test = Health(10,10)
enemy_melee = Attack_Type(Health.player)
My question is how do i access a variables value inside a class without making it global. Am i able to change the value of the class value within the class?
This Does Not change the players health because it can't access the players health but even when it does it does not return the value to the right place
I now to realise that it is much simpler to make the health a attribute, sorry everyone i do not fully understand how classes work! Thanks for all the help!
I hope this helps! :)
class Health:
def __init__(self): #Constructor initializing the variables.
self.player_health = 10
self.enemy_health = 10
class Combat:
#Attack function receives a health object called "hitter"
def attack(self, hitter):
hitter.player_health -= 1 #Health Object hitter's player_health reduced by one.
return hitter
bridge = Combat() #Combat Object
hitter = Health() #Health Object
bridge.attack(hitter) #hitter.player_health is now 9.
Here's one incarnation.
class Health:
def __init__(self):
self.player_health = 10
self.enemy_health = 10
class Combat:
def attack(self, health_obj):
health_obj += -1
return health_obj
bridge = Combat()
players = Health()
print(bridge.attack(players.player_health))

Total newbie... Need help understanding python classes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
My understanding of python is zero to none... Been exhausting myself reading what seems like a hundred different ways to approach this. Below I put the assignment description and my code... As of now I am having trouble using the 'getAnimal()' command. I'm not sure what it does or how it works. Thanks in advance :D
Assignment description: "Write a class definition for a class 'Zoo.' It should have instance variables for animal type, herbivore/carnivore/omnivore, and inside/outside. It should also have a getAnimal() method to show the animals information. Write a separate "ZooDriver" class to a) create three instances of zoo animals, b) get user input on which animal to view (1,2,3)c) show the animal info suing getAnimal()."
~~~~~~~~ My code:
class Zoo:
def __init__(self, animal, animal_type, habitat):
self.animal = animal
self.animal_type = animal_type
self.habitat = habitat
user_input=raw_input("Enter the number 1, 2, or 3 for information on an animal.")
if user_input == "1":
my_animal = Zoo("Giraffe", "herbivore", "outside")
elif user_input == "2":
my_animal = Zoo("Lion", "carnivore", "inside")
elif user_input == "3":
my_animal = Zoo("Bear", "omnivore", "inside")
print "Your animal is a %s, it is a %s, and has an %s habitat." % (my_animal.animal, my_animal.animal_type, my_animal.habitat)
A class defines a type of thing. An instance is one thing of that type. For example, you could say Building is a type of thing.
Let's start with a class named Building:
class Building():
pass
Now, to create an actual building -- an instance -- we call it almost like it was a function:
b1 = Building()
b2 = Building()
b3 = Building()
There, we just created three buildings. They are identical, which isn't very useful. Maybe we can give it a name when we create it, and store it in an instance variable. That requires creating a constructor that takes an argument. All class methods must also take self as its first argument, so our constructor will take two arguments:
class Building():
def __init__(self, name):
self.name = name
Now we can create three different buildings:
b1 = Building("firehouse")
b2 = Building("hospital")
b3 = Building("church")
If we want to create a "driver" class to create three buildings, we can do that pretty easily. If you want to set an instance variable or do some work when you create an instance, you can do that in a constructor. For example, this creates such a class that creates three buildings and stores them in an array:
class Town():
def __init__(self):
self.buildings = [
Building("firehouse"),
Building("hospital"),
Building("church")
]
We now can create a single object that creates three other objects. Hopefully that's enough to get you over the initial hurdle of understanding classes.
OK I will try to answer the main question here: What a class is.
From Google: class /klas/
noun: class; plural noun: classes
1.
a set or category of things having some property or attribute in common and
differentiated from others by kind, type, or quality.
In programming, a class is just that. say, for example you have class Dog. Dogs bark "ruf ruff".
We can define the dog class in python using just that information.
class Dog:
def bark(self):
print "ruf ruff"
To use the class, it is instantiated by calling () its constructor:
Spot = Dog()
We then want Spot to bark, so we call a method of the class:
Spot.bark()
To further explain the details of the code here would be to go outside of the scope of this question.
Further reading:
http://en.wikipedia.org/wiki/Instance_%28computer_science%29
http://en.wikipedia.org/wiki/Method_%28computer_programming%29
As a direct answer:
class Zoo(object):
def __init__(self, name="Python Zoo"):
self.name = name
self.animals = list()
def getAnimal(self,index):
index = index - 1 # account for zero-indexing
try:
print("Animal is {0.name}\n Diet: {0.diet}\n Habitat: {0.habitat}".format(
self.animals[index]))
except IndexError:
print("No animal at index {}".format(index+1))
def listAnimals(self,index):
for i,animal in enumerate(self.animals, start=1):
print("{i:>3}: {animal.name}".format(i=i,animal=animal))
class Animal(object):
def __init__(self, name=None, diet=None, habitat=None):
if any([attr is None for attr in [name,diet,habitat]]):
raise ValueError("Must supply values for all attributes")
self.name = name
self.diet = diet
self.habitat = habitat
class ZooDriver(object):
def __init__(self):
self.zoo = Zoo()
self.zoo.animals = [Animal(name="Giraffe", diet="Herbivore", habitat="Outside"),
Animal(name="Lion", diet="Carnivore", habitat="Inside"),
Animal(name="Bear", diet="Herbivore", habitat="Inside")]
def run(self):
while True:
print("1. List Animals")
print("2. Get information about an animal (by index)"
print("3. Quit")
input_correct = False
while not input_correct:
in_ = input(">> ")
if in_ in ['1','2','3']:
input_correct = True
{'1':self.zoo.listAnimals,
'2':lambda x: self.zoo.getAnimal(input("index #: ")),
'3': self.exit}[in_]()
else:
print("Incorrect input")
def exit(self):
return
if __name__ == "__main__":
ZooDriver().run()
I haven't actually run this code so some silly typos may have occurred and the usual "off-by-one" errors (oops), but I'm fairly confident in it. It displays a lot of concepts your instructor won't expect you to have mastered yet (such as string formatting, most likely, and almost certainly hash tables with lambdas). For that reason, I STRONGLY recommend you not copy this code to turn in.

Categories

Resources