diff --git a/app/reducers/chess-board.js b/app/reducers/chess-board.js index 9ea63ae..14fc298 100644 --- a/app/reducers/chess-board.js +++ b/app/reducers/chess-board.js @@ -1,21 +1,17 @@ import defaultState from "store/default-state"; +import movePiece from "reducers/move-piece"; const chessBoardReducer = (state = defaultState, action) => { switch (action.type) { case "MOVE_PIECE": - var piece = state.board[from.rank][from.file]; - state.board[to.rank][to.file] = piece; - state.board[from.rank][from.file] = null; - return state; + const newState = { + board: movePiece(state.board, action.from, action.to), + selectedSquare: null + } - var newBoard = state.board.map((item, index) => { - }); - return Object.assign({}, state, { - board: newBoard - }); + return Object.assign({}, state, newState); case "SELECT_PIECE": - console.log("Action fired"); return Object.assign({}, state, { selectedSquare: action.coords }); default: diff --git a/app/reducers/move-piece.js b/app/reducers/move-piece.js new file mode 100644 index 0000000..a830aa3 --- /dev/null +++ b/app/reducers/move-piece.js @@ -0,0 +1,17 @@ +import Immutable from "immutable"; +import { Map } from "immutable"; + +const movePiece = (board, from, to) => { + const newBoard = Immutable.fromJS(board); + const piece = board[from.rank][from.file]; + + const boardChange = Map([ + [to.rank, Map([[to.file, piece]])] + ]).mergeDeep(Map([ + [from.rank, Map([[from.file, null]])] + ])); + + return newBoard.mergeDeep(boardChange).toJS(); +} + +export default movePiece;