Changing screens - OpenWeek/app-for-a-KAP GitHub Wiki

Changing screens

How do we change screens in the game ? Simply use setScreen(new Screen()) in every screen buttons is tempting. However, it is a bad design fault since it leads to memory leaks, crashes and strange bugs.

Having an entity saving in memory an instance of screens (only created when they are first accessed) is a good way to solve this. In the application here, the main class Kapotopia has this role of conductor. When a screen try to be accessed, the game first check if it has been first accessed or not and create the game or not. The developer can also destroy screen still loaded in memory if this one start to grow to much.

The problem of resetting a screen.

Suppose you played game1 and you got a score of -45. Angry to have been so bad (and it's understandable), you go back to the Main menu screen and try again the game. However, in the introduction screen, that you already seen once btw, nothing appear, everything is blank. What happened ? As you use again the same screens as you keep them in memory, you havent reseted the multiple buttons appearing and making dissapearing the old one. Thus at the end, no button neither introduction scenes are shown anymore.

The solution ? Resetting the screen. It can be achieved by two ways :

  1. Destroying the screen and creating a new one
  2. Implementing a reset function that is called whenever the screen is leaved.

Destroying the screen is probably the easiest solution. However, if the player will pass by that screen often, it might not be a good idea since the assets will be reloaded each time. Then a reset function seems more appropriate. There, this is the responsibility of the programmer to make it's function run correctly.