diff --git a/src/App.js b/src/App.js index 8310a8a..5ba1bce 100644 --- a/src/App.js +++ b/src/App.js @@ -32,29 +32,65 @@ const KEY_CODES_MAPPER = { 40: 'BOTTOM', }; +const getRandomNumberFromRange = (min, max) => + Math.floor(Math.random() * (max - min +1 ) + min); + +const getRandomCoordinate = () => + ({ + x: getRandomNumberFromRange(1, GRID_SIZE - 1), + y: getRandomNumberFromRange(1, GRID_SIZE - 1), + }); + const isBorder = (x, y) => x === 0 || y === 0 || x === GRID_SIZE || y === GRID_SIZE; const isPosition = (x, y, diffX, diffY) => x === diffX && y === diffY; +const isSnake = (x, y, snakeCoordinates) => + snakeCoordinates.filter(coordinate => isPosition(coordinate.x, coordinate.y, x, y)).length; + +const getSnakeHead = (snake) => + snake.coordinates[0]; + +const getSnakeWithoutStub = (snake) => + snake.coordinates.slice(0, snake.coordinates.length - 1); + +const getIsSnakeEating = ({ snake, snack }) => + isPosition(getSnakeHead(snake).x, getSnakeHead(snake).y, snack.coordinate.x, snack.coordinate.y); + const getCellCs = (snake, snack, x, y) => cs( 'grid-cell', { 'grid-cell-border': isBorder(x, y), - 'grid-cell-snake': isPosition(x, y, snake.coordinate.x, snake.coordinate.y), + 'grid-cell-snake': isSnake(x, y, snake.coordinates), 'grid-cell-snack': isPosition(x, y, snack.coordinate.x, snack.coordinate.y), } ); const applySnakePosition = (prevState) => { - const directionFn = DIRECTION_TICKS[prevState.playground.direction]; - const coordinate = directionFn(prevState.snake.coordinate.x, prevState.snake.coordinate.y); + const isSnakeEating = getIsSnakeEating(prevState); + + const snakeHead = DIRECTION_TICKS[prevState.playground.direction]( + getSnakeHead(prevState.snake).x, + getSnakeHead(prevState.snake).y, + ); + + const snakeTail = isSnakeEating + ? prevState.snake.coordinates + : getSnakeWithoutStub(prevState.snake); + + const snackCoordinate = isSnakeEating + ? getRandomCoordinate() + : prevState.snack.coordinate; return { snake: { - coordinate, + coordinates: [snakeHead, ...snakeTail], + }, + snack: { + coordinate: snackCoordinate, }, }; }; @@ -74,16 +110,10 @@ class App extends Component { direction: DIRECTIONS.RIGHT, }, snake: { - coordinate: { - x: 20, - y: 10, - }, + coordinates: [getRandomCoordinate()], }, snack: { - coordinate: { - x: 25, - y: 10, - }, + coordinate: getRandomCoordinate(), } }; }