rootpanthera
rootpanthera

Reputation: 2771

Reset each variable in java

Is there a way to reset a value of a static variable to their initial state? For example:

I have a lot of variables which holds score, speed, etc. All those variables are changing during the program execution. So when the user fails in a game, I would like to reset ALL variables to their initial state. Is there some way? Because i don't know if it is a good idea to do this manually for EACH variable in my program. for example:

static int SCORE = 0;
static float SPEED = 2.3f;



public void resetGame() {

SCORE = 0;
SPEED = 2.3;

}

Upvotes: 3

Views: 18451

Answers (8)

user3001
user3001

Reputation: 3487

Usually games use more than one thread (for example when using Swing or painting any graphics), e.g. so inputs are not blocked. That means with all the other solutions you might run into race conditions. This solution of Evan Knowles came closest.

I would suggest a immutable GameState class, e.g.

public GameState {
  private final int score;
  private final int speed;

  // initial state/"reset game"
  public GameState() {
    score = 0;
    speed = 2.3;
  }
  // Private so we are always in a valid state
  private GameState(int _score, int _speed) {
     score = _score;
     speed = _speed;
  }

  public GameState updateSpeed(int _speed) { return new GameState(this.score, _speed); }
  public GameState updateScore(int _score) { return new GameState(_score, this.speed); }

  public int getSpeed() { return speed;}
  public int getScore() { return score;}


  // add getters, setters and whatsoever here. But watch for proper synchronization between threads!
}

The advantage here is that once the values are assigned, they can't be changed anymore ("immutable"/read-only) from the outside, so there are no concurrency issues. Plus, you get a sort of chaing for free (see below)! Moreover, you can safely (de-)serialize the game state for saving/loading games.

Effectively, each GameState represents one state in a finite state machine. Calling either updateSpeed or updateScore is a transition to a new state. The public default constructor is a transition to the initial state of the state machine. On a side note, the state machine is finite because the value ranges of score and speed are finite, thus all combiniations of them result in a finite amount of states.

I now assume your class for doing other game stuff is called Game.

public Game {
  private volatile GameState gameState = new GameState();
  public void resetGame() {
    gameState = new GameState();
  }
  // Just an example
  public increaseSpeed(int _additionalSpeed) {
    gameState = gameState.updateSpeed(gameState.getSpeed() + _additionalSpeed);
  }

  // Change more than one value
  public changeBoth(int _newSpeed, int _newScore) {
    // First way: Create a new GameState, change both values step by step and then assign afterwards.
    GameState _newState = gameState.updateScore(_newScore);
    // other computations follow
    // Do NOT assign to gameSpate here, because the state would be inconsistent then.  
    _newState = _newState.updateSpeed(_newSpeed);
    // At the END of the method, assign the new game state. That ensures that the state is always valid
    gameState = _newState;

    // Second way: Use method chaining if you don't need to make other computations in between. Again, do this at the end of the method
    gameState = gameState.updateScore(_newScore).updateSpeed(_newSpeed);
  }

}

The volatile keyword makes sure every thread sees the same value of the gameState variable. You might want to consider using other synchronization/locking techniques instead, too. Alternatively you can make the gameState field static and skip the volatile keyword if you only have one Game object. Because GameState is immutable(read-only), the state of your game now is always consistent/valid.

Upvotes: 0

53by97
53by97

Reputation: 425

A good way is to use a static init() and call it when exception occurs.

package com.kvvssut.misc;

public class ResetStatic {

    private static int SCORE = 0;
    private static float SPEED = 2.3f; 

    private static void init() {
        SCORE = 0;
        SPEED = 2.3f;       
    }



    public static void main(String[] args) {

        SCORE = 100;
        SPEED = 230.3f;

        try {
            throw new RuntimeException();
        } catch (Exception e) {
            init();
        }

        System.out.println(SCORE);
        System.out.println(SPEED);
    }

}

Upvotes: -1

PeterMmm
PeterMmm

Reputation: 24630

I have a lot of variables which holds score, speed, etc

You should put them all into one class and every member get initialsed (if the default won't work). You will hold the player's state in one reference to an object of this class. To reset simply create a new object of this class and assign it to the reference.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

Use an object, and set its initial state in the constructor:

public class GameSettings {
    private int score = 0;
    private float speed = 2.3F;

    // methods omitted for brevity
}

...

public void resetGame() {
    gameSettings = new GameSettings();
}

Also, please respect the Java naming conventions. ALL_CAPS is reserved for constants. Variables should be lowerCase.

Upvotes: 14

porglezomp
porglezomp

Reputation: 1349

You'll just have to reset them one by one. If you're worried about typos you could do: int initialscore = 0; int score = initialscore; and then reset them to the initial... variables in your function.

Upvotes: 0

Evan Knowles
Evan Knowles

Reputation: 7501

Why not just recreate the object if you want it reset? Then it'll implicitly have the default values.

Upvotes: 2

Philipp
Philipp

Reputation: 69663

You could just declare your variables without values and have a method initGamestate() which sets all variables to their initial values. Call this function both on initialization of the application and when the user starts a new game.

A more object-oriented solution would be to have a class GameState which has all these variables and sets the default in its constructor. You then start every game by initializing a fresh object with new GameState();

Upvotes: 1

Anubian Noob
Anubian Noob

Reputation: 13596

Store the default values.

static final int DEFAULT_SCORE = 0;
static final float DEFAULT_SPEED =2.3;

static int SCORE = DEFAULT_SCORE;
static float SPEED = DEFAULT_SPEED;

public static void resetGame() {
    SCORE = DEFAULT_SCORE;
    SPEED = DEFAULT_SPEED;
}

Upvotes: 3

Related Questions