js+jquery实现贪吃蛇经典小游戏
项目只使用到了html,css,js,jquery技术点,没有使用游戏框架,下载本地直接双击index.html 运行即可体验游戏效果。
项目展示
进入游戏

游戏开始

游戏暂停

html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇游戏</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="game-wrapper">
<h1>贪吃蛇游戏</h1>
<div class="game-info">
<div class="score-container">
<div class="score">得分: <span id="score">0</span></div>
<div class="high-score">最高分: <span id="highScore">0</span></div>
</div>
<button id="startBtn">开始游戏</button>
</div>
<div class="game-board-wrapper">
<div id="gameBoard"></div>
</div>
<div class="controls-info">
<p>使用方向键 ← ↑ → ↓ 控制蛇的移动</p>
<p>按空格键 <span class="key-space">Space</span> 暂停/继续游戏</p>
</div>
</div>
</div>
<script src="game.js"></script>
</body>
</html>
CSS文件
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: linear-gradient(135deg, #1a1a2e, #16213e);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
font-family: Arial, sans-serif;
}
.container {
width: 100%;
max-width: 800px;
padding: 20px;
}
.game-wrapper {
background: rgba(255, 255, 255, 0.1);
border-radius: 20px;
padding: 30px;
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.18);
}
h1 {
text-align: center;
margin-bottom: 30px;
font-size: 2.5em;
color: #fff;
text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}
.game-info {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.score-container {
font-size: 1.2em;
}
.score, .high-score {
margin: 5px 0;
}
#score, #highScore {
color: #4CAF50;
font-weight: bold;
}
#startBtn {
background: #4CAF50;
color: white;
border: none;
padding: 12px 30px;
border-radius: 25px;
font-size: 1.1em;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
}
#startBtn:hover {
background: #45a049;
transform: translateY(-2px);
}
.game-board-wrapper {
display: flex;
justify-content: center;
margin: 20px 0;
}
#gameBoard {
width: 600px;
height: 600px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.05);
border: 2px solid rgba(255, 255, 255, 0.1);
position: relative;
}
.snake-body {
width: 20px;
height: 20px;
background: #4CAF50;
position: absolute;
border-radius: 4px;
}
.snake-body.head {
background: #66bb6a;
box-shadow: 0 0 15px rgba(76, 175, 80, 0.7);
}
.food {
width: 20px;
height: 20px;
background: #ff4444;
position: absolute;
border-radius: 50%;
box-shadow: 0 0 15px rgba(255, 68, 68, 0.7);
}
.controls-info {
text-align: center;
margin-top: 20px;
color: rgba(255, 255, 255, 0.7);
font-size: 0.9em;
line-height: 1.6;
}
.controls-info p {
margin: 5px 0;
}
.key-space {
display: inline-block;
padding: 2px 8px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 4px;
margin: 0 3px;
}
@media (max-width: 768px) {
#gameBoard {
width: 300px;
height: 300px;
}
.snake-body, .food {
width: 10px;
height: 10px;
}
}
.pause-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 2em;
color: #fff;
background: rgba(0, 0, 0, 0.7);
padding: 20px 40px;
border-radius: 10px;
z-index: 100;
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% { opacity: 0.6; }
50% { opacity: 1; }
100% { opacity: 0.6; }
}
js文件
$(document).ready(function() {
// 游戏配置
const boardSize = 600;
const cellSize = 20;
const gridSize = boardSize / cellSize;
// 游戏状态
let snake = [];
let food = {};
let direction = 'right';
let gameLoop;
let score = 0;
let highScore = localStorage.getItem('highScore') || 0;
let isGameRunning = false;
// 添加暂停状态变量
let isPaused = false;
let savedInterval = null;
// 显示最高分
$('#highScore').text(highScore);
// 初始化蛇的位置
function initSnake() {
snake = [
{x: 6, y: 10},
{x: 5, y: 10},
{x: 4, y: 10}
];
}
// 生成食物
function generateFood() {
while (true) {
food = {
x: Math.floor(Math.random() * gridSize),
y: Math.floor(Math.random() * gridSize)
};
// 确保食物不会生成在蛇身上
let foodOnSnake = false;
for (let body of snake) {
if (body.x === food.x && body.y === food.y) {
foodOnSnake = true;
break;
}
}
if (!foodOnSnake) break;
}
}
// 绘制游戏画面
function draw() {
$('#gameBoard').empty();
// 绘制蛇
snake.forEach((segment, index) => {
const snakeElement = $('<div>')
.addClass('snake-body')
.css({
left: segment.x * cellSize + 'px',
top: segment.y * cellSize + 'px'
});
if (index === 0) {
snakeElement.addClass('head');
}
$('#gameBoard').append(snakeElement);
});
// 绘制食物
$('#gameBoard').append(
$('<div>')
.addClass('food')
.css({
left: food.x * cellSize + 'px',
top: food.y * cellSize + 'px'
})
);
}
// 移动蛇
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 < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize) {
gameOver();
return;
}
// 检查是否撞到自己
for (let body of snake) {
if (head.x === body.x && head.y === body.y) {
gameOver();
return;
}
}
snake.unshift(head);
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
score += 10;
$('#score').text(score);
if (score > highScore) {
highScore = score;
localStorage.setItem('highScore', highScore);
$('#highScore').text(highScore);
}
generateFood();
} else {
snake.pop();
}
draw();
}
// 游戏结束
function gameOver() {
clearInterval(gameLoop);
alert('游戏结束!得分:' + score);
isGameRunning = false;
isPaused = false;
$('#startBtn').text('重新开始');
$('.pause-text').remove();
}
// 开始游戏
function startGame() {
if (isGameRunning) return;
isGameRunning = true;
isPaused = false;
score = 0;
$('#score').text(score);
direction = 'right';
$('#startBtn').text('游戏中...');
initSnake();
generateFood();
draw();
if (gameLoop) clearInterval(gameLoop);
gameLoop = setInterval(moveSnake, 150);
}
// 添加暂停函数
function togglePause() {
if (!isGameRunning) return;
if (isPaused) {
// 继续游戏
isPaused = false;
gameLoop = setInterval(moveSnake, 150);
$('#startBtn').text('游戏中...');
// 移除暂停提示
$('.pause-text').remove();
} else {
// 暂停游戏
isPaused = true;
clearInterval(gameLoop);
$('#startBtn').text('已暂停');
// 添加暂停提示
$('#gameBoard').append(
$('<div>')
.addClass('pause-text')
.text('游戏暂停')
);
}
}
// 键盘控制
$(document).keydown(function(e) {
// 防止方向键和空格键滚动页面
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
// 空格键控制暂停
if (e.keyCode === 32) { // 空格键
togglePause();
return;
}
// 游戏暂停时不响应方向键
if (!isGameRunning || isPaused) return;
switch(e.keyCode) {
case 38: // 上
if (direction !== 'down') direction = 'up';
break;
case 40: // 下
if (direction !== 'up') direction = 'down';
break;
case 37: // 左
if (direction !== 'right') direction = 'left';
break;
case 39: // 右
if (direction !== 'left') direction = 'right';
break;
}
});
// 绑定开始按钮事件
$('#startBtn').click(startGame);
});
总结
可以直接下载代码到本地,双击index.html文件即可运行查看效果并体验游戏。
js+jquery实现贪吃蛇经典小游戏的更多相关文章
- 原生js写的贪吃蛇网页版游戏特效
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <bo ...
- JS练习实例--编写经典小游戏俄罗斯方块
最近在学习JavaScript,想编一些实例练练手,之前编了个贪吃蛇,但是实现时没有注意使用面向对象的思想,实现起来也比较简单所以就不总结了,今天就总结下俄罗斯方块小游戏的思路和实现吧(需要下载代码也 ...
- 用Python设计一个经典小游戏
这是关于Python的第9篇文章,介绍如何用Python设计一个经典小游戏:猜大小. 在这个游戏中,将用到前面我介绍过的所有内容:变量的使用.参数传递.函数设计.条件控制和循环等,做个整体的总结和复习 ...
- 20行JS代码实现贪吃蛇
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Java经典小游戏——贪吃蛇简单实现(附源码)
一.使用知识 Jframe GUI 双向链表 线程 二.使用工具 IntelliJ IDEA jdk 1.8 三.开发过程 3.1素材准备 首先在开发之前应该准备一些素材,已备用,我主要找了一个图片以 ...
- 用js写一个贪吃蛇小游戏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- jQuery实践-网页版2048小游戏
▓▓▓▓▓▓ 大致介绍 看了一个实现网页版2048小游戏的视频,觉得能做出自己以前喜欢玩的小游戏很有意思便自己动手试了试,真正的验证了这句话-不要以为你以为的就是你以为的,看视频时觉得看懂了,会写了, ...
- JS高级---案例贪吃蛇,把封装的函数移动到js文件中
案例贪吃蛇,把封装的函数移动到js文件中 <!DOCTYPE html> <html lang="en"> <head> <meta ch ...
- JS实现别踩白块小游戏
最近有朋友找我用JS帮忙仿做一个别踩白块的小游戏程序,但他给的源代码较麻烦,而且没有注释,理解起来很无力,我就以自己的想法自己做了这个小游戏,主要是应用JS对DOM和数组的操作. 程序思路:如图:将游 ...
- WinFom中经典小游戏(含源码)
最近整理了若干经典的小游戏,无聊时可以打发时间.程序本身不大,练手非常不错,主要是GDI编程,主界面地址如下图所示 源码下载方式 1,关注微信公众号:小特工作室(也可直接扫描签名处二维码) 2,发送: ...
随机推荐
- 合合信息扫描全能王亮相静安区3·15活动,AI扫描带来绿色消费新体验
保护消费者的合法权益,是全社会的共同责任.为优化消费环境.促进品质消费高地建设,打造安全优质和谐的消费环境,上海静安区消保委于3月15日举办静安区2024年"3·15"国际消费者权 ...
- C# 开源教程带你轻松掌握数据结构与算法
前言 在项目开发过程中,理解数据结构和算法如同掌握盖房子的秘诀.算法不仅能帮助我们编写高效.优质的代码,还能解决项目中遇到的各种难题. 给大家推荐一个支持C#的开源免费.新手友好的数据结构与算法入门教 ...
- 十七,Spring Boot 整合 MyBatis 的详细步骤(两种方式)
十七,Spring Boot 整合 MyBatis 的详细步骤(两种方式) @ 目录 十七,Spring Boot 整合 MyBatis 的详细步骤(两种方式) 1. Spring Boot 配置 M ...
- uniCloud
https://doc.dcloud.net.cn/uniCloud/ 什么是uniCloud uniCloud推出了opendb,包含了大量的开源数据库模板,常见数据表无需自己设计 uniCloud ...
- QT硬件通讯基础
QT硬件通讯基础 使用AI技术辅助生成 1 QT与硬件通讯概述 1.1 QT硬件通讯的基本概念 1.1.1 QT硬件通讯的基本概念 QT硬件通讯的基本概念 QT硬件通讯的基本概念 QT作为一种跨平台的 ...
- HDK Include Header File (1.7)
Download 1.7 | 1.7.1 | 1.7.2 1.7.1 使用方法:编译选项->目录->C++包含文件->添加 [解压目录]\include 1.7.2 使用方法:编译选 ...
- Linux进程调度-组调度及带宽控制
1. 概述 组调度(task_group)是使用Linux cgroup(control group)的cpu子系统来实现的,可以将进程进行分组,按组来分配CPU资源等. 比如,看一个实际的例子: A ...
- Pytorch常用的交叉熵损失函数CrossEntropyLoss()详解
本篇借鉴了这篇文章,如果有兴趣,大家可以看看:https://blog.csdn.net/geter_CS/article/details/84857220 1.交叉熵:交叉熵主要是用来判定实际的输出 ...
- iOS中异常处理机制使用小结
在iOS开发中经常会由于数组越界,添加数据为空,通信或者文件错误,内存溢出导致程序终端运行而引入异常处理机制.常用的处理方式是try catch机制.不过有几个专业术语需要解释,异常句柄.异常处理域断 ...
- 云原生周刊:K8s 1.26 到 1.29 版本的更新 | 2024.1.29
开源项目推荐 Skaffold Skaffold 是一个命令行工具,有助于 Kubernetes 应用程序的持续开发.您可以在本地迭代应用程序源代码,然后部署到本地或远程 Kubernetes 集群. ...