Skip to content

Commit

Permalink
part 04
Browse files Browse the repository at this point in the history
  • Loading branch information
rwieruch committed Sep 2, 2017
1 parent 0b00398 commit 9196a55
Showing 1 changed file with 42 additions and 12 deletions.
54 changes: 42 additions & 12 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
};
};
Expand All @@ -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(),
}
};
}
Expand Down

0 comments on commit 9196a55

Please sign in to comment.