Skip to content

Commit

Permalink
fix(UndoRedoManager): IndexOutOfBoundsException when adding a state
Browse files Browse the repository at this point in the history
Fixes #123, fixes #126
  • Loading branch information
kaajjo committed Jan 1, 2025
1 parent 6ad74a7 commit 7f7f202
Showing 1 changed file with 9 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,20 @@ class UndoRedoManager(private val initialState: GameState) {
private var states: MutableList<GameState> = mutableListOf(initialState)
private var currentState = 0

/**
* Adds a new game state to the history of states.
* If the current state changes, all later states are removed.
*
* @param gameState The new game state to add.
*/
fun addState(gameState: GameState) {
if (gameState == states[currentState]) {
if (currentState in states.indices && gameState == states[currentState]) {
return
}

val statesToDelete = mutableListOf<GameState>()
for (i in states.indices - 1) {
if (i > currentState) {
statesToDelete.add(states[i])
}
if (currentState < states.size - 1) {
states = states.subList(0, currentState + 1).toMutableList()
}
statesToDelete.forEach { item ->
states.remove(item)
}


states.add(gameState)
currentState = states.size - 1
Expand Down

0 comments on commit 7f7f202

Please sign in to comment.