diff --git a/src/reducers/game.js b/src/reducers/game.js index fb931c1..3497dbd 100644 --- a/src/reducers/game.js +++ b/src/reducers/game.js @@ -1,8 +1,39 @@ import Chess from 'chess' +function handleClick(state, square) { + const selectedSquare = state.client.game.board.getSquare(square); + const currentSide = state.client.game.getCurrentSide(); + + if(state.selectedSquare===square) + return { + client: state.client, + selectedSquare: null + }; + if(selectedSquare.piece + && selectedSquare.piece.side === currentSide) + return { + client: state.client, + selectedSquare: square + }; + try { + state.client.move(state.selectedSquare, selectedSquare.file + selectedSquare.rank) + return { + client: state.client, + selectedSquare: null + } + } catch (error) { + if(!error.includes("Move is invalid")) + throw error + } + + return state; +} + export default (state = {client: Chess.createSimple(), selectedSquare: null}, action) => { switch(action.type) { + case 'CLICK_SQUARE': + return handleClick(state, action.square); default: return state; }