snake game in js
- User
snake game in js
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
snake game in js
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure, I'd be happy to help you with a snake game in JavaScript.
Snake games are a classic example of a simple yet engaging game that can be implemented using JavaScript. Here's a basic outline of the steps involved:
Here's some sample code to get you started:
// create the canvas element
const canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
// get the canvas element
const ctx = canvas.getContext('2d');
// define the snake variables
let snake = {
head: { x: 250, y: 250 },
body: [
{ x: 250, y: 225 },
{ x: 225, y: 225 },
{ x: 200, y: 225 },
{ x: 175, y: 225 },
{ x: 150, y: 225 },
{ x: 125, y: 225 },
{ x: 100, y: 225 },
{ x: 75, y: 225 },
{ x: 50, y: 225 },
{ x: 25, y: 225 }
],
size: 10,
speed: 5
};
// define the food variables
let food = {
x: Math.floor(Math.random() * canvas.width),
y: Math.floor(Math.random() * canvas.height)
};
// function to draw the snake
function drawSnake() {
ctx.fillStyle = 'black';
ctx.fillRect(snake.head.x - snake.size / 2, snake.head.y - snake.size / 2, snake.size, snake.size);
ctx.beginPath();
ctx.moveTo(snake.head.x, snake.head.y);
for (let i = 1; i < snake.body.length; i++) {
ctx.lineTo(snake.body[i].x, snake.body[i].y);
}
ctx.closePath();
ctx.fill();
}
// function to draw the food
function drawFood() {
ctx.fillStyle = 'red';
ctx.fillRect(food.x - 5, food.y - 5, 10, 10);
}
// function to check for collisions
function checkCollision(snake, walls) {
// check for collision with left wall
if (snake.body[0].x - snake.size / 2 < 0) {
return true;
}
// check for collision with right wall
if (snake.body[0].x + snake.size / 2 > canvas.width) {
return true;
}
// check for collision with top wall
if (snake.body[0].y - snake.size / 2 < 0) {
return true;
}
// check for collision with bottom wall
if (snake.body[0].y + snake.size / 2 > canvas.height) {
return true;
}
// check for collision with other snake parts
for (let i = 1; i < snake.body.length; i++) {
if (i !== 0 && snake.body[0].x === snake.body[i].x && snake.body[0].y === snake.body[i].y) {
return true;
}
}
return false;
}
// function to move the snake
function moveSnake() {