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,发送: ...
随机推荐
- GPG 用法
GPG (GnuPG) 是一种加密工具,用于数据加密和数字签名. 密钥配置 # 生成密钥 gpg --full-generate-key # 列出密钥 gpg --list-keys # 列出公钥 g ...
- 【Python自动化】之运用Git+jenkins集成来运行展示pytest+allure测试报告
目录: 一.安装allure 二.生成allure报告 三.结合jenkins来集成pytest+allure 四.结合Git集成Jenkins+Pytest+Allure测试报告 五.附录 一.安装 ...
- 图文教程:从0到1将项目发布到 Maven 中央仓库
前言 本文基于官方文档 https://central.sonatype.org/publish/publish-guide/ 编写. 发布步骤: 创建账号 创建用户 Token 创建命名空间 配置 ...
- HTML & CSS – Styling Table
前言 Table (表格) 历史悠久, 它有许多独特的默认样式, 它也是最早的布局方案方案哦 (现在依然有用 table 来做布局的, 比如 email template). 这篇来介绍一下基本的 t ...
- 贝壳找房携手 Flutter,为三亿家庭提供更好的居住服务 | Flutter 开发者故事
贝壳找房是科技驱动的新居住服务平台,致力于在二手房.新房.租房以及装修等居住领域为三亿家庭提供全方位的品质居住服务.如此庞大的用户群体,自然也有着十分多样和复杂的使用场景和需求.以往使用原生开发模式时 ...
- 利用cv2.dilate对图像进行膨胀
cv2.getStructuringElement(cv2.MORPH_RECT, (7,7))介绍,请看这个博客.我简要说一下cv2.getStructuringElement,可用于构造一个特定大 ...
- 怎么根据token的有⽆去控制路由的跳转?进度条跳转 - 白名单是否有token - 单独封装文件permission .js
vue这边的路由⾃带了路由前置守卫,我们可以在前置守卫⾥拿到token数据,然后根据需求做分⽀判 断,要是token存在就使⽤next⽅法正常放⾏跳转,否则可以强制跳回到登录,让⽤户去获取token ...
- KubeSphere 边缘节点 IP 冲突的分析和解决思路分享
在上一篇监控问题排查的文章中,笔者分析了 KubeSphere 3.1.0 集成 KubeEdge 中的边缘监控原理和问题排查思路,在介绍 EdgeWatcher 组件时提到了"边缘节点的内 ...
- Java消息队列入门详解
什么是消息队列? 消息队列的产生主要是为了解决系统间的异步解耦与确保最终一致性.在实际应用场景中,往往存在一些主流程操作和辅助流程操作,其中主流程需要快速响应用户请求,而辅助流程可能涉及复杂的处理逻辑 ...
- javascript语法--for in、for of和forEach
首先看简单for循环效果,功能最基本,但可以实现所有循环功能 for (let i = 0; i < list.length; i++) { } 接下来看for in.for of和forEac ...