Strategy

Remember Maronic, the platformer we were designing in Chapter 3Understanding Structural Patterns, while discussing the Facade design pattern?

Well, canary Michael, who acts as a game designer in our small indie game development company, came up with a great idea. What if we were to give our hero an arsenal of weapons to protect us from those horrible carnivorous snails?

Weapons all shoot projectiles (you don't want to get close to those dangerous snails) in the direction our hero is facing:

enum class Direction {
LEFT, RIGHT
}

All projectiles should have a pair of coordinates (our game is 2D, remember?) and a direction:

abstract class Projectile(private val x: Int,
private val y: Int,
private val direction: Direction)

If we were to shoot only one type of projectile, that would be simple, since we already covered the Factory pattern in Chapter 2, Working with Creational Patterns:

class OurHero {
private var direction = Direction.LEFT
private var x: Int = 42
private var y: Int = 173

fun shoot(): Projectile {
return object : Projectile(x, y, direction) {
// Draw and animate projectile here
}
}
}

But Michael wants our hero to have at least three different weapons:

  • Peashooter: Shoots small peas that fly straight. Our hero starts with it.
  • Pomegranate: Explodes when hitting an enemy, much like a grenade.
  • Banana: Returns like a boomerang when it reaches the end of the screen.

Come on, Michael, give us some slack! Can't you just stick with regular guns that all work the same?!

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

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