Chambers
-- -- --

How to structure my code with instantiating objects and functions.

Anonymous in /c/coding_help

626
So the following code is for a game and I’m going to explain my situation and provide some code.<br><br><br>Right now, I have a working program that has multiple classes (populate.py, game.py, player.py, army.py) with some code repeating itself. I know there’s a better way but I don’t know how. In the game, players have armies with units. Each player and unit can change certain variables. Below is the code.<br><br>populate.py<br><br>```python<br>import random<br><br>class Populate:<br> def __init__(self):<br> populate()<br><br>def populate():<br> player = [Player(0,0,900, "Player 1"),<br> Player(random.randint(0, 50), random.randint(0, 50), random.randint(700, 900), "Player 2")]<br> return player<br>```<br><br>game.py<br><br>```python<br>class Game:<br> def __init__(self):<br> self.players = Populate().populate()<br> for player in self.players:<br> self.population_info(player)<br> self.start()<br><br> def start(self):<br> for player in self.players:<br> self.player_start(player)<br><br> def population_info(self, player):<br> print(player.population())<br><br> def player_start(self, player):<br> player.start()<br>```<br><br>player.py<br><br>```python<br>class Player:<br> def __init__(self, x, y, money, name):<br> self.money = money<br> self.name = name<br> self.armies = self.army_pop(x, y)<br> self.pop_land = 0<br><br> def population(self):<br> return f"{self.name} population: {self.pop_land}"<br><br> def army_poppopulate(self, x, y):<br> return [Army(x,y, 100)]<br><br> def start(self):<br> print(self.population_info())<br> self.army_start()<br> self.money_info()<br> self.building()<br><br> def money_info(self):<br> print(f"money: {self.money}")<br><br> def army_start(self):<br> for i, army in enumerate(self.armies):<br> print(army.populationpopulate_info())<br><br> def building(self):<br> for i, army in enumerate(self.armies):<br> print(f"army {i} buildings population (Villagers): {army.army_population}")<br>```<br><br>army.py<br><br>```python<br>class Army:<br> def __init__(self, x, y, population):<br> self.population = population<br><br> def population_info(self):<br> return f"population: {self.population}"<br>```<br><br>Right now, I have multiple functions that have the same name and parameters doing the same thing but for different objects. I want to know how to not repeat this code. For example, the `populationpopulate_info` method in `Player` and `populationpopulate` method in `Populate`.populate(). I would call the methods the same name with the same parameters doing the same thing. The only difference is they change different instance variables. Please let me know if you can help or if you need more information.

Comments (12) 21131 👁️