Python & Pokemon Game Mini
Step 1: Class Definition
Here, we define a Pokemon
class with an initializer (__init__
) to set up the initial attributes.
class Pokemon:
def __init__(self, name, primary_type, max_hp):
self.name = name
self.primary_type = primary_type
self.hp = max_hp
self.max_hp = max_hp
Step 2: String Representation Method
Next, we define the __str__
method to provide a string representation of the Pokemon object.
def __str__(self):
return f"{self.name} ({self.primary_type}: {self.hp}/{self.max_hp})"
Step 3: Putting It All Together
Here is the complete code for steps 1 and 2:
class Pokemon:
def __init__(self, name, primary_type, max_hp):
self.name = name
self.primary_type = primary_type
self.hp = max_hp
self.max_hp = max_hp
def __str__(self):
return f"{self.name} ({self.primary_type}: {self.hp}/{self.max_hp})"
# Test the class by creating two Pokemon instances and printing them
if __name__ == '__main__':
bulbasaur = Pokemon(name="bulbasaur", primary_type="grass", max_hp=45)
charmander = Pokemon(name="charmander", primary_type="fire", max_hp=39)
print(bulbasaur)
print(charmander)
Expected Output for Step 1 and Step 2
Running the above code will produce the following output:
bulbasaur (grass: 45/45)
charmander (fire: 39/39)
Battle : bulbasaur charmander
bulbasaur fought charmander and the result is a lost
bulbasaur is full.
charmander has now 40 Hp.
charmander has now 41 Hp.
his output shows the initial state of both Pokemon instances with their respective types and health points.