Time for action – calling game over

We will make sure that when a game over display screen pops up, any of our display objects that are currently in motion stop moving, and the event listeners are deactivated. Aside from the visual display of our game over screen, we'll be adding a sound notification that will also help to trigger the event. To end the game, perform the following steps:

  1. Create a new local function called callGameOver() and place it after the setScore() function and before the drawBackground() function:
        local callGameOver = function()
  2. Introduce the sound effects when the game over display pops up. Have gameIsActive set to false and pause the physics in the game:
          audio.play( gameOverSound )
          gameIsActive = false
          physics.pause()
  3. Create a shade that overlays the current background:
          shade = display.newRect( 0, 0, 570, 320 )
          shade:setFillColor( 0, 0, 0 )
          shade.x = 240; shade.y = 160
          shade.alpha = 0  -- Getting shade ready to display at game end
  4. Display the game over window and reiterate the final score:
          gameOverScreen = display.newImageRect( "gameOver.png", 400, 300 )
          local newScore = gameScore
          setScore( newScore )
          gameOverScreen.x = 240; gameOverScreen.y = 160
          gameOverScreen.alpha = 0
          gameGroup:insert( shade )
          gameGroup:insert( gameOverScreen )
          transition.to( shade, { time=200, alpha=0.65 } )
          transition.to( gameOverScreen, { time=500, alpha=1 } )
  5. Have the score display on the game over screen:
          scoreText.isVisible = false
          scoreText.text = "Score: " .. gameScore
          scoreText.xScale = 0.5; scoreText.yScale = 0.5  --> for clear retina display text
          scoreText.x = 240
          scoreText.y = 160
          scoreText:toFront()  -- Moves to front of current display group
          timer.performWithDelay( 0,
            function() scoreText.isVisible = true; end, 1 )
        end
    Time for action – calling game over

Our gameOver() function triggers our gameOverSound sound effect that we preloaded at the beginning of our code. We made sure no events, such as the motion from the accelerometer, are disabled through gameIsActive = false.

The elements of our display objects appear at this point in time with shade, gameOverScreen, and scoreText.

If you notice, scoreText disappears when game play has ended by scoreText.isVisible = false and then reappears in a different area of the screen, using timer.performWithDelay( 0, function() scoreText.isVisible = true; end, 1 ).

We will activate all the remaining functions and have them run accordingly.