Untitled

 avatar
unknown
plain_text
6 months ago
2.0 kB
3
Indexable
// Define the canvas
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

// Set the initial position and size of the snake
let snake = [{ x: 10, y: 10 }];
const snakeSize = 20;

// Set the initial direction of the snake
let direction = "right";

// Create the food for the snake
let food = { x: Math.floor(Math.random() * 20) * snakeSize, y: Math.floor(Math.random() * 20) * snakeSize };

// Function to draw the snake
function drawSnake() {
  ctx.fillStyle = "green";
  for (let i = 0; i < snake.length; i++) {
    ctx.fillRect(snake[i].x, snake[i].y, snakeSize, snakeSize);
  }
}

// Function to draw the food
function drawFood() {
  ctx.fillStyle = "red";
  ctx.fillRect(food.x, food.y, snakeSize, snakeSize);
}

// Function to update the game
function update() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Move the snake
  let head = { x: snake[0].x, y: snake[0].y };
  if (direction === "right") head.x += snakeSize;
  if (direction === "left") head.x -= snakeSize;
  if (direction === "up") head.y -= snakeSize;
  if (direction === "down") head.y += snakeSize;
  snake.unshift(head);

  // Check if the snake has eaten the food
  if (snake[0].x === food.x && snake[0].y === food.y) {
    // Generate new food
    food = { x: Math.floor(Math.random() * 20) * snakeSize, y: Math.floor(Math.random() * 20) * snakeSize };
  } else {
    // Remove the tail of the snake
    snake.pop();
  }

  // Draw the snake and food
  drawSnake();
  drawFood();
}

// Function to handle key presses
function handleKeyPress(event) {
  if (event.keyCode === 37 && direction !== "right") direction = "left";
  if (event.keyCode === 38 && direction !== "down") direction = "up";
  if (event.keyCode === 39 && direction !== "left") direction = "right";
  if (event.keyCode === 40 && direction !== "up") direction = "down";
}

// Start the game
document.addEventListener("keydown", handleKeyPress);
setInterval(update, 100);
Editor is loading...
Leave a Comment