我很乐意帮助您编写一个网页版贪吃蛇的代码。在下面的代码中,我使用了HTML、CSS和JavaScript来创建游戏界面和逻辑。请注意,在此代码中没有使用任何框架或库。

HTML代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset='UTF-8'>
    <title>贪吃蛇游戏</title>
    <link rel='stylesheet' href='style.css'>
  </head>
  <body>
    <div class='game-container'>
      <div class='game-board'></div>
      <div class='game-score'>得分:<span id='score'>0</span></div>
    </div>
    <script src='script.js'></script>
  </body>
</html>

CSS代码:

.game-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.game-board {
  width: 400px;
  height: 400px;
  border: 2px solid black;
  position: relative;
}

.game-score {
  margin-top: 10px;
  font-size: 20px;
}

.snake-head {
  width: 20px;
  height: 20px;
  background-color: green;
  position: absolute;
}

.snake-body {
  width: 20px;
  height: 20px;
  background-color: lightgreen;
  position: absolute;
}

.food {
  width: 20px;
  height: 20px;
  background-color: red;
  position: absolute;
}

JavaScript代码:

// 获取游戏板块和分数板块
const gameBoard = document.querySelector('.game-board');
const scoreBoard = document.querySelector('#score');

// 设置游戏板块的大小和格子数量
const boardSize = 400;
const gridSize = 20;
const gridCount = boardSize / gridSize;

// 初始化蛇和食物的位置和方向
let snake = [{ x: 5, y: 5 }, { x: 4, y: 5 }];
let food = { x: 10, y: 10 };
let direction = 'right';

// 初始化得分
let score = 0;

// 生成游戏板块的格子
for (let i = 0; i < gridCount * gridCount; i++) {
  const grid = document.createElement('div');
  grid.classList.add('grid');
  gameBoard.appendChild(grid);
}

// 获取所有格子并设置它们的位置
const grids = document.querySelectorAll('.grid');
grids.forEach((grid, index) => {
  const x = index % gridCount;
  const y = Math.floor(index / gridCount);
  grid.style.left = x * gridSize + 'px';
  grid.style.top = y * gridSize + 'px';
});

// 设置蛇和食物的位置
snake.forEach(segment => {
  const x = segment.x * gridSize;
  const y = segment.y * gridSize;
  const snakeSegment = document.createElement('div');
  snakeSegment.classList.add('snake-body');
  snakeSegment.style.left = x + 'px';
  snakeSegment.style.top = y + 'px';
  gameBoard.appendChild(snakeSegment);
});

const foodElement = document.createElement('div');
foodElement.classList.add('food');
foodElement.style.left = food.x * gridSize + 'px';
foodElement.style.top = food.y * gridSize + 'px';
 gameBoard.appendChild(foodElement);

// 移动蛇和食物的函数
function moveSnake() {
  // 计算蛇头的新位置
  const head = snake[0];
  let newHead = {};
  switch (direction) {
    case 'up':
      newHead = { x: head.x, y: head.y - 1 };
      break;
    case 'down':
      newHead = { x: head.x, y: head.y + 1 };
      break;
    case 'left':
      newHead = { x: head.x - 1, y: head.y };
      break;
    case 'right':
      newHead = { x: head.x + 1, y: head.y };
      break;
  }

  // 判断蛇是否吃到了食物
  if (newHead.x === food.x && newHead.y === food.y) {
    // 增加得分
    score += 10;
    scoreBoard.innerText = score;

    // 生成新的食物
    food = {
      x: Math.floor(Math.random() * gridCount),
      y: Math.floor(Math.random() * gridCount)
    };
    foodElement.style.left = food.x * gridSize + 'px';
    foodElement.style.top = food.y * gridSize + 'px';
  } else {
    // 移除蛇尾
    const tail = snake.pop();
    const tailElement = document.querySelector(`.snake-body:nth-child(${snake.length + 1})`);
    tailElement.remove();
  }

  // 判断蛇是否撞墙或撞到自己
  if (newHead.x < 0 || newHead.x >= gridCount || newHead.y < 0 || newHead.y >= gridCount) {
    clearInterval(intervalId);
    alert('游戏结束!');
    return;
  }
  if (snake.some(segment => segment.x === newHead.x && segment.y === newHead.y)) {
    clearInterval(intervalId);
    alert('游戏结束!');
    return;
  }

  // 添加新的蛇头
  snake.unshift(newHead);
  const newHeadElement = document.createElement('div');
  newHeadElement.classList.add('snake-head');
  newHeadElement.style.left = newHead.x * gridSize + 'px';
  newHeadElement.style.top = newHead.y * gridSize + 'px';
  gameBoard.appendChild(newHeadElement);
}

// 监听键盘按键事件
document.addEventListener('keydown', event => {
  switch (event.key) {
    case 'ArrowUp':
      if (direction !== 'down') {
        direction = 'up';
      }
      break;
    case 'ArrowDown':
      if (direction !== 'up') {
        direction = 'down';
      }
      break;
    case 'ArrowLeft':
      if (direction !== 'right') {
        direction = 'left';
      }
      break;
    case 'ArrowRight':
      if (direction !== 'left') {
        direction = 'right';
      }
      break;
  }
});

// 每隔200毫秒移动蛇
const intervalId = setInterval(moveSnake, 200);

这个代码生成了一个400x400像素的游戏界面,其中包含一个游戏板块和一个分数板块。玩家可以通过键盘上的箭头键来控制蛇的方向。蛇的长度和食物的位置都是随机生成的。当蛇吃到食物时,得分会增加10分,同时生成一个新的食物。如果蛇撞到墙或撞到自己,游戏就会结束。

网页版贪吃蛇游戏代码 - 使用HTML、CSS和JavaScript实现

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

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