一朵花如果只被用来观赏那只呈现出它的外在意义只是它生命的一部分若是不能够将其内在更实质的美发挥出来充其量也不过就是一朵死的花而已。


目录

一、前言

二、代码介绍

三、效果显示

四、编码实现

index.html

jquery-1.10.2.js

五、获取源码

获取源码?私信?关注?点赞?收藏?


一、前言

贪吃蛇是一款经典的小游戏。初始是像素版本,后来又衍生出3D版本、多人对战版本等。

贪食蛇游戏操作简单,可玩性比较高。这个游戏难度最大的不是蛇长得很长的时候,而是开始。那个时候蛇身很短,看上去难度不大,却最容易死掉,因为把玩一条小短蛇让人容易走神,失去耐心。由于难度小,你会不知不觉加快调整方向的速度,在游走自如的时候蛇身逐渐加长了,而玩家却没有意识到危险。

贪食蛇的另一个危险期在于游戏开始几十秒之后。由于玩家的注意力高度集中,精神紧张,此时局面稍好,就会不由自主地想放松一下,结果手指一松劲,贪食蛇就死了。所以贪食蛇可以算作一个敏捷型的小游戏。


二、代码介绍

一款简单的 HTML+JS 原生贪吃蛇小游戏

1、HTML

2、JS

3、舒适的画面感

4、流畅的游戏体验


三、效果显示

我们一起回味一下好玩的贪吃蛇吧!!!

A.

B.

舒适美观的画面,灵动的体验!!!

是否想体验一下呢?


四、编码实现


由于文章篇幅限制,部分代码将不予展示,但会将完整代码文件放在下方

注意路径(⊙o⊙)?

o(* ̄▽ ̄*)ブ


index.html

<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title>JS贪吃蛇</title><script src="static/js/jquery-1.10.2.js"></script><style>@font-face {font-family: "game";src: url("https://fonts.googleapis.com/css2?family=Poppins:wght@500;800&display=swap");}* {padding: 0;margin: 0;box-sizing: border-box;}button:focus {outline: 0;}html,body {height: 100%;font-family: "Poppins", sans-serif;color: #6e7888;}body {background-color: #222738;display: flex;justify-content: center;align-items: center;color: #6e7888;}canvas {background-color: #181825;}.container {display: flex;width: 100%;height: 100%;flex-flow: column wrap;justify-content: center;align-items: center;}#ui {display: flex;align-items: center;font-size: 10px;flex-flow: column;margin-left: 10px;}h2 {font-weight: 200;transform: rotate(270deg);}#score {margin-top: 20px;font-size: 30px;font-weight: 800;}.noselect {user-select: none;}#replay {font-size: 10px;padding: 10px 20px;background: #6e7888;border: none;color: #222738;border-radius: 20px;font-weight: 800;transform: rotate(270deg);cursor: pointer;transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);}#replay:hover {background: #a6aab5;background: #4cffd7;transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);}#replay svg {margin-right: 8px;}@media (max-width: 600px) {#replay {margin-bottom: 20px;}#replay,h2 {transform: rotate(0deg);}#ui {flex-flow: row wrap;margin-bottom: 20px;}#score {margin-top: 0;margin-left: 20px;}.container {flex-flow: column wrap;}}#author {width: 100%;bottom: 40px;display: inline-flex;align-items: center;justify-content: center;font-weight: 600;color: inherit;text-transform: uppercase;padding-left: 35px;}#author span {font-size: 10px;margin-left: 20px;color: inherit;letter-spacing: 4px;}#author h1 {font-size: 25px;}.wrapper {display: flex;flex-flow: row wrap;justify-content: center;align-items: center;margin-bottom: 20px;}</style></head><body><div class="container noselect"><div class="wrapper"><button id="replay"><i class="fas fa-play"></i>RESTART</button><div id="canvas"></div><div id="ui"><h2>SCORE</h2><span id="score">00</span></div></div><div id="author"><h1>SNAKE</h1><span><p>小键盘方向键控制</p></span></div></div><script>/**
This is a snake game I made with Vanilla Javascript.
Follow me on twitter @fariatondo
**/let dom_replay = document.querySelector("#replay");let dom_score = document.querySelector("#score");let dom_canvas = document.createElement("canvas");document.querySelector("#canvas").appendChild(dom_canvas);let CTX = dom_canvas.getContext("2d");const W = (dom_canvas.width = 400);const H = (dom_canvas.height = 400);let snake,food,currentHue,cells = 20,cellSize,isGameOver = false,tails = [],score = 00,maxScore = window.localStorage.getItem("maxScore") || undefined,particles = [],splashingParticleCount = 20,cellsCount,requestID;let helpers = {Vec: class {constructor(x, y) {this.x = x;this.y = y;}add(v) {this.x += v.x;this.y += v.y;return this;}mult(v) {if (v instanceof helpers.Vec) {this.x *= v.x;this.y *= v.y;return this;} else {this.x *= v;this.y *= v;return this;}}},isCollision(v1, v2) {return v1.x == v2.x && v1.y == v2.y;},garbageCollector() {for (let i = 0; i < particles.length; i++) {if (particles[i].size <= 0) {particles.splice(i, 1);}}},drawGrid() {CTX.lineWidth = 1.1;CTX.strokeStyle = "#232332";CTX.shadowBlur = 0;for (let i = 1; i < cells; i++) {let f = (W / cells) * i;CTX.beginPath();CTX.moveTo(f, 0);CTX.lineTo(f, H);CTX.stroke();CTX.beginPath();CTX.moveTo(0, f);CTX.lineTo(W, f);CTX.stroke();CTX.closePath();}},randHue() {return ~~(Math.random() * 360);},hsl2rgb(hue, saturation, lightness) {if (hue == undefined) {return [0, 0, 0];}var chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;var huePrime = hue / 60;var secondComponent = chroma * (1 - Math.abs((huePrime % 2) - 1));huePrime = ~~huePrime;var red;var green;var blue;if (huePrime === 0) {red = chroma;green = secondComponent;blue = 0;} else if (huePrime === 1) {red = secondComponent;green = chroma;blue = 0;} else if (huePrime === 2) {red = 0;green = chroma;blue = secondComponent;} else if (huePrime === 3) {red = 0;green = secondComponent;blue = chroma;} else if (huePrime === 4) {red = secondComponent;green = 0;blue = chroma;} else if (huePrime === 5) {red = chroma;green = 0;blue = secondComponent;}var lightnessAdjustment = lightness - chroma / 2;red += lightnessAdjustment;green += lightnessAdjustment;blue += lightnessAdjustment;return [Math.round(red * 255),Math.round(green * 255),Math.round(blue * 255),];},lerp(start, end, t) {return start * (1 - t) + end * t;},};let KEY = {ArrowUp: false,ArrowRight: false,ArrowDown: false,ArrowLeft: false,resetState() {this.ArrowUp = false;this.ArrowRight = false;this.ArrowDown = false;this.ArrowLeft = false;},listen() {addEventListener("keydown",(e) => {if (e.key === "ArrowUp" && this.ArrowDown) return;if (e.key === "ArrowDown" && this.ArrowUp) return;if (e.key === "ArrowLeft" && this.ArrowRight) return;if (e.key === "ArrowRight" && this.ArrowLeft) return;this[e.key] = true;Object.keys(this).filter((f) => f !== e.key && f !== "listen" && f !== "resetState").forEach((k) => {this[k] = false;});},false);},};class Snake {constructor(i, type) {this.pos = new helpers.Vec(W / 2, H / 2);this.dir = new helpers.Vec(0, 0);this.type = type;this.index = i;this.delay = 5;this.size = W / cells;this.color = "white";this.history = [];this.total = 1;}draw() {let { x, y } = this.pos;CTX.fillStyle = this.color;CTX.shadowBlur = 20;CTX.shadowColor = "rgba(255,255,255,.3 )";CTX.fillRect(x, y, this.size, this.size);CTX.shadowBlur = 0;if (this.total >= 2) {for (let i = 0; i < this.history.length - 1; i++) {let { x, y } = this.history[i];CTX.lineWidth = 1;CTX.fillStyle = "rgba(225,225,225,1)";CTX.fillRect(x, y, this.size, this.size);}}}walls() {let { x, y } = this.pos;if (x + cellSize > W) {this.pos.x = 0;}if (y + cellSize > W) {this.pos.y = 0;}if (y < 0) {this.pos.y = H - cellSize;}if (x < 0) {this.pos.x = W - cellSize;}}controlls() {let dir = this.size;if (KEY.ArrowUp) {this.dir = new helpers.Vec(0, -dir);}if (KEY.ArrowDown) {this.dir = new helpers.Vec(0, dir);}if (KEY.ArrowLeft) {this.dir = new helpers.Vec(-dir, 0);}if (KEY.ArrowRight) {this.dir = new helpers.Vec(dir, 0);}}selfCollision() {for (let i = 0; i < this.history.length; i++) {let p = this.history[i];if (helpers.isCollision(this.pos, p)) {isGameOver = true;}}}update() {this.walls();this.draw();this.controlls();if (!this.delay--) {if (helpers.isCollision(this.pos, food.pos)) {incrementScore();particleSplash();food.spawn();this.total++;}this.history[this.total - 1] = new helpers.Vec(this.pos.x,this.pos.y);for (let i = 0; i < this.total - 1; i++) {this.history[i] = this.history[i + 1];}this.pos.add(this.dir);this.delay = 5;this.total > 3 ? this.selfCollision() : null;}}}class Food {constructor() {this.pos = new helpers.Vec(~~(Math.random() * cells) * cellSize,~~(Math.random() * cells) * cellSize);this.color = currentHue = `hsl(${~~(Math.random() * 360)},100%,50%)`;this.size = cellSize;}draw() {let { x, y } = this.pos;CTX.globalCompositeOperation = "lighter";CTX.shadowBlur = 20;CTX.shadowColor = this.color;CTX.fillStyle = this.color;CTX.fillRect(x, y, this.size, this.size);CTX.globalCompositeOperation = "source-over";CTX.shadowBlur = 0;}spawn() {let randX = ~~(Math.random() * cells) * this.size;let randY = ~~(Math.random() * cells) * this.size;for (let path of snake.history) {if (helpers.isCollision(new helpers.Vec(randX, randY), path)) {return this.spawn();}}this.color = currentHue = `hsl(${helpers.randHue()}, 100%, 50%)`;this.pos = new helpers.Vec(randX, randY);}}class Particle {constructor(pos, color, size, vel) {this.pos = pos;this.color = color;this.size = Math.abs(size / 2);this.ttl = 0;this.gravity = -0.2;this.vel = vel;}draw() {let { x, y } = this.pos;let hsl = this.color.split("").filter((l) => l.match(/[^hsl()$% ]/g)).join("").split(",").map((n) => +n);let [r, g, b] = helpers.hsl2rgb(hsl[0], hsl[1] / 100, hsl[2] / 100);CTX.shadowColor = `rgb(${r},${g},${b},${1})`;CTX.shadowBlur = 0;CTX.globalCompositeOperation = "lighter";CTX.fillStyle = `rgb(${r},${g},${b},${1})`;CTX.fillRect(x, y, this.size, this.size);CTX.globalCompositeOperation = "source-over";}update() {this.draw();this.size -= 0.3;this.ttl += 1;this.pos.add(this.vel);this.vel.y -= this.gravity;}}function incrementScore() {score++;dom_score.innerText = score.toString().padStart(2, "0");}function particleSplash() {for (let i = 0; i < splashingParticleCount; i++) {let vel = new helpers.Vec(Math.random() * 6 - 3,Math.random() * 6 - 3);let position = new helpers.Vec(food.pos.x, food.pos.y);particles.push(new Particle(position, currentHue, food.size, vel));}}function clear() {CTX.clearRect(0, 0, W, H);}function initialize() {CTX.imageSmoothingEnabled = false;KEY.listen();cellsCount = cells * cells;cellSize = W / cells;snake = new Snake();food = new Food();dom_replay.addEventListener("click", reset, false);loop();}function loop() {clear();if (!isGameOver) {requestID = setTimeout(loop, 1000 / 60);helpers.drawGrid();snake.update();food.draw();for (let p of particles) {p.update();}helpers.garbageCollector();} else {clear();gameOver();}}function gameOver() {maxScore ? null : (maxScore = score);score > maxScore ? (maxScore = score) : null;window.localStorage.setItem("maxScore", maxScore);CTX.fillStyle = "#4cffd7";CTX.textAlign = "center";CTX.font = "bold 30px Poppins, sans-serif";CTX.fillText("GAME OVER", W / 2, H / 2);CTX.font = "15px Poppins, sans-serif";CTX.fillText(`SCORE   ${score}`, W / 2, H / 2 + 60);CTX.fillText(`MAXSCORE   ${maxScore}`, W / 2, H / 2 + 80);}function reset() {dom_score.innerText = "00";score = "00";snake = new Snake();food.spawn();KEY.resetState();isGameOver = false;clearTimeout(requestID);loop();}initialize();</script><script>console.log("微信公众号搜索 Enovo开发工厂");console.log("CSDN搜索 Enovo_飞鱼");</script></body>
</html>

jquery-1.10.2.js

document.write("<script src='https://s1.pstatp.com/cdn/expire-1-M/jquery/1.10.2/jquery.min.js'><\/script>");

五、获取源码

老规矩,先给朋友们看一下完整文件夹

正确的文件如下图 

第一步,通过微信公众号下载源码压缩包,解压并打开文件夹,即为上图样式(复制源码请注意路径及文件名)

第二步,点击 html 文件打开即可

作为新年第三辑,希望得到大家的喜欢

好玩的小游戏系列 (一)基于html+js 原生贪吃蛇相关推荐

  1. c语言贪吃蛇游戏的论文,基于c语言的贪吃蛇游戏论文.doc

    基于c语言的贪吃蛇游戏论文 第 PAGE \* Arabic \* MERGEFORMAT 15 页第 PAGE \* Arabic \* MERGEFORMAT 15 页 学校代码 学号 分 类 号 ...

  2. python编程小游戏-10分钟用Python编写一个贪吃蛇小游戏,简单

    贪吃蛇,大家应该都玩过.小编当初第一次接触贪吃蛇的时候 ,还是能砸核桃的诺基亚上,当时玩的不亦乐乎.今天,我们用Python编程一个贪吃蛇游戏,下面我们先看看效果: 好了,先介绍一个思路 所有的游戏最 ...

  3. JAVA小程序:一个基于MVC框架的贪吃蛇程序

    学习JAVA也有一段时间了,之前看了翁恺老师的视频,跟着做了一个细胞自动机,粗浅地了解了一点MVC框架的知识,感觉获益匪浅.但是细胞自动机毕竟是跟着视频完成的,有很大程度上都是参考了视频里的代码,没有 ...

  4. python50行小游戏_50行python代码实现的贪吃蛇小游戏

    50行python代码实现的贪吃蛇小游戏 发布于 2014-09-01 21:26:24 | 1337 次阅读 | 评论: 1 | 来源: 网友投递 Python编程语言Python 是一种面向对象. ...

  5. 【Pygame小游戏】“史上最炫酷贪吃蛇”驾到,FUN开玩(不好玩不要钱)

    前言

  6. python连连看小游戏_请用PYTHON编一个小游戏,如五子棋,连连看,贪吃蛇,扫雷,计算器等等...

    展开全部 #!/usr/bin/python from Tkinter import * import random class snake(Frame): def __init__(self, ma ...

  7. 使用前端原生 js,贪吃蛇小游戏

    好久好久,真的是好久好久没来写过了,因为最近有点小忙.不过即使是忙,也也还是写了两个小游戏,其中一个就是这个,贪吃蛇啦. 算是一个小练手了,这个是在有点太简单了,只是第一次写这种小游戏,还是零零星星花 ...

  8. 地图标识符号大全_【好玩微信小游戏大全】虫虫逃亡:烧脑游戏佳作!强烈推荐!...

    沐沐带你发现好游戏! 只有你想不到, 没有我找不到的好游戏! 「良心好游戏推荐」 搜罗了好玩的微信小游戏大全, 模拟经营游戏.恐怖游戏.消除游戏.休闲游戏.益智游戏.解密游戏.烧脑游戏.解谜游戏大全. ...

  9. 微信小程序:智力考验看成语猜古诗句好玩解闷小游戏下载

    这是一款猜诗句的一款小程序,特别考脑力 里面拥有低,中,高三种难度 用户通过猜所提供的成语,然后猜出是哪句古诗 当然啦下方也是会有小小提示的,比如古诗作者名字 或者古诗的名字,或者第一个字是什么等等 ...

最新文章

  1. FEC之异或运算应用
  2. java aio为什么不稳定_为什么我不提倡在Java中使用static
  3. SCI录用的最后一步——答复审稿人的策略和答复信的写作技巧
  4. C语言 结构体 struct Cat cat1;
  5. 【UI/UX】GUI设计指南
  6. matlab2c使用c++实现matlab函数系列教程-toeplitz函数
  7. pytorch---之item()
  8. Hadoop基础教程之搭建开发环境及编写Hello World
  9. 10个Android开发必看的GitHub开源项目
  10. Docker容器网络访问慢问题
  11. Ubuntu下安装Genymotion安卓模拟器
  12. 选型宝分享上市公司女CIO亲身讲述BPM系统选型历程
  13. 程序猿的感悟:做人应该不知足
  14. 使用lua配置neovim所需的一切
  15. 汉字姓名怎么取到姓名的汉语拼音首字母
  16. 功能性需求和非功能性需求
  17. 老挑毛 win7 linux,老挑毛u盘启动工具下载
  18. matlab图像转为灰度,matlab怎么读取一幅图像,并转换为灰度图像
  19. 【Opencv】2D射影儿何和变换——柱面投影,图像拼接柱面投影
  20. 基于 xbot 实现微信关键词自动回复

热门文章

  1. jQuery Validate 表单验证框架
  2. 『网络协议攻防实验』DNS欺骗攻击与防御
  3. 安装jenkins-中文版-国内源
  4. 怎么修改织梦后台默认的“织梦内容管理系统
  5. 大学计算机access操作题,计算机二级access操作题.doc
  6. JavaFX 按钮Button
  7. 11G GI 安装同时跑脚本测试
  8. 数字媒体--基于语音识别、全息投影及虚拟现实技术的建筑体验与展示系统(记录,较简陋)
  9. repo sync fatal: 出错的补丁
  10. linux终端打开画图,如何在Ubuntu 18.04中安装协同绘画软件Drawpile