Written by Vasi
January 29
We all have fond memories of playing the classic 8-bit snake game. I decided to recreate this nostalgic experience using Svelte, to learn and apply new techniques.
Dive into the pixelated world of my snake game! Use the arrow keys on the screen or WASD and the arrow keys on the keyboard to control the snake as it slithers around the screen, consuming green fruits to grow longer.
The game is fairly easy at the start as the board is large but gets more interesting as more fruits are consumed.
Current Score: 0
Best Score: 0
Snake Game
The name “8-Pixel Snake” is not just catchy; it reflects the game’s essence. Each snake body segment and the fruit are composed of eight pixel squares, adding a retro charm to the experience.
In my other post Tic-tac-toe with Svelte I briefly talked about the new runes system of Svelte 5 to declare an reactive state.In that example the runes that helped me achieve all the needed reactivity for that game was $state
and $props
.These runes are fundamental to most Svelte components , for this game I had to go and explore other functionalities of the framwork to get the desired result.
Tween
To achieve a fluid snake movement, I employed Svelte’s Tween
motion class, which smoothly interpolates values. So the snake body is a instance of a Tween class that and will move smoothly to its target value.
$effect
Since the game is rendered on a canvas, I used the $effect
rune to track changes in the snake’s position and update the canvas accordingly.The effect rune re-runs the function every time the tween instance chnages , so the canvas can be updated but also the game state can be checked.
Developing this game was a learning experience, as Svelte’s Tween
functionality is relatively new, and there aren’t many examples to follow. However, through experimentation and perseverance, I was able to overcome these challenges and create a working game.
I have some ideas for future improvements, such as introducing smarter fruit generation patterns and refining the snake’s movement mechanics.
Building this simple game with Svelte was a rewarding experience. It allowed me to explore and apply new Svelte features, while also revisiting a childhood classic.