Pong | Updating the score.

The score game object needs to respond when it receives a message to update the score.

  1. In the assets panel, right click the main folder (or any file inside it) and select, 'New...', 'Script'.

Score script

  1. Name the script, 'score', and click, 'Create Script'.

Name score script

  1. In the init function of the score script, initialise the two variables to hold the scores for each player.
function init(self)
	self.player1_score = 0
	self.player2_score = 0
end
  1. In the on_message function, add the code to respond to the messages that the score object can receive.
function on_message(self, message_id, message, sender)
	if message_id == hash("player1_scored") then
		self.player1_score = self.player1_score + 1
		label.set_text("#label", self.player1_score .. " : " .. self.player2_score)
	end
	if message_id == hash("player2_scored") then
		self.player2_score = self.player2_score + 1
		label.set_text("#label", self.player1_score .. " : " .. self.player2_score)
	end
end
What does this code do?

If the score object receives a message that player1 has scored it increments the player1_score variable before updating the text in the label. Note 'label' is the id of the label object. We prefix this with a # symbol.

two dots (..) is a concatenator operator in Lua. This joins variables and strings together. The player1_score variable is concatenated with a colon and the player2_score.

  1. Finally it is important to remember to attach this script file to the score game object. In the assets panel, double click, 'main.collection'.
  2. In the outline panel, right click, 'score' and select, 'Add Component File'.

Add score script

  1. Choose, '/main/score.script' and click 'OK'.

Choose score script

  1. Save the changes by pressing CTRL-S or 'File', 'Save All'.
  2. Run your game at this point. It should now keep the score.
  3. Run

Our game logic is now finished, but it would be nice to add some sound effects. Stage 9a >