Я пытаюсь использовать Stack в качестве инструмента для отмены перемещения элементов игры в нарды (кубики, слоты и т. Д. c ..), и это на самом деле работает довольно хорошо, за исключением того, что элементы GUI возвращаются обратно туда, где они предполагается при нажатии кнопки «Отменить».
Инициализация переменных стека:
static Stack<Slot[]> BoardState = new Stack<>(); // stack to keep game variables
static Stack<Boolean> GameState = new Stack<>(); // stack to keep game variables
static Stack<Integer> GameData = new Stack<>(); // stack to keep game variables
Stack Pu sh & Функции Pop:
public static void saveGame() { // save all crucial information in stacks for undo.
BoardState.push(Board.getSlots());
GameData.push(getTurnCount());
GameData.push(Dice.getDice1());
GameData.push(Dice.getDice2());
GameState.push(isWhiteTurn());
GameState.push(isOngoing());
GameState.push(Dice.dice1Available);
GameState.push(Dice.dice2Available);
GameState.push(Dice.dice3Available);
GameState.push(Dice.dice4Available);
GameState.push(Dice.dice1Playable);
GameState.push(Dice.dice2Playable);
GameState.push(Dice.dice3Playable);
GameState.push(Dice.dice4Playable);
setCanload(true);
}
public static void loadGame() { // save all crucial information in stacks for load.
Board.setSlots(BoardState.pop());
Dice.setDice1(GameData.pop());
Dice.setDice2(GameData.pop());
Rules.setTurnCount(GameData.pop());
Dice.setDice4Playable(GameState.pop());
Dice.setDice3Playable(GameState.pop());
Dice.setDice2Playable(GameState.pop());
Dice.setDice1Playable(GameState.pop());
Dice.setDice4Available(GameState.pop());
Dice.setDice3Available(GameState.pop());
Dice.setDice2Available(GameState.pop());
Dice.setDice1Available(GameState.pop());
setOngoing(GameState.pop());
setWhiteTurn(GameState.pop());
if (BoardState.empty())
setCanload(false);
}
Кнопка отмены на GUI классе:
JButton undo = new JButton("Undo");
panel.add(undo);
undo.setBounds(805, 465, 75, 40);
undo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Rules.isCanload() == true) {
Rules.loadGame();
setBoard(Rules.getSlots());
JOptionPane.showMessageDialog(null, "Undo Successful");
setPlayble(Rules.canPlay(Board.getSlots(), Board.getDice()));
} else {
JOptionPane.showMessageDialog(null, "Unable to undo");
}
}
});