Frage

I am implementing a basic board game in Java and that I am having difficulty deciding the pros and cons of in solving. I am already successfully making use of the Command Pattern to enable undo functionality in the game, and originally intended to implement game saving/loading by serializing the entire set of game model objects.

However I realised that as the game is a board game with no random elements involved and always initialising with the same state, I could implement save/load functionality by simply serializing the object containing the command stack and the commands themselves up to that point, and then re-execute all of the commands in order to bring the game up to the saved position.

My current design does not allow me to do this, as my Commands hold references to the object instances that form my board's tiles and pieces, which I believe is best OO practice. That would mean I would also have to serialise those model objects, which would defeat the purpose of just serialising the commands and executing them. My question is whether having the commands just hold the integer locations of the boards tiles would be considered bad practice.

Relevant portion of my Command class code:

private GameController controller;
private Tile sourceTile;
private Tile[] route;

public MoveCommand(GameController controller, Tile sourceTile, Tile... route) {
    this.controller = controller;
    this.sourceTile = sourceTile;
    this.route = route;
}

@Override
public void execute() {
    controller.executeMove(sourceTile, route);
}

I intend to change the Tile references into references to a new serializable class called TileLocation or something to that effect, which will hold an X and Y integer so that the board can find the tiles.

War es hilfreich?

Lösung

Nothing wrong with storing your game state and moves as integers. But I would not recommend to use java serialization for long term storage. (it will be almost impossible to update game classes and reread saved states). Use some kind of XML or JSON databinding ( Jackson, GSON , whetever you like) for long term persistence.

Andere Tipps

I would also argue against serialization, and opt for JSON or XML instead. However, if you must serialize, you can use the "transient" keyword on any member variable to prevent it from being included in the serialization.

private transient int x = 0;

this particular variable won't be included when serializing the object. In general it's good practice (even if you use JSON or XML) to mark these types of fields as transient so you can use reflection to discover the contents of an object to write out, without having specific business logic to decide which fields to save and which not to save.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top