This is a DOM-based game of Snake that I wrote in JavaScript over a decade ago. It was made to have sort of a nostalgic feel to it.
You can now play and edit the game live in codesandbox:
https://codesandbox.io/s/github/patorjk/JavaScript-Snake?file=/index.html
2025: Looks like CSS inside the sandbox isn't working properly, in the game it works fine though
On first load sometimes the game frame will not load correctly and you'll need to press the refresh icon above its display panel to get the game to show.
Original game is located here:
http://patorjk.com/games/snake
The index.html file should give an idea of how to use this code. However, below you can see how to initialize it into any div within a webpage.
const mySnakeBoard = new SNAKE.Board( {
boardContainer: "game-area",
fullScreen: false,
width: 580,
height:400
});
The comments within the source code are formatted a little strange because at the time I was playing around with YUI Doc which generates documentation from code. Kind of sucks that there's so much churn in the JavaScript world. However, I'm glad the rest of the code doesn't use any external libraries, as this game still works the same after over a decade.
Clone project, then at command line:
npx parcel src/index.html
Runs on http://localhost:1234
If you want to control the snake via an AI algorithm see the ai-init.js and ai-example files.
Essentially all you have to do is run params.startAIGame();
when initializing and pass in a moveSnakeWithAI
method
which is run before the snake does each move.
moveSnakeWithAI: ({
grid,
snakeHead,
currentDirection,
isFirstGameMove,
setDirection,
}) => {
/*
Direction:
0
3 1
2
*/
// This is NOT a real hamiltonian cycle. It misses some values, I'm just including this here as an example of
// a look-up type table that you could do.
const hamiltonianCycleGrid = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 0],
[0, 0, 2, 3, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 0],
[0, 0, 2, 0, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0],
[0, 0, 2, 0, 2, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0],
[0, 0, 3, 0, 3, 3, 3, 3, 0, 3, 0, 3, 0, 3, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
const newDirection = hamiltonianCycleGrid[snakeHead.row][snakeHead.col];
setDirection(newDirection);
},
onInit: (params) => {
params.startAIGame(); // This start an AI game
},
Thanks goes to these people: (emoji key)