Getting my first interactions worked out was another great highlight. I decided to use two canvas elements - one for the food and one for the snake. It took some trial and error (and math) to get the coordinates figured out and detect intersections, but once they were working and a food piece moved when the snake's head touched it - it was so thrilling!
Challenges: Struggles While Building
I wanted to make a button that would clear the screen and reset all the points so a player could start a new game. However, when I first implemented this, the arrow keys were no longer registering in the canvas - instead, it moved the full window itself. When the player clicked the button, it took the keyboard focus away from the canvas and placed it on the whole page. Once I realized this, it was a quick fix to reset the focus when a new game was ready to start.
Mapping was the other big challenge I faced in this. I haven't worked with coordinates and intersections much, so this was a great experience. Figuring out if two items are in the same location and remembering to keep coordinates updated when a move is detected took a little work! But it was a great way to discover edge cases and experiment.
Takeaway: Lessons Learned
I was thrilled when this game first worked, and I still occasionally play it. It's a soothing way to spend a few minutes, and I can't help but try to get a higher score. Plus, I got to put the knowledge I was learning into active practice and have something new and fun to share!
During the building process, the biggest takeaways for me were:
Interacting with a web page can change the focus of the keyboard - it's an important thing to remember as a developer.
Another reminder that managing state is important, especially in a game where multiple things need to change on each press of a key. Tracking when two items intersect with each other, moving coordinates to new places, and updating the UI all rely on consistent, matching data.
A few things I'd like to improve in this project:
I want to make this a bit more like the original phone game and have the snake move continuously in the last pressed direction once the game starts. It would make it more challenging than it currently is. Plus, part of the fun of the game is that you can sometimes lose control!
Some of the sizes of items could stand to be adjusted as well. Currently, it can feel like it's taking a bit too long to go from one side of the game board to the other. Whether that means adjusting the amount the snake moves, the sizing of the snake and food, or reducing the size of the canvas, there's some room for improvement here.