Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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