前端 jQuery 实现 贪吃蛇游戏

article/2025/8/19 16:01:35

 效果图

 源代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>jQuery贪吃蛇游戏</title><script src="https://cdn.tailwindcss.com"></script><link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet"><script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script><script>tailwind.config = {theme: {extend: {colors: {primary: '#3B82F6',secondary: '#10B981',danger: '#EF4444',dark: '#1E293B',light: '#F8FAFC'},fontFamily: {sans: ['Inter', 'system-ui', 'sans-serif'],},}}}</script><style type="text/tailwindcss">@layer utilities {.content-auto {content-visibility: auto;}.grid-board {display: grid;grid-template-columns: repeat(20, 1fr);grid-template-rows: repeat(20, 1fr);gap: 1px;}.snake-head {background-color: #3B82F6;border-radius: 4px;}.snake-body {background-color: #93C5FD;border-radius: 2px;}.food {background-color: #EF4444;border-radius: 50%;}.game-container {@apply relative bg-dark rounded-lg overflow-hidden shadow-lg;}.control-btn {@apply w-16 h-16 flex items-center justify-center rounded-full bg-primary/20 text-primary transition-all duration-200 hover:bg-primary/40 active:scale-95;}}</style>
</head>
<body class="bg-gradient-to-br from-light to-gray-200 min-h-screen flex flex-col items-center justify-center p-4 font-sans"><div class="max-w-md w-full mx-auto"><!-- 游戏标题 --><h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-center text-dark mb-6"><i class="fa fa-gamepad text-primary mr-2"></i>贪吃蛇</h1><!-- 游戏状态和控制区 --><div class="flex flex-wrap justify-between items-center mb-4"><div class="flex items-center gap-4"><div class="bg-white p-3 rounded-lg shadow-md"><p class="text-sm text-gray-500">分数</p><p id="score" class="text-2xl font-bold text-primary">0</p></div><div class="bg-white p-3 rounded-lg shadow-md"><p class="text-sm text-gray-500">最高分</p><p id="highScore" class="text-2xl font-bold text-secondary">0</p></div></div><div class="flex gap-2"><button id="startBtn" class="px-4 py-2 bg-primary text-white rounded-lg shadow-md hover:bg-primary/90 transition-all duration-200"><i class="fa fa-play mr-1"></i>开始</button><button id="pauseBtn" class="px-4 py-2 bg-gray-600 text-white rounded-lg shadow-md hover:bg-gray-700 transition-all duration-200" disabled><i class="fa fa-pause mr-1"></i>暂停</button></div></div><!-- 游戏区域 --><div class="game-container aspect-square"><div id="gameBoard" class="grid-board w-full h-full bg-gray-800"></div><!-- 游戏开始遮罩 --><div id="startScreen" class="absolute inset-0 bg-dark/80 flex flex-col items-center justify-center z-10"><h2 class="text-2xl font-bold text-white mb-4">贪吃蛇游戏</h2><p class="text-gray-300 mb-6">使用方向键或屏幕按钮控制蛇的移动</p><button id="playBtn" class="px-6 py-3 bg-primary text-white rounded-lg shadow-lg hover:bg-primary/90 transition-all duration-200 transform hover:scale-105"><i class="fa fa-play-circle mr-2"></i>开始游戏</button></div><!-- 游戏结束遮罩 --><div id="gameOverScreen" class="absolute inset-0 bg-dark/80 flex flex-col items-center justify-center z-10 hidden"><h2 class="text-2xl font-bold text-danger mb-2">游戏结束</h2><p class="text-xl text-white mb-2">您的分数: <span id="finalScore" class="font-bold">0</span></p><p class="text-gray-300 mb-6">最高分: <span id="finalHighScore" class="font-bold">0</span></p><button id="restartBtn" class="px-6 py-3 bg-primary text-white rounded-lg shadow-lg hover:bg-primary/90 transition-all duration-200 transform hover:scale-105"><i class="fa fa-refresh mr-2"></i>重新开始</button></div></div><!-- 移动端控制按钮 --><div class="mt-6 grid grid-cols-3 gap-2 max-w-xs mx-auto md:hidden"><div></div><button id="upBtn" class="control-btn mx-auto"><i class="fa fa-chevron-up text-xl"></i></button><div></div><button id="leftBtn" class="control-btn"><i class="fa fa-chevron-left text-xl"></i></button><div></div><button id="rightBtn" class="control-btn"><i class="fa fa-chevron-right text-xl"></i></button><div></div><button id="downBtn" class="control-btn mx-auto"><i class="fa fa-chevron-down text-xl"></i></button><div></div></div><!-- 游戏说明 --><div class="mt-6 p-4 bg-white rounded-lg shadow-md"><h3 class="font-semibold text-lg mb-2 text-dark">游戏说明</h3><ul class="text-gray-600 space-y-1"><li><i class="fa fa-check-circle text-primary mr-1"></i> 吃食物增长长度并获得分数</li><li><i class="fa fa-check-circle text-primary mr-1"></i> 撞到墙壁或自己的身体游戏结束</li><li><i class="fa fa-check-circle text-primary mr-1"></i> 游戏过程中可以暂停或重新开始</li><li><i class="fa fa-check-circle text-primary mr-1"></i> 移动端用户可以使用屏幕上的方向按钮</li></ul></div></div><script>$(document).ready(function() {// 游戏配置const config = {gridSize: 20, // 网格大小initialSpeed: 200, // 初始速度(毫秒)speedIncrease: 5, // 每次加速减少的毫秒数maxSpeed: 80 // 最大速度(毫秒)};// 游戏状态let gameState = {snake: [{x: 10, y: 10}], // 蛇的初始位置,头部在前direction: {x: 1, y: 0}, // 初始方向:右nextDirection: {x: 1, y: 0}, // 下一个方向food: null, // 食物位置score: 0, // 当前分数highScore: localStorage.getItem('snakeHighScore') || 0, // 最高分isRunning: false, // 游戏是否正在运行gameLoop: null, // 游戏循环定时器speed: config.initialSpeed // 当前速度};// DOM元素const $gameBoard = $('#gameBoard');const $score = $('#score');const $highScore = $('#highScore');const $startBtn = $('#startBtn');const $pauseBtn = $('#pauseBtn');const $startScreen = $('#startScreen');const $gameOverScreen = $('#gameOverScreen');const $finalScore = $('#finalScore');const $finalHighScore = $('#finalHighScore');const $playBtn = $('#playBtn');const $restartBtn = $('#restartBtn');// 初始化高分显示$highScore.text(gameState.highScore);// 创建游戏网格function createGrid() {$gameBoard.empty();for (let y = 0; y < config.gridSize; y++) {for (let x = 0; x < config.gridSize; x++) {const $cell = $('<div>').addClass('bg-gray-700 transition-all duration-100');$cell.attr('id', `cell-${x}-${y}`);$gameBoard.append($cell);}}}// 随机生成食物位置function generateFood() {// 确保食物不会出现在蛇身上let newFood;do {newFood = {x: Math.floor(Math.random() * config.gridSize),y: Math.floor(Math.random() * config.gridSize)};} while (gameState.snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));gameState.food = newFood;updateBoard();}// 更新游戏面板function updateBoard() {// 清除之前的蛇和食物$('.snake-head, .snake-body, .food').removeClass('snake-head snake-body food');// 绘制蛇gameState.snake.forEach((segment, index) => {const $cell = $(`#cell-${segment.x}-${segment.y}`);if (index === 0) {$cell.addClass('snake-head');} else {$cell.addClass('snake-body');}});// 绘制食物if (gameState.food) {$(`#cell-${gameState.food.x}-${gameState.food.y}`).addClass('food');}}// 移动蛇function moveSnake() {// 更新方向gameState.direction = gameState.nextDirection;// 计算新的头部位置const head = {x: gameState.snake[0].x + gameState.direction.x,y: gameState.snake[0].y + gameState.direction.y};// 检查是否碰撞墙壁if (head.x < 0 || head.x >= config.gridSize || head.y < 0 || head.y >= config.gridSize) {gameOver();return;}// 检查是否碰撞自身if (gameState.snake.some(segment => segment.x === head.x && segment.y === head.y)) {gameOver();return;}// 将新头部添加到蛇身gameState.snake.unshift(head);// 检查是否吃到食物if (head.x === gameState.food.x && head.y === gameState.food.y) {// 吃到食物,增加分数gameState.score += 10;$score.text(gameState.score);// 更新最高分if (gameState.score > gameState.highScore) {gameState.highScore = gameState.score;$highScore.text(gameState.highScore);localStorage.setItem('snakeHighScore', gameState.highScore);}// 加速gameState.speed = Math.max(config.maxSpeed, gameState.speed - config.speedIncrease);// 生成新食物generateFood();} else {// 没吃到食物,移除尾部gameState.snake.pop();}// 更新面板updateBoard();}// 开始游戏function startGame() {if (gameState.isRunning) return;gameState.isRunning = true;$startScreen.addClass('hidden');$gameOverScreen.addClass('hidden');$startBtn.attr('disabled', true);$pauseBtn.attr('disabled', false);// 初始化蛇和食物gameState.snake = [{x: 10, y: 10}];gameState.direction = {x: 1, y: 0};gameState.nextDirection = {x: 1, y: 0};gameState.score = 0;gameState.speed = config.initialSpeed;$score.text(gameState.score);// 生成食物generateFood();// 开始游戏循环gameState.gameLoop = setInterval(moveSnake, gameState.speed);}// 暂停游戏function pauseGame() {if (!gameState.isRunning) return;gameState.isRunning = false;clearInterval(gameState.gameLoop);$startBtn.attr('disabled', false);$pauseBtn.attr('disabled', true);}// 游戏结束function gameOver() {pauseGame();$finalScore.text(gameState.score);$finalHighScore.text(gameState.highScore);$gameOverScreen.removeClass('hidden');}// 处理键盘控制function handleKeydown(e) {// 阻止方向键滚动页面if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(e.key)) {e.preventDefault();}// 游戏未开始时,空格键开始游戏if (!gameState.isRunning && e.key === ' ') {if ($gameOverScreen.is(':visible')) {startGame();} else if ($startScreen.is(':visible')) {$startScreen.addClass('hidden');}return;}// 游戏运行中,处理方向键switch (e.key) {case 'ArrowUp':if (gameState.direction.y !== 1) { // 不能直接掉头gameState.nextDirection = {x: 0, y: -1};}break;case 'ArrowDown':if (gameState.direction.y !== -1) {gameState.nextDirection = {x: 0, y: 1};}break;case 'ArrowLeft':if (gameState.direction.x !== 1) {gameState.nextDirection = {x: -1, y: 0};}break;case 'ArrowRight':if (gameState.direction.x !== -1) {gameState.nextDirection = {x: 1, y: 0};}break;case ' ': // 空格键暂停/继续if (gameState.isRunning) {pauseGame();} else if (!$startScreen.is(':visible') && !$gameOverScreen.is(':visible')) {startGame();}break;}}// 初始化游戏function initGame() {createGrid();// 绑定事件$(document).keydown(handleKeydown);$startBtn.click(startGame);$pauseBtn.click(pauseGame);$playBtn.click(startGame);$restartBtn.click(startGame);// 移动端控制$('#upBtn').click(() => {if (gameState.direction.y !== 1) {gameState.nextDirection = {x: 0, y: -1};}});$('#downBtn').click(() => {if (gameState.direction.y !== -1) {gameState.nextDirection = {x: 0, y: 1};}});$('#leftBtn').click(() => {if (gameState.direction.x !== 1) {gameState.nextDirection = {x: -1, y: 0};}});$('#rightBtn').click(() => {if (gameState.direction.x !== -1) {gameState.nextDirection = {x: 1, y: 0};}});}// 启动游戏initGame();});</script>
</body>
</html>

上面的贪吃蛇游戏使用了以下外部插件和资源:

  1. Tailwind CSS - 用于构建响应式布局和样式

    • 版本:v3
    • 通过 CDN 引入:https://cdn.tailwindcss.com
    • 作用:提供了丰富的工具类,快速实现界面布局、样式和动画效果
  2. Font Awesome - 用于图标显示

    • 版本:v4.7.0
    • 通过 CDN 引入:https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css
    • 作用:提供游戏中使用的各种图标,如方向键、游戏按钮图标等
  3. jQuery - 用于 DOM 操作和事件处理

    • 版本:v3.6.0
    • 通过 CDN 引入:https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
    • 作用:简化 DOM 操作,实现游戏逻辑和交互效果

这些外部资源都是通过 CDN 直接引入的,无需额外安装,确保了游戏的快速加载和兼容性。


http://www.hkcw.cn/article/agbbOyVqji.shtml

相关文章

怒更一波免费声音克隆和AI配音功能

宝子们&#xff01; 最近咱软件TransDuck的免费声音克隆和AI配音功能被大家用爆啦&#xff01;感谢各位自来水疯狂安利&#xff01;&#xff01; DD这里也是收到好多用户提的宝贵建议&#xff01;所以&#xff0c;连夜肝了波更新&#xff01; 这次重点更新使用克隆音色进行A…

深入解析Java8核心新特性(Lambda、函数式接口、Stream)

有一个想法&#xff0c;把Java重要版本新特性拿出来分别深入解析&#xff0c;于是&#xff0c;这个专栏来了&#xff01; 文章目录 前言一、Lambda表达式&#xff1a;函数式编程的基石1.1 Lambda表达式&#xff1a;概念与本质1.2 Lambda语法结构详解1.3 Lambda与函数式接口的关…

Swagger 访问不到 报错:o.s.web.servlet.PageNotFound : No mapping for GET /doc.html

1.使用的版本 Swagger版本&#xff1a;2.9.2 Spring Boot版本&#xff1a;2.6.15 2.问题 &#xff08;1&#xff09;控制台报错 o.s.web.servlet.PageNotFound - No mapping for GET /swagger-ui.html WARN o.s.web.servlet.PageNotFound - No mapping for GET /swagger…

MyBatis联表查询

数据库表结构 CREATE TABLE teacher (id int(11) NOT NULL AUTO_INCREMENT,tname varchar(255) DEFAULT NULL,PRIMARY KEY (id) USING BTREE ) ENGINEInnoDB AUTO_INCREMENT3 DEFAULT CHARSETutf8 ROW_FORMATCOMPACT;CREATE TABLE student (id int(11) NOT NULL AUTO_INCREMEN…

技术分享 | Oracle SQL优化案例一则

本文为墨天轮数据库管理服务团队第70期技术分享&#xff0c;内容原创&#xff0c;作者为技术顾问马奕璇&#xff0c;如需转载请联系小墨&#xff08;VX&#xff1a;modb666&#xff09;并注明来源。 一、问题概述 开发人员反映有条跑批语句在测试环境执行了很久都没结束&…

在力扣刷题中触摸算法的温度

在代码的世界里&#xff0c;每一道力扣题目都是一扇通往未知的门。当我推开这些门&#xff0c;与内置求和函数、二进制位运算、辗转相减思想以及链表结构相遇时&#xff0c;才真正触摸到算法的温度 —— 那是一种理性与智慧交织的炽热&#xff0c;也是思维不断淬炼的滚烫。​ 最…

LangFuse:开源LLM工程平台的革新实践

文章目录 一 架构设计与技术栈二 增强型监控能力三 提示词工程支持&#xff08;新增&#xff09;四 性能优化实践五 LangFuse部署&#xff08;docker&#xff09;和代码集成5.1 LangFuse平台部署5.2 LangFuse代码集成和检测体验 一 架构设计与技术栈 LangFuse采用模块化架构设…

信创采购热潮下的隐忧:单一技术路线的市场垄断之困

在国家信息技术应用创新&#xff08;信创&#xff09;战略的强力推动下&#xff0c;信创产业迎来了前所未有的发展机遇。 然而&#xff0c;随着采购规模的快速增长&#xff0c;单一技术路线中标现象逐渐凸显&#xff0c;引发了行业内外的广泛关注。本文将从现状、成因与影响三个…

美国还有36个州仍允许未成年人或童婚婚姻

美国还有36个州仍允许未成年人婚姻当地时间5月28日,美国俄勒冈州的州长蒂娜科特克签署了一项法令,禁止俄勒冈州未满18岁的未成年人结婚。然而,在这则新闻背后却隐藏着一个令美国乃至世界很多国家的网民都相当吃惊的魔幻情况……先介绍下俄勒冈的情况。根据当地媒体报道,俄勒…

国产榴莲6月中下旬批量上市 甜蜜来袭

对于美食爱好者而言,今年似乎又是一个“甜蜜”的年份。从年初开始,车厘子、蓝莓等曾经的高价水果价格纷纷大幅下降。在北京一家生鲜超市,一进门最显眼的位置上摆放着来自泰国的金枕榴莲。与榴莲相比,山竹的价格近年来相对稳定。这家超市里,一盒4A规格的山竹一共6颗,售价1…

国家要发财政补贴?假的 虚假信息需警惕

近日,有四川网民反映收到关于《2025年国家财政部补贴》的声明。该声明称,根据国家财政部和人力资源社会保障部发布的通知,将发放薪资补贴、社保补贴、医保补贴、住房补贴、交通补贴、岗位补贴等,并要求申领认证。5月29日,四川财政部门相关工作人员表示,这则消息是假的,其…

实战指南:步进电机规格书参数解析——以28BYJ48为例(不聊原理,只讲应用)

前言:为什么写这篇? 网上讲解步进电机原理的文章铺天盖地,但当你拿到一份电机规格书时,面对诸如“牵出频率≥1000Hz”,“自定位转矩≥300gfcm”等参数,是否仍感到一头雾水?本文以常见的28BYJ48减速步进电机规格书为例,跳过原理,直击参数的实际意义与应用陷阱,助你快速…

男子酒驾冲卡撞伤交警 肇事者已被刑拘

5月27日晚,交警在陕西西安莲湖区文景南路与农兴路十字路口附近设卡执勤时,一名男子驾车冲卡,撞毁护栏并撞伤一名交警。该男子涉嫌酒驾,已被刑拘。事发后,该男子弃车逃离现场,但很快被执勤交警抓获。目击者称,听到撞击声后,一辆由北向南行驶的黑色商务车冲过道路中间的护…

有多少业主,想着赶走自己的物业公司

‌有相当一部分业主希望赶走自己的物业公司‌。许多业主对物业公司的服务感到不满,主要原因包括物业公司服务不到位、乱收费、侵占业主收入等。例如,一些物业公司被指责拿钱不干活,设备损坏拖延维修,额外收费项目模糊不清,甚至侵占广告收入等‌。此外,部分业主认为物业公…

90后作家刘楚昕获奖感言刷屏 挚爱遗言催人泪下

日前,90后作家刘楚昕创作的小说《泥潭》荣获第二届漓江文学奖虚构类奖。在颁奖现场上,作家余华公布了这个好消息。而获奖者刘楚昕的感言因格外催泪动人在朋友圈里刷了屏。2017年,刘楚昕在武汉大学读博期间遇到了他的初恋女友。当时,他正朝着自己的文学梦马不停蹄地赶路。“…

时隔多日 金正恩露面再次喜笑颜开!

时隔多日金正恩露面再次喜笑颜开。据央视新闻报道,朝鲜人民军大联合部队炮兵部队29日进行了火炮射击比赛。朝鲜劳动党总书记、国务委员长金正恩观摩火炮射击比赛。在火炮射击比赛中,各前线大联合部队首长直接进行火力指挥。金正恩说,参赛炮兵部队展现了炮兵武装力量的实战能…

【Linux篇】叩响新世界的大门:线程

概念角度&#xff1a; 感性理解线程&#xff1a; 进程&#xff1a;内核数据结构数据和代码 线程&#xff1a;进程内部的一个执行分支 进程也是被cpu调度&#xff0c;所以进程还有一个执行流的概念 内核与资源角度理解&#xff1a; 进程&#xff1a; 承担分配系统资源的…

夫妻领证时发现互不知姓名 闪婚变闪离引发争议

你听说过这样的事吗?一对男女去民政局领结婚证,却因为男方不知道女方名字,女方也不知道男方名字而失败。这对来自襄州区古驿镇的年轻人尽管领证失败,但仍然坚持“闪婚”。他们在一起住了一年,但从未同房,最终这段短暂的婚姻走到了尽头。然而,高达十多万元的彩礼给两家人…

男子酒驾冲卡撞伤交警被刑拘 肇事司机已被控制

5月27日晚,交警在陕西西安莲湖区文景南路与农兴路十字路口附近设卡执勤时,一名男子驾车冲卡,冲毁护栏并撞伤一名交警。次日下午,该男子因涉嫌酒驾被刑拘。事发后,肇事司机弃车逃离现场,但很快被执勤交警抓获。据事发地商户描述,听到撞击声后,一辆由北向南行驶的黑色商务…

RISCV——内核及汇编

RISCV——内核及汇编 小狼http://blog.csdn.net/xiaolangyangyang 1、寄存器组&#xff08;ABI&#xff09; 2、异常及中断 XV6 trap&#xff08;二&#xff09;RISCV中断异常处理/定时器中断 mie&#xff1a;中断开关mip&#xff1a;中断状态mstatus.mie&#xff1a;全局中断…