HTML贪吃蛇游戏

ops/2024/9/23 22:23:17/

文章目录

      • 贪吃蛇html" title=游戏>游戏
    • 运行效果
    • 注意
    • 代码


贪吃蛇html" title=游戏>游戏

贪吃蛇是一款经典的休闲益智html" title=游戏>游戏。本文将通过HTML5和JavaScript详细解析如何实现一个简易版的贪吃蛇html" title=游戏>游戏。html" title=游戏>游戏的主要逻辑包括蛇的移动、碰撞检测、食物生成等功能。以下是html" title=游戏>游戏的完整代码及注释解析。(纯属好玩)

运行效果

在这里插入图片描述

注意

PC端可以用键盘上,下,左,右键操作,手机上可以用按钮操作。

代码

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Snake Game</title><style>body {margin: 0;display: flex;flex-direction: column;justify-content: center;align-items: center;height: 100vh;background-color: #000;}canvas {border: 1px solid #fff;}.mobile-controls {display: flex;justify-content: center;margin-top: 20px;}.control-button {background-color: #fff;border: 1px solid #000;padding: 10px 20px;margin: 5px;font-size: 18px;cursor: pointer;border-radius: 5px;}</style>
</head><body><canvas id="gameCanvas"></canvas><div class="mobile-controls"><button class="control-button" id="left"></button><button class="control-button" id="up"></button><button class="control-button" id="down"></button><button class="control-button" id="right"></button></div><script>const canvas = document.getElementById('gameCanvas');const ctx = canvas.getContext('2d');const scale = 20;const rows = 20;const columns = 20;canvas.width = columns * scale;canvas.height = rows * scale;let snake;let food;let direction = { x: 1, y: 0 };let isGameOver = false;let baseSnakeColor;let foodColor;// 随机生成颜色的函数function getRandomColor() {const r = Math.floor(Math.random() * 256);const g = Math.floor(Math.random() * 256);const b = Math.floor(Math.random() * 256);return `rgb(${r}, ${g}, ${b})`;}function Snake() {this.body = [{ x: 10, y: 10 }];this.draw = function () {for (let i = 0; i < this.body.length; i++) {const gradientFactor = i / this.body.length;// 通过调整颜色实现渐变效果,头部颜色较深,尾部颜色较浅const r = Math.floor(255 * (1 - gradientFactor)); // 以红色基调为例const g = Math.floor(100 * gradientFactor); // 可根据需要调整const b = Math.floor(150); // 固定一个蓝色调ctx.fillStyle = `rgb(${r},${g},${b})`;ctx.fillRect(this.body[i].x * scale, this.body[i].y * scale, scale, scale);}};this.update = function () {const newHead = {x: this.body[0].x + direction.x,y: this.body[0].y + direction.y};// 检查蛇是否撞墙或与自身碰撞if (newHead.x < 0 || newHead.x >= columns || newHead.y < 0 || newHead.y >= rows || this.isCollision(newHead)) {isGameOver = true;}this.body.unshift(newHead);if (newHead.x === food.x && newHead.y === food.y) {generateFood();} else {this.body.pop();}};// 检查蛇是否与自身碰撞this.isCollision = function (pos) {for (let i = 0; i < this.body.length; i++) {if (this.body[i].x === pos.x && this.body[i].y === pos.y) {return true;}}return false;};}// 生成食物,确保食物不会生成在蛇身体上function generateFood() {let isOnSnake;do {isOnSnake = false;food = {x: Math.floor(Math.random() * columns),y: Math.floor(Math.random() * rows)};// 检查食物是否生成在蛇身体上for (let i = 0; i < snake.body.length; i++) {if (snake.body[i].x === food.x && snake.body[i].y === food.y) {isOnSnake = true;break;}}} while (isOnSnake); // 如果食物生成在蛇身体上,重新生成foodColor = getRandomColor(); // 每次生成新的食物时,食物颜色变化}// 绘制食物function drawFood() {ctx.fillStyle = foodColor;ctx.fillRect(food.x * scale, food.y * scale, scale, scale);}// html" title=游戏>游戏主循环function gameLoop() {if (isGameOver) {alert('Game Over');document.location.reload();return;}ctx.clearRect(0, 0, canvas.width, canvas.height);snake.update();snake.draw();drawFood();setTimeout(gameLoop, 200);  // 控制html" title=游戏>游戏速度(200ms 间隔)}// 控制蛇的方向window.addEventListener('keydown', (e) => {switch (e.key) {case 'ArrowUp':if (direction.y === 0) direction = { x: 0, y: -1 };break;case 'ArrowDown':if (direction.y === 0) direction = { x: 0, y: 1 };break;case 'ArrowLeft':if (direction.x === 0) direction = { x: -1, y: 0 };break;case 'ArrowRight':if (direction.x === 0) direction = { x: 1, y: 0 };break;}});// 移动端控制按钮document.getElementById('left').addEventListener('click', () => {if (direction.x === 0) direction = { x: -1, y: 0 };});document.getElementById('right').addEventListener('click', () => {if (direction.x === 0) direction = { x: 1, y: 0 };});document.getElementById('up').addEventListener('click', () => {if (direction.y === 0) direction = { x: 0, y: -1 };});document.getElementById('down').addEventListener('click', () => {if (direction.y === 0) direction = { x: 0, y: 1 };});// 初始化html" title=游戏>游戏baseSnakeColor = getRandomColor(); // 在html" title=游戏>游戏开始时生成蛇的基色,并且保持一致snake = new Snake();generateFood();gameLoop();</script></body></html>

http://www.ppmy.cn/ops/114989.html

相关文章

安全带检测系统源码分享

安全带检测检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Visio…

vim编辑器的简单使用

定义&#xff1a;Vim 是一个功能强大的文本编辑器&#xff0c;广泛用于编程和服务器环境。 Vim 的三种主要模式 命令模式&#xff08;Normal Mode&#xff09;&#xff1a;默认进入的模式&#xff0c;在该模式下&#xff0c;你可以执行各种命令&#xff0c;如保存、退出、删除…

UE5——在线子系统

Unreal Engine 5 (UE5) 的在线子系统&#xff08;Online Subsystem&#xff09;实现多人在线游戏的原理涉及到网络编程和分布式系统设计中的多个方面。以下是该系统工作的一些核心概念和技术&#xff1a; 1. 客户端-服务器架构: - 大多数现代多人在线游戏采用客户端-服务器模型…

CTFShow-反序列化

一些基础&#xff1a; private变量会被序列化为&#xff1a;\x00类名\x00变量名 protected变量会被序列化为: \x00*\x00变量名 public变量会被序列化为&#xff1a;变量名 __sleep() //在对象被序列化之前运行 * __wakeup() //将在反序列化之后立即调用&#xff08;当反序列化时…

Qt 类型选择器和类选择器的区别

概念上的区别请查看此篇博客&#xff1a;Qt 样式表、选择器、盒子模型&#xff0c;下面我直接举例说明。 示例界面&#xff1a; 1、类型选择器&#xff1a; QWidget {background-color: rgb(255, 85, 127); }运行结果&#xff08;因为QPushButton是QWidget的子类&#xff0…

Springboot提升-MapStruct组件使用

文章目录 1. 添加依赖2. 创建映射接口3. 在Spring Boot中使用MapStruct映射器4. 配置MapStruct 在Spring Boot项目中使用MapStruct可以帮助你更方便地管理对象之间的映射逻辑。下面是一些基本步骤来设置和使用MapStruct&#xff1a; 1. 添加依赖 首先&#xff0c;你需要在项目…

C++ 落地AI项目教程:以libtorch实现逻辑回归

C++ 落地AI项目教程:以libtorch实现逻辑回归 1. 逻辑回归基本原理 逻辑回归是一种二分类算法,其原理是:通过学习训练数据,将数据分为两个类,比如0和1. 逻辑回归(Logistic Regression)是一种统计学上常用的分类算法,尽管其名称中含有“回归”一词,但实际上它被广泛应用…

招联金融内推(深圳武汉大量招后端、算法)---2025秋招内推

【投递方式】 直接扫下方二维码&#xff0c;或点击内推官网https://wecruit.hotjob.cn/SU61025e262f9d247b98e0a2c2/mc/position/campus&#xff0c;使用内推码 igcefb 投递&#xff09; 【招聘岗位】 后台开发 前端开发 数据开发 数据运营 算法开发 技术运维 软件测试 产品策…