Time for action –making win and lose conditions

For any game alerts to even appear during game play, we need to create some if statements for every possible scenario available in each level. When this occurs, the score needs to be reset back to zero. To make the win and lose conditions, follow these steps:

  1. Below the alertScreen() function, create a new function called restart():
    function restart()
  2. Create an if statement for a "win" game event when the first level has been completed and transitions to level 2:
      if gameEvent == "win" and currentLevel == 1 then
        currentLevel = currentLevel + 1
        changeLevel2()
        levelNum.text = tostring(currentLevel)
  3. Add an elseif statement for a "win" game event when the second level has been completed and when it notifies the player that the game has been completed:
      elseif gameEvent == "win" and currentLevel == 2 then
        alertScreen("  Game Over", "  Congratulations!")
        gameEvent = "completed"
  4. Add another elseif statement for the "lose" game event at the first level. Reset the score to zero and replay level 1:
      elseif gameEvent == "lose" and currentLevel == 1 then
        score = 0
        scoreNum.text = "0"
        changeLevel1()
  5. Add another elseif statement for a "lose" game event at the second level. Reset the score to zero and replay level 2:
      elseif gameEvent == "lose" and currentLevel == 2 then
        score = 0
        scoreNum.text = "0"
        changeLevel2()
  6. Finally, add another elseif statement for gameEvent = "completed". Close the function with end:
      elseif gameEvent == "completed" then
        alertBox:removeEventListener("tap", restart)
      end
    end
  7. Now, we need to backtrack and add an event listener to the alertScreen() function using the alertBox object. We will add it to the bottom of the function. This will activate the restart() function:
      alertBox:addEventListener("tap", restart)

The restart() function checks all the gameEvent and currentLevel variables that occur during game play. When a game event checks for the "win" string, it also goes down the list of statements to see what comes out true. For example, if the player wins and is currently on level 1, then the player moves on to level 2.

If the player loses, gameEvent == "lose" becomes true, and the code checks what level the player lost in. For any level the player loses in, the score reverts to 0, and the current level the player was on is set up again.