Play the classic retro Snake game. Eat food, grow longer, and set new high scores entirely in your browser.
When a snake gets to be 50 segments long, moving it forward one step might seem like a heavy operation. Do you have to update the X/Y coordinates of all 50 segments in memory on every single frame?
A beginner might write a loop: for (let i = snake.length - 1; i > 0; i--) snake[i] = snake[i-1];. This shifts every single segment to the position of the one in front of it.
While this works, it takes O(N) time, meaning the longer the snake gets, the slower the game runs, eventually causing lag when the snake is huge.
In computer science, a snake is perfectly modeled using a Deque (pronounced "deck"). Instead of updating 50 segments, the game engine only ever does two things on a tick:
push()es it to the front of the array (the new head).pop()s the last segment off the back of the array (the tail).Because the middle 48 segments never actually changed their coordinates, the operation always takes exactly the same amount of time, O(1), whether the snake is 3 segments long or 3,000 segments long.
When the snake eats an apple, the engine simply skips Step 2 for that frame, causing the snake to grow by exactly one segment.
Why is updating the coordinates of every snake segment on every frame a bad approach?