效果图
源代码:
<!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>
上面的贪吃蛇游戏使用了以下外部插件和资源:
-
Tailwind CSS - 用于构建响应式布局和样式
- 版本:v3
- 通过 CDN 引入:https://cdn.tailwindcss.com
- 作用:提供了丰富的工具类,快速实现界面布局、样式和动画效果
-
Font Awesome - 用于图标显示
- 版本:v4.7.0
- 通过 CDN 引入:https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css
- 作用:提供游戏中使用的各种图标,如方向键、游戏按钮图标等
-
jQuery - 用于 DOM 操作和事件处理
- 版本:v3.6.0
- 通过 CDN 引入:https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
- 作用:简化 DOM 操作,实现游戏逻辑和交互效果
这些外部资源都是通过 CDN 直接引入的,无需额外安装,确保了游戏的快速加载和兼容性。