println("Squirtle's health has been restored by $amount x2 points with a Super Potion.")
}
}
// Restore health to the Pokémon
restoreHealth(charmander, 20)
val superPotion = WaterHealItem()
superPotion.restoreHealth(squirtle, 10)
}
In this example, we have created a base class Pokemon and two subclasses FirePokemon and WaterPokemon that inherit from Pokemon. We have also demonstrated polymorphism by calling the attack method on each
Now some enhancements:
import kotlin.random.Random
open class Pokemon(val name: String, val type: String, val attacks: Array<String>) {
var healthPoints = 100
// Method Overloading - multiple methods with the same name but different parameters
fun attack(pokemon: Pokemon) {
val attackIndex = Random.nextInt(attacks.size)
attack(pokemon, attackIndex)
}
fun attack(pokemon: Pokemon, attackIndex: Int) {
val attack = attacks[attackIndex]
val damage = (0..50).random()
pokemon.healthPoints -= damage
println("$name used $attack and dealt $damage damage to ${pokemon.name}")
val pokemonAttacks = arrayOf(attacks.random(), attacks.random())
return when (type) {
"Electric" -> Pikachu(name, type, pokemonAttacks)
else -> Pokemon(name, type, pokemonAttacks)
}
}
fun play() {
for (i in 1..10) {
val pokemon1 = generatePokemon()
val pokemon2 = generatePokemon()
println("${pokemon1.name} (${pokemon1.type}) vs ${pokemon2.name} (${pokemon2.type})")
while (pokemon1.isAlive() && pokemon2.isAlive()) {
pokemon1.attack(pokemon2)
if (pokemon2.isAlive()) {
pokemon2.attack(pokemon1)
}
}
if (pokemon1.isAlive()) {
println("${pokemon1.name} wins!")
} else {
println("${pokemon2.name} wins!")
}
println()
}
}
}
fun main() {
val game = Game()
game.play()
}
In this example, we have created an array attacks of 10 different attacks. We then created a trainer array of Pokémon and an opponent array of Pokémon, each with a random attack from the attacks array. The random selection was achieved by using the nextInt() method from the Random class. Finally, we demonstrated that each Pokémon has a random attack from the array by printing their names and attacks.
The attack method in the Pokemon class is overloaded with a second version that takes an attackIndex parameter. This allows the player to specify which attack to use.
The isAlive method in the Pokemon class is marked as open. This allows the method to be overridden by subclasses.
The Pikachu class is a subclass of Pokemon that overrides the isAlive method. Pikachu is stronger than other Pokemon, so it can survive with fewer health points.
The generatePokemon method in the Game class now returns a Pokemon or a Pikachu, depending on the type of Pokemon generated.
The play method in the Game class now uses the attack method without an attackIndex parameter, which will use a random attack.
The main function is unchanged.
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (