Time for action – setting the score

Who doesn't like some friendly competition? We're familiar with scoreboards from the games we made in the previous chapters. So, we are not strangers to tracking the score. Perform the following steps to set the score:

  1. Create a local function called setScore() with a parameter called scoreNum:
        local setScore = function( scoreNum )
  2. Set the variables to count the score:
          local newScore = scoreNum
          gameScore = newScore
          if gameScore < 0 then gameScore = 0; end
  3. Have the score updated when points are earned in game play and close the function:
          scoreText.text = "Score: " .. gameScore
          scoreText.xScale = 0.5; scoreText.yScale = 0.5
          scoreText.x = (scoreText.contentWidth * 0.5) + 15
          scoreText.y = 15
        end

When setScore(scoreNum) is called within any function, it will refer to all the methods using the gameScore variable. Assuming gameScore = 0 at the start of the application, the value increments to what gameScore is set to.

In scoreText.text = "Score: " .. gameScore, "Score: " is the string that displays on the device during game play. The gameScore variable takes the current value given to the variable and displays it as a string.

A logical setting for your display objects helps the player envision the relationship between the main character and the environment. Since our main character is a lumberjack, it would make sense to have him set in a forest or an area focused entirely on nature.