Learning html, javascript, and css by making a snake game. i followed Bro Code tutorial on youtube all credits to him. While playing around with the code, i managed to fix some bug i found in the code. The fixes will be shown below the game overview. I changed the game a little bit so that there is no border. Everytime the snake is touching the border of the game, it will automatically teleport the snake to the opposite of the border. Like the image below.
The game will automatically start after you copy the html file path to the browser. You can move the snake by using arrows key. The objective is to eat the apple (the red block) and to get highest score as possible.
Your snake will get bigger as you it more apple.
As your snake gets bigger, you should be careful to not eat yourself. If you do, the game over text will pop up and the game will stop. You can restart the game by pressing the reset button.
Everytime you press reset, the speed of the snake increase. This has something to do with how the setTimout method works. In order to fix that, i created a global variable and assign the variable in the nextTick function. After that, i can clear it everytime the game reset.
Sometimes the food will spawn inside the snake body. In order to fix that, we simply need to check if the createFood function created the foodX and foodY coordinate inside the snake body. If it is, we call the createFood function again. This implementation is definitely not the greatest, there could be a worst case possibility where the createFood function keep spawning the food inside the snake body. But this works for now at least.
You can actually press the button fast enough so that the game will think that the snake is eating itself (a bit hard to explain by words). In this image, the snake is going right. If you press down and then left fast enough. The game will actually think you are moving left. I think this has something to do with how actionListener is instant and the game itself are programmed to run a check every 100 ms.
Well we can fix it by using some variable that will tell are we allowed to take input right now or not.
This will fix the bug