MASIGNASUKAv102
6510051498749449419

Snake game code

Snake game code
Add Comments
Sunday, April 23, 2023

Html

<html>
  <head>
    <title>Snake Game</title>
    <style>
      #canvas {
        border: 1px solid #ccc;
      }
    </style>
  </head>
  <body>
    <canvas height="400" id="canvas" width="400"></canvas>
    <script src="snake.js"></script>
  </body>
</html>
CSS
body {
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
  margin: 0 auto;
}
JAVAScript
// Initialize the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// Set up the snake properties
var snake = {
  x: 10,
  y: 10,
  size: 20,
  speed: 10,
  direction: 'right',
  body: []
};

// Set up the food properties
var food = {
  x: Math.floor(Math.random() * 38 + 1) * 10,
  y: Math.floor(Math.random() * 38 + 1) * 10,
  size: 20
};

// Draw the snake
function drawSnake() {
  // Add the current position of the snake's head to the beginning of the body array
  snake.body.unshift({ x: snake.x, y: snake.y });

  // Remove the last position of the snake's body to simulate movement
  if (snake.body.length > snake.size) {
    snake.body.pop();
  }

  // Draw the snake's body
  for (var i = 0; i < snake.body.length; i++) {
    ctx.fillStyle = '#000';
    ctx.fillRect(snake.body[i].x, snake.body[i].y, snake.size, snake.size);
  }
}

// Move the snake
function moveSnake() {
  // Update the snake position based on the direction
  if (snake.direction === 'right') {
    snake.x += snake.speed;
  } else if (snake.direction === 'left') {
    snake.x -= snake.speed;
  } else if (snake.direction === 'up') {
    snake.y -= snake.speed;
  } else if (snake.direction === 'down') {
    snake.y += snake.speed;
  }
}

// Draw the food
function drawFood() {
  ctx.fillStyle = '#f00';
  ctx.fillRect(food.x, food.y, food.size, food.size);
}

// Check for collision between the snake and the food
function checkCollision() {
  if (snake.x < food.x + food.size &&
      snake.x + snake.size > food.x &&
      snake.y < food.y + food.size &&
      snake.y + snake.size > food.y) {
    // The snake has collided with the food, so increase its size and generate a new food location
    snake.size++;
    food.x = Math.floor(Math.random() * 38 + 1) * 10;
    food.y = Math.floor(Math.random() * 38 + 1) * 10;
  }
}

// Game loop
function gameLoop() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the snake and move it
  drawSnake();
  moveSnake();

  // Draw the food and check for collision
  drawFood();
  checkCollision();

  // Update the game loop
  requestAnimationFrame(gameLoop);
}

// Handle keyboard input to change the direction of the snake
document