Building the Classic Snake Game
Posted on March 23, 2023 • 3 minutes • 614 words
Table of contents
Lets build the classic snake game with html, css, and javascript.
Prompt
You are an AI programming assistant.
Write a javascript snake game.
First think step-by-step -- describe your plan for what to build in pseudocode, written out in great detail, then output the code in code blocks.
You will minimize any other prose.
Chat History
You are an AI programming assistant.
Write a javascript snake game.
First think step-by-step – describe your plan for what to build in pseudocode, written out in great detail, then output the
- html
- css
- javascript code in separate code blocks. You will minimize any other prose.
ChatGPT »
// Pseudocode
-
Initialize game variables and objects (canvas, context, snake, food, game speed)
-
Create a game loop function
-
Inside game loop:
a. Clear the canvas
b. Draw the snake
c. Update the snake’s position
d. Check for collisions (snake with itself or wall)
e. If collision, end the game
f. Draw the food
g. Check if the snake ate the food
h. If the snake ate the food, create new food and increase snake length
i. Update game speed based on score
j. Call game loop again after a delay based on game speed
-
Set up event listeners for arrow keys to change snake direction
-
Start the game loop
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snakegame.js"></script>
</body>
</html>
CSS:
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #222;
}
canvas {
border: 4px solid #fff;
}
Save this CSS as “styles.css” and ensure it is in the same folder as your HTML and JavaScript files.
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const gridSize = 20;
const snakeColor = "#0f0";
const foodColor = "#f00";
class Snake {
constructor() {
this.body = [{x: gridSize * 5, y: gridSize * 5}];
this.direction = {x: 0, y: -gridSize};
this.newDirection = {...this.direction};
}
changeDirection(x, y) {
if (x !== -this.direction.x || y !== -this.direction.y) {
this.newDirection = {x, y};
}
}
update() {
this.direction = {...this.newDirection};
const newX = this.body[0].x + this.direction.x;
const newY = this.body[0].y + this.direction.y;
this.body.unshift({x: newX, y: newY});
this.body.pop();
}
grow() {
this.body.push({...this.body[this.body.length - 1]});
}
checkCollision() {
for (let i = 1; i < this.body.length; i++) {
if (this.body[0].x === this.body[i].x && this.body[0].y === this.body[i].y) {
return true;
}
}
return this.body[0].x < 0 || this.body[0].x >= canvas.width || this.body[0].y < 0 || this.body[0].y >= canvas.height;
}
draw() {
ctx.fillStyle = snakeColor;
for (const segment of this.body) {
ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
}
}
}
class Food {
constructor(snake) {
do {
this.x = Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize;
this.y = Math.floor(Math.random() * (canvas.height / gridSize)) * gridSize;
} while (this.checkCollision(snake));
}
checkCollision(snake) {
for (const segment of snake.body) {
if (this.x === segment.x && this.y === segment.y) {
return true;
}
}
return false;
}
draw() {
ctx.fillStyle = foodColor;
ctx.fillRect(this.x, this.y, gridSize, gridSize);
}
}
const snake = new Snake();
let food = new Food(snake);
let gameSpeed = 200;
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.draw();
snake.update();
if (snake.checkCollision()) {
alert("Game Over");
return;
}
food.draw();
if (snake.body[0].x === food.x && snake.body[0].y === food.y) {
snake.grow();
food = new Food(snake);
gameSpeed = Math.max(50, gameSpeed - 5);
}
setTimeout(gameLoop, gameSpeed);
}
document.addEventListener("keydown", event => {
switch (event.key) {
case "ArrowUp":
snake.changeDirection(0, -gridSize);
break;
case "ArrowDown":
snake.changeDirection(0, gridSize);
break;
case "ArrowLeft":
snake.changeDirection(-gridSize, 0);
break;
case "ArrowRight":
snake.changeDirection(gridSize, 0);
break;
}
});
gameLoop();
This is the complete JavaScript code for the snake game. Save it as “snakegame.js” and make sure it is in the same folder as the HTML and CSS files.
Happy Prompting