在不知道您的游戏的确切目标或您想到的其他类型的移动(我假设移动也放置数字)的情况下,这是我在 java 中可能会根据您当前的限制采取的方法提出来。
/* Game.java */
import java.util.Stack;
public class Game
{
protected static abstract class Move
{
protected final int x;
protected final int y;
protected Move(int x, int y) {
this.x = x;
this.y = y;
}
protected void execute(Game game) {
game.placeFigure(x, y);
}
protected void undo(Game game) {
game.removeFigure(x, y);
}
}
private Stack<Move> history = new Stack<Move>();
public void doMove(Move move) {
move.execute(this);
history.push(move);
}
public void undoMove() {
if(history.empty()) {
System.out.println("no move to undo");
}
else {
Move move = history.pop();
move.undo(this);
}
}
protected void placeFigure(int x, int y) {
System.out.println("place figure at: " + x + "," + y);
}
protected void removeFigure(int x, int y) {
System.out.println("remove figure at: " + x + "," + y);
}
}
/* DefaultMove.java */
public class DefaultMove extends Game.Move
{
public DefaultMove(int x, int y) {
super(x, y);
}
}
/* SpecialMove.java */
public class SpecialMove extends Game.Move
{
public SpecialMove(int x, int y) {
super(x + 10, y + 10);
System.out.println("SpecialMove displaces x and y by 10");
}
}
/* Main.java */
public class Main
{
public static void main(String[] arguments) {
Game game = new Game();
DefaultMove defaultMove = new DefaultMove(3,6);
SpecialMove specialMove = new SpecialMove(4,5);
game.doMove(defaultMove);
game.doMove(specialMove);
game.undoMove();
game.undoMove();
game.undoMove();
}
}
哪些打印:
SpecialMove displaces x and y by 10
place figure at: 3,6
place figure at: 14,15
remove figure at: 14,15
remove figure at: 3,6
no move to undo
也许这根本不是您想要的,但希望这能给您一些想法。让我知道您是否有完全其他的目标,我会看看我是否可以满足。