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

使用js和canvas实现简单的网页贪吃蛇小游戏

玩法介绍

点击开始游戏后,使用键盘上的↑↓←→控制移动,吃到食物增加长度,碰到墙壁或碰到自身就游戏结束
在这里插入图片描述
在这里插入图片描述

代码实现

代码比较简单,直接阅读注释即可,复制即用

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Snake Game</title><style>body {margin: 0;overflow: hidden;}canvas {display: block;position: absolute;top: 0;left: 0;z-index: 1;background-color: #000;}.start-screen {position: absolute;top: 0;left: 0;width: 100%;height: 100%;background-color: rgba(0, 0, 0, 0.8);color: white;text-align: center;z-index: 2;display: flex;align-items: center;justify-content: center;font-size: 24px;}button {font-size: 24px;padding: 10px 20px;cursor: pointer;}</style>
</head>
<body><div class="start-screen"><h1>Snake Game</h1><button id="startButton">Start Game</button></div><canvas id="gameCanvas" width="800" height="600"></canvas><script>const canvas = document.getElementById('gameCanvas');const ctx = canvas.getContext('2d');// 设置 Canvas 为全屏canvas.width = window.innerWidth;canvas.height = window.innerHeight;// 方块大小const blockSize = 20;// 游戏状态let snake = [{ x: 100, y: 100 }];let food = { x: 200, y: 200 };let direction = 'right';let score = 0;let isRunning = false;// 游戏速度const speed = 100;// 绘制蛇function drawSnake() {ctx.fillStyle = '#0f0';snake.forEach(segment => {ctx.fillRect(segment.x, segment.y, blockSize, blockSize);});}// 绘制食物function drawFood() {ctx.fillStyle = '#f00';ctx.fillRect(food.x, food.y, blockSize, blockSize);}// 检查碰撞function checkCollision() {// 检查蛇是否撞墙if (snake[0].x < 0 || snake[0].x >= canvas.width || snake[0].y < 0 || snake[0].y >= canvas.height) {alert('Game Over!');isRunning = false;return;}// 检查蛇是否撞到自己for (let i = 1; i < snake.length; i++) {if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) {alert('Game Over!');isRunning = false;return;}}// 检查蛇是否吃到食物if (snake[0].x === food.x && snake[0].y === food.y) {score++;placeFood();} else {snake.pop();}}// 放置新的食物function placeFood() {food = {x: Math.floor(Math.random() * (canvas.width / blockSize)) * blockSize,y: Math.floor(Math.random() * (canvas.height / blockSize)) * blockSize};}// 更新游戏状态function update() {if (!isRunning) return;let newX = snake[0].x;let newY = snake[0].y;if (direction === 'left') newX -= blockSize;if (direction === 'right') newX += blockSize;if (direction === 'up') newY -= blockSize;if (direction === 'down') newY += blockSize;snake.unshift({ x: newX, y: newY });checkCollision();}// 渲染游戏画面function draw() {ctx.clearRect(0, 0, canvas.width, canvas.height);drawSnake();drawFood();}// 游戏主循环function gameLoop() {update();draw();setTimeout(gameLoop, speed);}// 键盘事件function handleKeyPress(event) {if (event.key === 'ArrowLeft' && direction !== 'right') direction = 'left';if (event.key === 'ArrowRight' && direction !== 'left') direction = 'right';if (event.key === 'ArrowUp' && direction !== 'down') direction = 'up';if (event.key === 'ArrowDown' && direction !== 'up') direction = 'down';}// 开始按钮事件document.getElementById('startButton').addEventListener('click', () => {const startScreen = document.querySelector('.start-screen');startScreen.style.display = 'none';// 添加键盘事件监听document.addEventListener('keydown', handleKeyPress);isRunning = true;placeFood();gameLoop();});// 游戏结束时移除键盘事件监听window.addEventListener('beforeunload', () => {document.removeEventListener('keydown', handleKeyPress);});</script>
</body>
</html>
http://www.lryc.cn/news/459968.html

相关文章:

  • Kafka SASL/PLAIN认证模式
  • 苹果AI科学家研究证明基于LLM的模型存在缺陷 因为它们无法推理
  • 鸿蒙NEXT开发-页面路由(基于最新api12稳定版)
  • asp.net Core MVC 内容协商
  • 智能EDA小白从0开始 —— DAY10 Yosys
  • 《OpenCV计算机视觉》—— 人脸检测
  • 【unity框架开发12】从零手搓unity存档存储数据持久化系统,实现对存档的创建,获取,保存,加载,删除,缓存,加密,支持多存档
  • YOLOv11进行图像与视频的目标检测
  • SpinalHDL之错误集(一)
  • 【arcgis】ArcGIS中如何避免标注压盖要素
  • 数通--3
  • SpringBoot基础(五):集成JUnit5
  • 正点原子学习笔记之汇编LED驱动实验
  • 网络学习第二篇
  • 一些小结汇总
  • 20240720 科大讯飞 笔试
  • 【AIGC】寻找ChatGPT最佳推理步骤:CoT思维链技术的探索与应用
  • 一、安装VMWARE和CentOS
  • 岩石分类检测数据集 4700张 岩石检测 带标注 voc yolo 9类
  • 电脑基础知识:mfc110.dll丢失的解决方法
  • Lua 协同程序(coroutine)
  • NASA:ARCTAS 区域的二级 FIRSTLOOK 气溶胶产品子集。 它包含气溶胶光学深度和粒子类型,以及相关的大气数据
  • go clean command
  • 鸿蒙NEXT开发-动画(基于最新api12稳定版)
  • HTML 入门
  • 前端面试题(十五)
  • 如何成为 Rust 核心贡献者?Rust 开发的核​​心是什么?Rust 重要技术专家揭秘
  • springboot + nacos + sofarpc 整合后报错403
  • 小米路由器R3Gv2安装openwrt记录
  • 记录一下,android studio 登录不上github的问题