This is a simple snake game implementation in JavaScript using the modules format, including all basic features:
- simple navigation with ARROW keys (UP, DOWN, LEFT and RIGHT)
- avoid moving out of bounds
- random food placement
- food pickup
- growing when eating food
- scoring when eating food
- pause and unpause game with SPACE
- dying when touching own body
- dying when touching borders
- game over when dead, pauses game
- unpausing after game over resets the game
- high-score keeps track of highest score between games
- reversing direction if pressing opposite direction
The direction reversion logic reverses the snake direction based on the tail direction, turning the tail into the new head. For instance, if the body of the snake is performing a U shaped moviment going up and DOWN is pressed, the tail will become the head and the snake will start going up from the other end.
Another example is when the snake body is performing an L shape move, going up after going left, and DOWN is pressed. In that case, the snake will go right because the tail was going left and it is now the head and the direction was reversed.
To allow browsers to run modules locally, a static server is needed to avoid CORS rules from blocking the module imports.
For first time only, navigate to the root of the project and install the dependencies:
npm install
# OR
yarn install
To execute the included static server, run:
npm start
# OR
yarn start
Then open http://localhost:5000
in your browser.
Action | Keys |
---|---|
Starting | UP, DOWN, LEFT or RIGHT |
Moving | UP, DOWN, LEFT or RIGHT |
Pause toggle | SPACE |
Restarting on game over | SPACE |