0
\$\begingroup\$

What is the best practice when implementing a way to start a game when a previous game has been played and the game's variables have already some kind of values assigned to them?

The most naive answer would be to create a method that would set all the variables and objects the game uses to their default value.

However that would be obviously error prone in cases when some time later a new variable is added to the game and not added to the method where it's set to a default value - such cases could lead to impossible to track bugs when a game would work ok if started first time, but not thereafter.

This would also violate DRY principle as a variable would have a default value at two different places - in the place where it's used and in the method where it's reset.

\$\endgroup\$
4
\$\begingroup\$

The most naive answer would be to create a method that would set all the variables and objects the game uses to their default value.

Do that thing. In the spot where you create a new game (for the first time or are resetting variables), call that function. It will set all of your variables to default and its called from both places. This is perfectly DRY.

when some time later a new variable is added to the game and not added to the method

Put an invalid value into it when you declare it. Set it to null or -1 or whatever. Something that will absolutely cause a problem if the value isn't set to its proper starting value by your function.

If some of your variables are objects and those objects hold values too...discard them and create new ones. Don't bother resetting them, just delete and recreate: the constructor is that create-defaults method. If you wanted to, you could do this for your main collection of variables (rather than having them as fields on your Game class, make them fields on your GameData class and then just create a new GameData whenever you start a new game).

\$\endgroup\$
0
\$\begingroup\$

For those that might ran into same question in the future:

I've decided to go with wrapping the entire logic of my game in a class that gets instantiated when the game starts. When the game ends I just destroy the existing object and create a new one, thus avoiding any chance of bugs when resetting the game.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.