Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const updateGameState = () => {
- // If the user chose a valid direction update the snake direction.
- const chosenDirectionIsValid = state.chosenDirection !== undefined
- && !wouldEatItself(
- arenaSize,
- state.snake.body,
- state.chosenDirection
- );
- if (chosenDirectionIsValid) {
- state.snake.direction = state.chosenDirection;
- }
- state.chosenDirection = undefined;
- // If the snake stands still, the game is frozen.
- if (state.snake.direction === Direction.NONE) {
- return;
- }
- // If by moving the head we get a collision with the body,
- // the snake dies.
- const body = initial(state.snake.body);
- const head = last(state.snake.body);
- const newHead = moveTo(head, state.snake.direction, arenaSize);
- if (body.some(part => coincident(part, newHead))) {
- state.snake.status = Status.DEAD;
- return;
- }
- // If the snake is dead, the game is frozen.
- if (state.snake.status === Status.DEAD) {
- return;
- }
- // If the snake eats the food, consume it
- // and increment score and stocks.
- if (
- state.food !== undefined
- && coincident(newHead, state.food.coords)
- ) {
- state.score += state.food.strength;
- state.snake.stocks = state.food.strength;
- state.food = undefined;
- }
- // Make sure there is always some food to eat.
- if (state.food === undefined) {
- state.food = {
- coords: {
- x: random(0, arenaSize - 1),
- y: random(0, arenaSize - 1),
- },
- strength: random(1, 5),
- };
- }
- // Update the snake position and consume one stock, if available.
- const newBody = state.snake.stocks > 0
- ? state.snake.body
- : tail(state.snake.body);
- state.snake.body = [...newBody, newHead];
- state.snake.stocks = Math.max(0, state.snake.stocks - 1);
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement