Vages / svelte-snake-workshop

A workshop that teaches Svelte and SvelteKit through making the classic game Snake
https://svelte-snake-workshop.vercel.app
MIT License
13 stars 12 forks source link

Use an object to keep track of the state instead of multiple variables #8

Open Vages opened 2 years ago

Vages commented 2 years ago

Because svelte can react to assignments within an object as well as to an object itself, perhaps it's best to replace this monstrosity with an object:

  // Letting the state variables go uninitialized is safe,
  // because they are initialized by resetGame before they are ever read
  let apple;
  let gameState;
  let headDirection;
  let headDirectionQueue;
  let score;
  let snake;
  let willGrow;

  function resetGame() {
    const initialSnake = [
      { x: 4, y: 4 },
      { x: 4, y: 3 },
      { x: 4, y: 2 },
    ];
    apple = drawRandomOpenSpace(BOARD_DIMENSIONS, initialSnake);
    gameState = GAME_STATES.START_SCREEN;
    headDirection = DIRECTION.SOUTH;
    headDirectionQueue = [];
    score = 0;
    snake = initialSnake;
    willGrow = false;
  }
Vages commented 2 years ago

I'm not sure if this will make anything better.