NEW: Master Swift design patterns with my latest book! >>

< Previous: Slice to win   Next: Wrap up >

Game over, man: SKTexture

You are now within reach of the end of this project, and not a moment too soon, I suspect. You'll be pleased to know that you're just two methods away from the end, and neither of them are particularly taxing.

First is the subtractLife() method, which is called when a penguin falls off the screen without being sliced. It needs to subtract 1 from the lives property that we created what seems like years ago, update the images in the livesImages array so that the correct number are crossed off, then end the game if the player is out of lives.

To make it a bit clearer that something bad has happened, we're also going to add playing a sound and animate the life being lost – we'll set the X and Y scale of the life being lost to 1.3, then animate it back down to 1.0.

Here's the code:

func subtractLife() {
    lives -= 1

    run(SKAction.playSoundFileNamed("wrong.caf", waitForCompletion: false))

    var life: SKSpriteNode

    if lives == 2 {
        life = livesImages[0]
    } else if lives == 1 {
        life = livesImages[1]
    } else {
        life = livesImages[2]
        endGame(triggeredByBomb: false)

    life.texture = SKTexture(imageNamed: "sliceLifeGone")

    life.xScale = 1.3
    life.yScale = 1.3 1, duration:0.1))

Note how I'm using SKTexture to modify the contents of a sprite node without having to recreate it, just like in project 14.

Finally, there's the endGame() method. I've made this accept a parameter that sets whether the game ended because of a bomb, so that we can update the UI appropriately.

func endGame(triggeredByBomb: Bool) {
    if gameEnded {

    gameEnded = true
    physicsWorld.speed = 0
    isUserInteractionEnabled = false

    if bombSoundEffect != nil {
        bombSoundEffect = nil

    if triggeredByBomb {
        livesImages[0].texture = SKTexture(imageNamed: "sliceLifeGone")
        livesImages[1].texture = SKTexture(imageNamed: "sliceLifeGone")
        livesImages[2].texture = SKTexture(imageNamed: "sliceLifeGone")

If the game hasn't already ended, this code stops every object from moving by adjusting the speed of the physics world to be 0. It stops any bomb fuse fizzing, and sets all three lives images to have the same "life gone" graphic. Nothing surprising in there, but you do need to declare gameEnded as a property for your class, like this:

var gameEnded = false

Even though the game has ended, some actions can still take place. This should be banned if possible, so add these lines to the start of tossEnemies() and touchesMoved():

if gameEnded {

That's it, your game is done!

Learn Swift faster!

Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!

< Previous: Slice to win   Next: Wrap up >
Click here to visit the Hacking with Swift store >>