一个网页贪吃蛇代码

当然可以。这是一个基本的贪吃蛇游戏的HTML和JavaScript代码:

<!DOCTYPE html>
<html>
<body>

<canvas id="canvas" width="400" height="400" style="background-color:#000"></canvas>

<script>
// Game variables
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var size = 20;
var direction;
var score;
var snake = [];
var food = null;

// Game functions
function loop() {
      
      
  update();
  draw();
  if (gameOver()) {
      
      
    reset();
  }
}

function update() {
      
      
  var head = Object.assign({
      
      }, snake[0]); // Start with the head
  switch(direction) {
      
      
    case 'left':
      head.x -= size;
      break;
    case 'up':
      head.y -= size;
      break;
    case 'right':
      head.x += size;
      break;
    case 'down':
      head.y += size;
      break;
  }
  snake.unshift(head); // Add the new head to the snake

  if (food && food.x === head.x && food.y === head.y) {
      
       // food eaten
    score++;
    food = null;
  } else {
      
       // normal move
    snake.pop(); // remove the tail
  }

  if (!food) {
      
       // no food, create one
    food = {
      
      
      x: Math.floor(Math.random() * canvas.width / size) * size,
      y: Math.floor(Math.random() * canvas.height / size) * size,
    };
  }
}

function draw() {
      
      
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'lightgreen';
  snake.forEach(function(cell) {
      
      
    ctx.fillRect(cell.x, cell.y, size, size);
  });
  if (food) {
      
      
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x, food.y, size, size);
  }
}

function gameOver() {
      
      
  var head = snake[0];
  return head.x < 0 || head.y < 0 || head.x >= canvas.width || head.y >= canvas.height || snake.slice(1).some(function(cell) {
      
      
    return cell.x === head.x && cell.y === head.y;
  });
}

function reset() {
      
      
  direction = 'right';
  score = 0;
  snake = [{
      
      x: canvas.width / 2, y: canvas.height / 2}];
  food = null;
}

// Event handlers
window.addEventListener('keydown', function(e) {
      
      
  switch(e.key) {
      
      
    case 'ArrowUp':
      direction = 'up';
      break;
    case 'ArrowDown':
      direction = 'down';
      break;
    case 'ArrowLeft':
      direction = 'left';
      break;
    case 'ArrowRight':
      direction = 'right';
      break;
  }
});

// Game loop
reset();
setInterval(loop, 200);
</script>

</body>
</html>

此代码在一个网页上创建了一个400像素宽高的方形画布,并在其上运行一个简单的贪吃蛇游戏。蛇的身体每个部分是一个20像素的正方形,蛇每次移动都会前进一格。你可以用箭头键来控制蛇的移动。蛇每吃掉一个食物,得分就会增加,然后食物就会在一个新的位置再次出现。

猜你喜欢

转载自blog.csdn.net/m0_57236802/article/details/131615537