当前位置: 首页 > news >正文

不到200行代码,一键写出简单贪吃蛇网页游戏!附详细代码!快来看看吧!

​哈喽大家好,这里是大白百宝阁,每天分享一段小代码~

今天要分享的是,不到200行代码,制作html版贪吃蛇,效果如下:

游戏结束后,还会显示:

代码如下:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>贪吃蛇游戏</title><style>body {display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;background-color: #333;}canvas {border: 1px solid #fff;}</style>
</head>
<body><canvas id="gameCanvas" width="400" height="400"></canvas><script>const canvas = document.getElementById('gameCanvas');const ctx = canvas.getContext('2d');// 常量const GRID_SIZE = 20;const CELL_SIZE = canvas.width / GRID_SIZE;// 蛇的初始化let snake = [{ x: 5, y: 10 },{ x: 4, y: 10 },{ x: 3, y: 10 }];// 食物的初始化let food = {x: Math.floor(Math.random() * GRID_SIZE),y: Math.floor(Math.random() * GRID_SIZE)};let direction = 'right';let score = 0;let gameInterval;let gameSpeed = 300;// 移动蛇function moveSnake() {const 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 === food.x && head.y === food.y) {score++;generateFood();increaseGameSpeed();} else {snake.pop();}snake.unshift(head);// 检查是否撞到墙壁或自己if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE || checkCollision(head)) {stopGame();alert(`游戏结束! 你的得分是 ${score}`);resetGame();}}// 检查蛇头是否撞到自己function checkCollision(head) {for (let i = 1; i < snake.length; i++) {if (head.x === snake[i].x && head.y === snake[i].y) {return true;}}return false;}// 绘制蛇function drawSnake() {ctx.clearRect(0, 0, canvas.width, canvas.height);drawGrid();ctx.fillStyle = '#fff';snake.forEach(segment => {ctx.fillRect(segment.x * CELL_SIZE, segment.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);});}// 绘制食物function drawFood() {ctx.fillStyle = '#f00';ctx.fillRect(food.x * CELL_SIZE, food.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);}// 绘制网格function drawGrid() {ctx.strokeStyle = '#444';for (let x = 0; x <= canvas.width; x += CELL_SIZE) {ctx.beginPath();ctx.moveTo(x, 0);ctx.lineTo(x, canvas.height);ctx.stroke();}for (let y = 0; y <= canvas.height; y += CELL_SIZE) {ctx.beginPath();ctx.moveTo(0, y);ctx.lineTo(canvas.width, y);ctx.stroke();}}// 生成新的食物function generateFood() {food = {x: Math.floor(Math.random() * GRID_SIZE),y: Math.floor(Math.random() * GRID_SIZE)};}// 增加游戏速度function increaseGameSpeed() {gameSpeed = Math.max(gameSpeed - 20, 100);stopGame();startGame();}// 重置游戏function resetGame() {snake = [{ x: 5, y: 10 },{ x: 4, y: 10 },{ x: 3, y: 10 }];direction = 'right';score = 0;gameSpeed = 300;generateFood();startGame();}// 开始游戏function startGame() {gameInterval = setInterval(function() {moveSnake();drawSnake();drawFood();}, gameSpeed);}// 停止游戏function stopGame() {clearInterval(gameInterval);}// 监听键盘事件改变蛇的移动方向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;}});// 开始游戏resetGame();</script>
</body>
</html>

大白会在下一篇文章中,详细解释该代码的运作,并且给出优化UI和性能的方案,关注我,我们在下一篇文章见~


http://www.mrgr.cn/news/23239.html

相关文章:

  • Linux IO模型:IO多路复用
  • Android源码 ota升级
  • 2-89 基于matlab的图像去噪方法
  • 利士策分享,克服生活中的困难:走好勇攀高峰的每一步
  • 计算机的发展史和基本结构
  • 我的第3个AI项目-Advanced RAG with Gemma, Weaviate, and LlamaIndex
  • Linux 中 Tail 命令的 9 个实用示例
  • 【华为OD流程】性格测试选项+注意事项
  • 从“纯血鸿蒙”看“自研系统”有多难
  • 洛谷 P10798 「CZOI-R1」消除威胁
  • Android使用Room后无法找到字符BR
  • 选择网站服务器有哪几种类型?
  • C8T6超绝模块--USART串口通信
  • docker conda
  • 分组注解和自定义注解及分页查询
  • 4.人事管理系统(springbootvue项目)
  • AUTOSAR_EXP_ARAComAPI的5章笔记(4)
  • 【重学 MySQL】二十二、limit 实现分页
  • 手把手带你拿捏指针(1)
  • Pytorch添加自定义算子之(13)-CMake与Ninja编译Pytorch自定义算子