Created
July 23, 2021 07:06
-
-
Save LarsBergqvist/32341f6ba97ca873521c1778d182fade to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const initialState = { | |
moves: 0, | |
gameComplete: false, | |
imageNumber: 1, | |
tiles: [], | |
size: undefined, | |
gameId: undefined, | |
gameName: undefined | |
}; | |
// The reducer for the game | |
// The state is an object with game state and an array of tiles | |
// A tile is a number 1-N and the blank tile is represented by 0 | |
function tileGame(state = initialState, action) { | |
switch (action.type) { | |
case INIT_GAME: { | |
return Object.assign({}, initialState, { | |
gameId: action.gameId, | |
size: gameConfigs[action.gameId].size, | |
gameName: gameConfigs[action.gameId].name, | |
imageNumber: action.imageNumber, | |
tiles: generateTileSet(gameConfigs[action.gameId].size, action.doShuffling) | |
}); | |
} | |
case MOVE_TILE: { | |
if (action.id === 0) { | |
// selected blank tile | |
return state; | |
} | |
if (state.gameComplete) { | |
return state; | |
} | |
if (action.id < 0 || action.id > (state.size * state.size - 1)) { | |
return state; | |
} | |
if (!hasEmptyTileOnSides(state.size, action.id, state.tiles)) { | |
return state; | |
} | |
// | |
// Move the tile | |
// | |
const newTiles = state.tiles.map(t => t); | |
const setWithSwappedTiles = swapTilesInSet(newTiles, 0, action.id); | |
// | |
// Check result | |
// | |
const gameComplete = allTilesAreAligned(setWithSwappedTiles); | |
return Object.assign({}, state, { | |
gameComplete, | |
moves: state.moves + 1, | |
tiles: setWithSwappedTiles | |
}); | |
} | |
default: | |
return state; | |
} | |
} | |
export default tileGame; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment