layouts.gui_script 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. local function set_scores_state(self, score_state)
  2. gui.set_text(self.ui_elements.num_score, score_state.score)
  3. gui.set_text(self.ui_elements.num_best, score_state.best_score)
  4. end
  5. function init(self)
  6. self.current_score_state = { -- < 1 >
  7. score = math.random(100, 500),
  8. best_score = math.random(501, 999)
  9. }
  10. self.ui_elements = {} -- < 2 >
  11. self.ui_elements.num_score = gui.get_node("num_score")
  12. self.ui_elements.num_best = gui.get_node("num_best")
  13. set_scores_state(self, self.current_score_state) -- < 3 >
  14. end
  15. function on_message(self, message_id, message, sender)
  16. if message_id == hash("layout_changed") then -- < 4 >
  17. set_scores_state(self, self.current_score_state)
  18. elseif message_id == hash("update_score") then -- < 5 >
  19. self.current_score_state.score = self.current_score_state.score + message.score
  20. if self.current_score_state.score > self.current_score_state.best_score then
  21. self.current_score_state.best_score = self.current_score_state.score
  22. end
  23. set_scores_state(self, self.current_score_state)
  24. end
  25. end
  26. --[[
  27. 1.-It's important to store the state of the UI separately from the view.
  28. 2.-Having all the nodes for UI elements makes it easier to work with.
  29. 3.-This function updates the view with the current state.
  30. 4.-When the layout changes, all the nodes (view) reset to the corresponding layout setup.
  31. At this point, we need to restore our state.
  32. 5.-External code updates the state, and we apply changes of the state to the view.
  33. --]]