Fruit arsenal

First, let's discuss how we could solve this in the Java way.

In Java, we would have created an interface, that abstracts the changes. In our case, what changes is our hero's weapon:

interface Weapon {
fun shoot(x: Int,
y: Int,
direction: Direction): Projectile
}

Then all other weapons would implement this interface:

class Peashooter : Weapon {
override fun shoot(x: Int,
y: Int,
direction: Direction) =
object : Projectile(x, y, direction) {
// Fly straight
}
}

class Pomegranate : Weapon {
override fun shoot(x: Int,
y: Int,
direction: Direction) =
object : Projectile(x, y, direction) {
// Explode when you hit first enemy
}
}

class Banana : Weapon {
override fun shoot(x: Int,
y: Int,
direction: Direction) =
object : Projectile(x, y, direction) {
// Return when you hit screen border
}
}

Then our hero would hold a reference to a weapon (Peashooter at the beginning):

private var currentWeapon : Weapon = Peashooter()

It would delegate the actual shooting process to it:

fun shoot(): Projectile = currentWeapon.shoot(x, y, direction)

What's left is the ability to equip another weapon:

fun equip(weapon: Weapon) {
currentWeapon = weapon
}

And that's what the Strategy design pattern is all about. Now, our algorithms (Maronic's weapons, in that case) are interchangeable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.122.68