|
|
当我们要写一个网页贪吃蛇游戏时,首先需要了解一下贪吃蛇游戏的基本规则和原理。贪吃蛇游戏是一个经典的游戏,玩家控制一条蛇在游戏区域内移动,吃到食物后身体变长,如果蛇碰到自己的身体或游戏区域的边界,则游戏结束。
下面是一个简单的网页贪吃蛇游戏代码示例:
- <!DOCTYPE html>
- <html>
- <head>
- <title>贪吃蛇游戏</title>
- <style>
- #gameArea {
- width: 400px;
- height: 400px;
- border: 1px solid black;
- }
- </style>
- </head>
- <body>
- <div id="gameArea"></div>
- <script>
- const gameArea = document.getElementById('gameArea');
- const blockSize = 20; // 每个方块的大小
- let snake = [{ x: 10, y: 10 }]; // 初始蛇身
- let food = { x: 15, y: 15 }; // 初始食物位置
- let direction = 'right'; // 初始移动方向
- function draw() {
- gameArea.innerHTML = ''; // 清空游戏区域
- // 画蛇
- snake.forEach(segment => {
- const snakeSegment = document.createElement('div');
- snakeSegment.style.width = blockSize + 'px';
- snakeSegment.style.height = blockSize + 'px';
- snakeSegment.style.backgroundColor = 'green';
- snakeSegment.style.position = 'absolute';
- snakeSegment.style.left = segment.x * blockSize + 'px';
- snakeSegment.style.top = segment.y * blockSize + 'px';
- gameArea.appendChild(snakeSegment);
- });
- // 画食物
- const foodBlock = document.createElement('div');
- foodBlock.style.width = blockSize + 'px';
- foodBlock.style.height = blockSize + 'px';
- foodBlock.style.backgroundColor = 'red';
- foodBlock.style.position = 'absolute';
- foodBlock.style.left = food.x * blockSize + 'px';
- foodBlock.style.top = food.y * blockSize + 'px';
- gameArea.appendChild(foodBlock);
- }
- function update() {
- // 根据方向移动蛇头
- let headX = snake[0].x;
- let headY = snake[0].y;
- if (direction === 'up') headY--;
- if (direction === 'down') headY++;
- if (direction === 'left') headX--;
- if (direction === 'right') headX++;
- // 更新蛇身
- snake.unshift({ x: headX, y: headY });
- // 判断是否吃到食物
- if (headX === food.x && headY === food.y) {
- // 生成新的食物
- food.x = Math.floor(Math.random() * (gameArea.clientWidth / blockSize));
- food.y = Math.floor(Math.random() * (gameArea.clientHeight / blockSize));
- } else {
- // 没有吃到食物,移除蛇尾
- snake.pop();
- }
- }
- function gameLoop() {
- update();
- draw();
- setTimeout(gameLoop, 100); // 控制游戏速度
- }
- gameLoop();
- // 监听键盘事件控制蛇的移动方向
- document.addEventListener('keydown', event => {
- if (event.key === 'ArrowUp' && direction !== 'down') direction = 'up';
- if (event.key === 'ArrowDown' && direction !== 'up') direction = 'down';
- if (event.key === 'ArrowLeft' && direction !== 'right') direction = 'left';
- if (event.key === 'ArrowRight' && direction !== 'left') direction = 'right';
- });
- </script>
- </body>
- </html>
复制代码
你可以将这段代码复制粘贴到一个新建的HTML文件中,然后在浏览器中打开这个HTML文件,就可以玩这个简单的网页贪吃蛇游戏了。希望你玩得开心! |
|