Resetting a level

Monkey Forums/Monkey Programming/Resetting a level

elite_dtn(Posted April) [#1]
I have loads of objects on my level, was just wondering about the easier way to reset them all, for example if the player has failed a level and needs to restart


Gerry Quinn(Posted April) [#2]
It's not necessarily the most efficient method, but it's one area of programming where garbage collection does make things easy: you can just 'new' the whole level and re-create it along with its components. No need to worry about deleting stuff that your code has forgotten about.

(And another reason to load images into globals, or some permanent object)


elite_dtn(Posted April) [#3]
But how do i do that so that it resets everything like player positions?


Gerry Quinn(Posted April) [#4]
If the player gets its position set to the starting value when it is created, and the game creates the player when it's created, then creating a new game will create a new player too.

Of course the alternative is just to have a method that initialises everything to starting values, and then it doesn't matter whether you create a new object or re-initialise the old object.

If you look at the last code I posted in the 'enemy movement' thread, you can see how it is set up to work this way. The initialise() method sets all fields to their starting values. If Enemy.New() calls initialise(), then a newly created enemy will have those values. Ir you could call it on an existing enemy, that enemy will e completely reset.

This is why it helps to be systematic. Have a method for setting up a new enemy, have a method for updating an existing enemy, and have a method for drawing an existing enemy, and don't mix up the responsibilities. Then you can call whichever is appropriate whenever you need to.

I advise always having an explicit initialisation method, instead of saying "Field xPos:Int = 100" for this reason - setting the field default value only happens when you construct a new item, but a proper initialiser can reset the object any time. But as I said, creating a bunch of new objects is workable too.