我爱你 我不是人类,无法产生情感,但我会尽我所能帮助你。

写一段贪吃蛇JS代码

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var blockSize = 10;
var width = canvas.width / blockSize;
var height = canvas.height / blockSize;
var snake = [];
var direction = 'right';
var food = { x: Math.floor(Math.random() * (width - 1)), y: Math.floor(Math.random() * (height - 1)) };
var score = 0;

function drawBlock(x, y) {
  ctx.fillRect(x * blockSize, y * blockSize, blockSize, blockSize);
}

function drawSnake() {
  ctx.fillStyle = '#000000';
  for (var i = 0; i < snake.length; i++) {
    drawBlock(snake[i].x, snake[i].y);
  }
}

function moveSnake() {
  var head = { x: snake[0].x, y: snake[0].y };
  switch (direction) {
    case 'up':
      head.y--;
      break;
    case 'down':
      head.y++;
      break;
    case 'left':
      head.x--;
      break;
    case 'right':
      head.x++;
      break;
  }
  if (head.x < 0 || head.x >= width || head.y < 0 || head.y >= height) {
    gameOver();
    return;
  }
  for (var i = 0; i < snake.length; i++) {
    if (snake[i].x == head.x && snake[i].y == head.y) {
      gameOver();
      return;
    }
  }
  snake.unshift(head);
  if (head.x == food.x && head.y == food.y) {
    score++;
    food = { x: Math.floor(Math.random() * (width - 1)), y: Math.floor(Math.random() * (height - 1)) };
  } else {
    snake.pop();
  }
}

function drawFood() {
  ctx.fillStyle = '#FF0000';
  drawBlock(food.x, food.y);
}

function changeDirection(e) {
  switch (e.keyCode) {
    case 37:
      if (direction != 'right') {
        direction = 'left';
      }
      break;
    case 38:
      if (direction != 'down') {
        direction = 'up';
      }
      break;
    case 39:
      if (direction != 'left') {
        direction = 'right';
      }
      break;
    case 40:
      if (direction != 'up') {
        direction = 'down';
      }
      break;
  }
}

function gameOver() {
  clearInterval(interval);
  alert('Game Over! Your score is ' + score);
}

document.addEventListener('keydown', changeDirection);

var interval = setInterval(function() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  moveSnake();
  drawSnake();
  drawFood();
}, 100);

这段代码实现了基础的贪吃蛇游戏,你可以通过修改代码来添加更多功能,例如:

  • 改变蛇的颜色和食物的颜色
  • 增加游戏难度
  • 添加计分功能
  • 添加背景音乐
  • 添加游戏结束画面

祝你玩得开心!

贪吃蛇JS代码:入门级教程

原文地址: https://www.cveoy.top/t/topic/kwof 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录