const Immutable = require('immutable'); import * as TroggleActions from '../../actions/board/troggle.actions'; import { SETTINGS } from '../../App'; const initial = []; const reducer = (state = initial, action) => { if (action.type !== TroggleActions.TROGGLE_ACTION) { return state; } switch (action.action) { case TroggleActions.MOVE: // Randomize movement with boolean flags. const moveToAttack = Boolean(Math.round(Math.random())); const moveAlongXAxis = Boolean(Math.round(Math.random())); const moveInPositiveDirection = Boolean(Math.round(Math.random())); const x = state[action.index].x; const y = state[action.index].y; let newX = x; let newY = y; // DO NOT CONSOLIDATE. Attack first, ask questions later. if (moveAlongXAxis === true) { if (x === SETTINGS.GRID_WIDTH - 1 || (moveToAttack && x >= action.muncherX)) { newX = x - 1; } else if (x === 0 || (moveToAttack && x < action.muncherX)) { newX = x + 1; } else if (moveInPositiveDirection) { newX = x + 1; } else if (!moveInPositiveDirection) { newX = x - 1; } } else { if (y === SETTINGS.GRID_HEIGHT - 1 || (moveToAttack && y >= action.muncherY)) { newY = y - 1; } else if (y === 0 || (moveToAttack && y < action.muncherY)) { newY = y + 1; } else if (moveInPositiveDirection) { newY = y + 1; } else if (!moveInPositiveDirection) { newY = y - 1; } } return Immutable.fromJS(state) .setIn([action.index, 'x'], newX) .setIn([action.index, 'y'], newY) .toJS(); case TroggleActions.CREATE: return Immutable.List(state).push({ x: 0, y: 0 }).toArray(); break; } return state; }; export default reducer;