Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. const updateGameState = () => {
  2. // If the user chose a valid direction update the snake direction.
  3. const chosenDirectionIsValid = state.chosenDirection !== undefined
  4. && !wouldEatItself(
  5. arenaSize,
  6. state.snake.body,
  7. state.chosenDirection
  8. );
  9. if (chosenDirectionIsValid) {
  10. state.snake.direction = state.chosenDirection;
  11. }
  12. state.chosenDirection = undefined;
  13.  
  14. // If the snake stands still, the game is frozen.
  15. if (state.snake.direction === Direction.NONE) {
  16. return;
  17. }
  18.  
  19. // If by moving the head we get a collision with the body,
  20. // the snake dies.
  21. const body = initial(state.snake.body);
  22. const head = last(state.snake.body);
  23. const newHead = moveTo(head, state.snake.direction, arenaSize);
  24. if (body.some(part => coincident(part, newHead))) {
  25. state.snake.status = Status.DEAD;
  26. return;
  27. }
  28.  
  29. // If the snake is dead, the game is frozen.
  30. if (state.snake.status === Status.DEAD) {
  31. return;
  32. }
  33.  
  34. // If the snake eats the food, consume it
  35. // and increment score and stocks.
  36. if (
  37. state.food !== undefined
  38. && coincident(newHead, state.food.coords)
  39. ) {
  40. state.score += state.food.strength;
  41. state.snake.stocks = state.food.strength;
  42. state.food = undefined;
  43. }
  44.  
  45. // Make sure there is always some food to eat.
  46. if (state.food === undefined) {
  47. state.food = {
  48. coords: {
  49. x: random(0, arenaSize - 1),
  50. y: random(0, arenaSize - 1),
  51. },
  52. strength: random(1, 5),
  53. };
  54. }
  55.  
  56. // Update the snake position and consume one stock, if available.
  57. const newBody = state.snake.stocks > 0
  58. ? state.snake.body
  59. : tail(state.snake.body);
  60. state.snake.body = [...newBody, newHead];
  61. state.snake.stocks = Math.max(0, state.snake.stocks - 1);
  62. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement