Skip to content

Instantly share code, notes, and snippets.

@LarsBergqvist
Created July 23, 2021 06:32
Show Gist options
  • Save LarsBergqvist/72d7818692c65c2ff461e006d144fb42 to your computer and use it in GitHub Desktop.
Save LarsBergqvist/72d7818692c65c2ff461e006d144fb42 to your computer and use it in GitHub Desktop.
Reducer for image puzzle game
const initialState = {
turnNo: 1,
numClicksWithinTurn: 0,
selectedId: undefined,
gameComplete: false,
imageNumber: 1,
tiles: [],
size: undefined, // number of rows/columns in the puzzle matrix
gameId: undefined,
gameName: undefined
};
// The reducer for the game
// State is an object with game status and an array of tiles
// The array represents a size*size matrix with a unique
// numerical value 0...size*size-1 per tile
// A tile is an object with these properties:
// {
// id: number, // the number/value for the tile
// top: number, // pixel offset for the image that is projected on the tile
// left: number // pixel offset for the image that is projected on the tile
// }
//
function tileGame(state = initialState, action) {
switch (action.type) {
case INIT_GAME: {
const size = gameConfigs[action.gameId].size
return Object.assign({}, initialState,
{
gameId: action.gameId,
size,
gameName: gameConfigs[action.gameId].name,
imageNumber: action.imageNumber,
tiles: generateTileSet(size)
});
}
case SELECT_TILE: {
if (state.gameComplete) {
return state;
}
if (action.id < 0 || action.id > (state.size * state.size - 1)) {
return state;
}
const numClicks = state.numClicksWithinTurn + 1;
if (numClicks === 1) {
const newTiles = state.tiles.map(t => t);
return Object.assign({}, state, {
selectedId: action.id,
numClicksWithinTurn: numClicks,
gameComplete: false,
tiles: newTiles
});
}
const newTiles = state.tiles.map(t => t);
if (action.id === state.selectedId) {
return Object.assign({}, state, {
selectedId: undefined,
numClicksWithinTurn: 0,
tiles: newTiles
});
}
const setWithSwappedTiles = swapTilesInSet(newTiles, state.selectedId, action.id);
const gameComplete = allTilesAreAligned(setWithSwappedTiles);
return Object.assign({}, state, {
selectedId: undefined,
numClicksWithinTurn: 0,
gameComplete,
turnNo: state.turnNo + 1,
tiles: setWithSwappedTiles
});
}
case SHUFFLE_TILES: {
const newTiles = shuffleTileSet(state.tiles);
return Object.assign({}, state, { tiles: newTiles });
}
default:
return state;
}
}
export default tileGame;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment