Let's play a game

Report a typo

Imagine that your team is making a board game engine. Your teammates already created the Board class and successfully implemented theplace, move and reDraw methods of the GameEngine interface in the BoardGameEngine class, but the work is not finished yet: the undo, save and load methods are waiting to be implemented too.

Since it's a good idea to achieve their functionality using the Memento pattern, your teammates added the Snapshot nested class inside the Board class that will be used for saving and restoring the state of Board. Your task is to finish the work! However, the implementation must satisfy the following requirements:

  • Do not make breaking changes to the code because BoardGameEngine is already used as an implementation of the GameEngine interface somewhere else. You CAN make changes to the existing code but make sure they won't break anything.

  • The state of Board must be saved automatically every time it changes.

  • undo must roll back the changes one by one. If there are no changes left to undo, undo must do nothing.

  • save and load must work together: save must create a savepoint in memory (not on a hard drive!) and load must restore the board to that state. There must be only one savepoint, and subsequent calls of the save method must overwrite it.

  • If no savepoint is available, the load method must do nothing. Also, when the load method successfully loads a savepoint, the history of Board state changes must be cleared so that undo does not roll back anything until new changes are made.

Good luck and have fun!

Write a program in Java 17
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// Don't touch it, it's already in use!
interface GameEngine {

void place(char entity, int x, int y);

void move(int fromX, int fromY, int toX, int toY);

void undo();

void save();

void load();

void reDraw();
}

// this class is finished for now, no changes to board logic please
class Board {
private static final char EMPTY = ' ';
private char[][] squares;

Board(int width, int height) {
squares = new char[height][width];
Arrays.stream(squares).forEach(row -> Arrays.fill(row, EMPTY));
}

public void place(char gamePiece, int col, int row) {
squares[row - 1][col - 1] = gamePiece;
}

public void move(int fromCol, int fromRow, int toCol, int toRow) {
char gamePiece = squares[fromRow - 1][fromCol - 1];
___

Create a free account to access the full topic