Work is coming along nicely. I’ve been mainly focused on the hud, which is of importance to testing the power-ups. I’ve also implemented some power-ups.

Bomberman Hud

The hud is displayed on the left side and shows player information like health, lives, score and power-ups.

In this post I want to explain how I further Swiftified the source code, this time by adopting a more functional style of programming.

When the timer expires, the monsters enrage. At this moment the enrage is just a movement speed increase on the monsters.

The original code for enraging monsters looked like the following:

private func enrageMonsters() {
    for creature in self.creatures {
        if creature is Monster {
            if let visualComponent = creature.componentForClass(VisualComponent) {
                visualComponent.spriteNode.speed *= 1.6
            }
        }
    }
}

To Swiftify the source code, we can use the filter and forEach functions when processing collections:

private func enrageMonsters() {
    self.creatures
        .filter({ $0 is Monster })
        .forEach({
            if let visualComponent = $0.componentForClass(VisualComponent) {
                visualComponent.spriteNode.speed *= 1.6
            }
        })
}

Another situation where I adopted this functional style would be when activating power-ups. Initially the code looked like this:

func activate(forPlayer player: Player) {
    if self.activated == false {
        self.activated = true
        
        switch self.power {
            ...
        case .DestroyBlocks:                
            if let tiles = self.game?.tiles {
                for tile in tiles {
                    tile.destroy()
                }
            }
        case .DestroyMonsters:
            if let creatures = self.game?.creatures {
                for creature in creatures {
                    if creature is Monster {
                        creature.destroy()
                    }
                }
            }
        default: break
        }
    }
}

The functional approach is as follows:

func activate(forPlayer player: Player) {
    if self.activated == false {
        self.activated = true
        
        switch self.power {
            ...
        case .DestroyBlocks:
            self.game?.tiles.forEach({
                $0.destroy()
            })
        case .DestroyMonsters:
            self.game?.creatures
                .filter({ $0 is Monster })
                .forEach({ $0.destroy() })
        default: break
        }
    }
}

It’s certainly more concise and I can appreciate that.

At the moment I wonder what the benefits and downsides of this approach are. The Swiftified code might be slightly harder to debug, as breakpoints might not work as well. I do think the Swiftified source code is nicer to read though.