Today, we will discuss how to make a simple Pokémon game in Python.
First, let us understand how Pokémon works:
For each Pokémon, there are three properties: health, attack, and defense.
Health is the current health status for the Pokémon,
Attack is the amount of damage the Pokémon can do to its opponent,
and Defense is the amount of damage the Pokémon can handle from its opponent.
We will use the following formula for calculating attack damage:
Where r is a random value between 0.85 and 1 inclusive.
Once the value is calculated, we subtract it from the health of the other Pokémon.
Now let us start programming this game.
We start by importing the random library. This will allow us to pick a random value from 0.85 to 1.
We then create a class Pokémon that will be the basis of our Pokémon characters:
The next step is to create the __init__ constructor and override the __str__ function to make it print the current properties of the Pokémon:
After this, we would like to create the attack function. To help us, we will also create a helper function called calculate_damage():
Notice that we use a list choices to randomly choose a number between 0.85 and 1 inclusive.
Also notice that we split the entire formula into steps and store them in variables partA, partB, partAB, r, and partC. This is to show each step of the process.
We then create the function attack(otherPkm), which takes in the object of the other Pokémon. Here, we subtract the damage, which calculated from the previous function, from the other Pokémon's health, and then output how much damage was done. We also check if the other Pokémon's health is less or at zero. If so, we declare that the other Pokémon has fainted.
The otherPkm.health=0 is to reset the health to zero if the health happened to be less than zero.
All right, we are done with the program. Here is the class that we made as well as some objects at the bottom:
If we run this, we get the following output:
To attack a Pokémon, we use the following syntax:
thisPokemon.attack(otherPokemon)
In this example, there are two objects, p and b, that we can use. Here is an example:
You may have noticed that the last function call had the p object attack itself! This is not what we want. As a challenge, try resolving this issue:
Challenge: As we can see, the function allow a Pokémon to attack itself. Modify the program such that the function prevents the user from doing such a thing.
If you would like another challenge:
Challenge 2: Modify the program such that the user is asked how many Pokémon should it make, whose Pokémon's turn is it, and what Pokémon should it attack. In other words, make the entire program dynamic.