In this project, I built a simple snake game. It hasn't been totally done yet, as the head can cross its body.
Tech used: DOM manipulation and jQuery
In the html, I only constructed two divs. One is for the board, in which we play the game. The other is for counting scores.
- main.js
- I used querySelector to get the html element for the board, so I can pass it into the constructor of Apple and Head.
- I created corresponding instances for Apple, Head and Body.
- In the end, I added an eventListener so I can capture the keyboard instructions.
- Head.js
- constructor(el). In the constructor function, I created a html element and appended it to the el, so for a given Head instance, there will be a corresponding html element, where we can show it in the UI. I also added some properties like speed, direction, target. One thing worth noting is at the end, I used a setTimeOut() where I called the move() method, so the snake can move after being created.
- move(). In this method, I checked if the snake should move to its next position and if it gets an apple. The main logic of the game were all in this method. If I have time to refactor, I will separate some logic like checkGetApple, checkOutRange in individual methods.
- Apple.js
- constructor(el). Similar to the Head. Created a html element so I can change its position on the board.
- resetApple(). Randomly give it a new position.
- Body.js
- constructor(head). A body instance will always be linked to a head instance. It also has a length property.
- show(). In this method, I showed the body nodes. Everytime show the body nodes, I cleared the past body nodes. And then I added current body nodes as html elements. The position of these nodes would be retrieved from the path of the head. What I'm doing can work, but is not efficient, I should refactor in the future.