先不多说先上图


下面是代码部分(这里你可以根据需要改变蛇头和身体还有食物的图片,然后默认的样式是使用纯颜色的如果没有更改我的背景图片的话------改这些图开始是想搞笑一下朋友哈哈哈,请不要在意哈),还有操作键是使用 ↑ ↓ ← → )

<!DOCTYPE html>
<html><head lang="en"><meta charset="UTF-8"><title>贪食蛇</title><style>.map {width: 800px;height: 600px;background-color: #ccc;position: relative;left: 50%;transform: translate(-50%);}#dv {color: whitesmoke;font-weight: 700;text-align: center;line-height: 50px;width: 150px;height: 50px;position: absolute;background-color: orange;border-radius: 10px;top: 50%;left: 50%;transform: translate(-50%);cursor: pointer;}</style>
</head><body><div class="map"><div id="dv">开始游戏</div></div><script>//食物:是一个对象,有宽,有高,有颜色,有横纵坐标//自调用函数(function () {var element = []; //用来保存每个小方块食物的function Food(x, y, width, height, color) {this.x = x || 0;this.y = y || 0;this.width = width || 20;this.height = height || 20;this.color = color || "green";}//为原型添加初始化的方法(作用:在页面上显示这个食物)//因为食物要在地图上显示,所以,需要地图的这个参数(map--就是页面上的.class=map的这个div)Food.prototype.init = function (map) {//先删除这个小食物//外部无法访问,此函数在自调用函数里面remove();//创建divvar div = document.createElement("div");//把div加到map里面map.appendChild(div);//获取div的样式div.style.width = this.width + "px";div.style.height = this.height + "px";div.style.backgroundColor = this.color;//脱离文档流div.style.position = "absolute";//横纵坐标先停止----随机产生this.x = parseInt(Math.random() * (map.offsetWidth / this.width)) * this.width;this.y = parseInt(Math.random() * (map.offsetHeight / this.height)) * this.height;div.style.left = this.x + "px";div.style.top = this.y + "px";//把div加入element数组中element.push(div);//改变食物的样式---改成自己喜欢的东西div.style.backgroundImage = "url(" + "../images/shi.png" + ")";div.style.backgroundRepeat = "no-repaet";div.style.backgroundSize = "cover";};//私有函数function remove() {for (var i = 0; i < element.length; i++) {var ele = element[i];//找到这个子元素的父级元素,然后删除这个子元素ele.parentNode.removeChild(ele);//再次把element中的这个子元素删除element.splice(i, 1);}}//把Food暴露给window,外部可以使用window.Food = Food;}());//自调用函数---小蛇(function () {//存放小蛇的每个身体部分var element = [];//小蛇的构造函数function Snake(width, height, driection) {this.width = width || 20;this.height = height || 20;//小蛇的身体this.body = [{x: 3,y: 2,color: "red"},{x: 2,y: 2,color: "orange"},{x: 1,y: 2,color: "orange"}];//方向this.driection = driection || "right";}//为原型添加方法---小蛇初始化的方法Snake.prototype.init = function (map) {//先删除之前的小蛇remove();//循环遍历创建divfor (var i = 0; i < this.body.length; i++) {//数组中的每个数组元素都是一个对象var obj = this.body[i];//创建divvar div = document.createElement("div");//把div加入地图map中map.appendChild(div);//设置div的样式div.style.position = "absolute";div.style.width = this.width + "px";div.style.height = this.height + "px";//横纵坐标div.style.left = obj.x * this.width + "px";div.style.top = obj.y * this.height + "px";//背景颜色div.style.backgroundColor = obj.color;//方向还没定//把div加入到element数组中---目的是为了删除//把div加入数组中element.push(div);//更改头部的----变成图片if (i == 0) {div.style.backgroundImage = "url(" + "../images/tou_03.png" + ")";div.style.backgroundRepeat = "no-repaet";div.style.backgroundSize = "cover";}//更改尾巴的样式照片if (i != 0) {div.style.backgroundImage = "url(" + "../images/shi.png" + ")";div.style.backgroundRepeat = "no-repaet";div.style.backgroundSize = "cover";}}};//为原型添加方法---小蛇动起来Snake.prototype.move = function (food, map) {var i = this.body.length - 1;for (; i > 0; i--) {this.body[i].x = this.body[i - 1].x;this.body[i].y = this.body[i - 1].y;}//判断方向---改变小蛇的头的坐标位置switch (this.driection) {case "left":this.body[0].x -= 1;break;case "right":this.body[0].x += 1;break;case "top":this.body[0].y -= 1;break;case "bottom":this.body[0].y += 1;break;}//判断有没有吃到食物//小蛇的头的坐标和食物的坐标一致var headX = this.body[0].x * this.width;var headY = this.body[0].y * this.height;//判断小蛇的头和食物坐标是否相同if (headX == food.x && headY == food.y) {//获取小蛇的最后的尾巴var last = this.body[this.body.length - 1];//把最后的蛇尾复制一个,重新的加入到小蛇的body中this.body.push({x: last.x,y: last.y,color: last.color});//把食物删除,重新初始化食物food.init(map);}};//删除小蛇的私有函数function remove() {//获取数组var i = element.length - 1;for (; i >= 0; i--) {var ele = element[i];//从map地图上删除这个子元素divele.parentNode.removeChild(ele);element.splice(i, 1);}}window.Snake = Snake;}());//自调用函数---游戏对象(function () {var that = null;//游戏的构造函数function game(map) {this.food = new Food(); //食物对象this.snake = new Snake(); //小蛇对象this.map = map; //地图that = this;}game.prototype.init = function () {//初始化游戏//食物初始化this.food.init(this.map);//小蛇初始化this.snake.init(this.map);that = this;document.getElementById("dv").onclick = function () {document.getElementById("dv").style.display = "none";//调用小蛇移动的方法that.runSnake(that.food, that.map);//调用按键的方法that.bindKey();}.bind(that);};//添加原型方法---设置小蛇可以自动跑起来game.prototype.runSnake = function (food, map) {//自动的去移动var time = 90;var fn = function () {//此时this是window//移动小蛇this.snake.move(food, map);//初始化小蛇this.snake.init(map);//横坐标的最大值var maxX = map.offsetWidth / this.snake.width;//纵坐标的最大值var maxY = map.offsetHeight / this.snake.height;//小蛇的头的坐标var headX = this.snake.body[0].x;var headY = this.snake.body[0].y;//判断 横坐标 有没撞墙if (headX < 0 || headX >= maxX) {//撞墙停止定时器clearInterval(timeId);alert("游戏结束");location.reload();}//判断 纵坐标 有没撞墙if (headY < 0 || headY >= maxY) {clearInterval(timeId);alert("游戏结束");location.reload();}//判断 小蛇的头部 有没有 撞到自己for (let i = 1; i < this.snake.body.length; i++) {let x = this.snake.body[i].x;let y = this.snake.body[i].y;if (headX === x && headY === y) {clearInterval(timeId);alert("游戏结束");location.reload();}}//增加游戏难度,判断 到达一定数量的时候 加速switch (true) {case 5 <= this.snake.body.length && this.snake.body.length <= 10:clearInterval(timeId);time = 60;timeId = setInterval(fn, time);break;case 10 <= this.snake.body.length && this.snake.body.length <= 15:clearInterval(timeId);time = 40;timeId = setInterval(fn, time);break;case 15 <= this.snake.body.length:clearInterval(timeId);time = 30;timeId = setInterval(fn, time);break;}console.log(this.snake.body.length + "--" + "time:" + time);}.bind(that);//定时器小蛇自运动var timeId = setInterval(fn, time);};//添加原型方法---设置用户按键,改变小蛇移动的方向game.prototype.bindKey = function () {//获取用户的按键,改变小蛇的移动方向document.addEventListener("keydown", function (e) {//获取按键的值并进行判断是,改变小蛇移动的方向switch (e.keyCode) {//没有bind方法时此时的this指向的是documencase 37:if (this.snake.driection != "right") {this.snake.driection = "left";}break;case 38:if (this.snake.driection != "bottom") {this.snake.driection = "top";}break;case 39:if (this.snake.driection != "left") {this.snake.driection = "right";}break;case 40:if (this.snake.driection != "top") {this.snake.driection = "bottom";}break;}}.bind(that), false);};//把game暴露给window,外部就可以访问game对象window.game = game;}());//初始化游戏对象var gm = new game(document.querySelector(".map"));//初始化游戏---开始游戏gm.init();</script>
</body></html>

我已经尽量给以上代码注上注释。希望能帮到更多朋友更好的理解贪食蛇游戏的实现思路!

原生js实现贪食蛇小游戏相关推荐

  1. 【第三篇:利用ChatGPT编写贪食蛇小游戏】

    好像现在最近对ChatGPT讨论越来越热,ChatGPT的出现应该会引发"一次新的社会变革",未来很多码农会失业啊!与其坐着被改变,不如尝试主动改变,我今天就利用ChatGPT编写 ...

  2. as 贪食蛇小游戏(一)

    刚想学as制作游戏,所以打算先写个贪食蛇小游戏练习下.. 说明:使用的开发工具为 flash builder4.6 首先创建一个as项目. 然后我们先来添加一个config as类将游戏的所有设置都存 ...

  3. 用Java开发贪食蛇小游戏

    用Java开发贪食蛇小游戏 一.实验内容 1.实现贪吃蛇游戏基本功能,屏幕上随机出现一个"食物",称为豆子,上下左右控制"蛇"的移动,吃到"豆子&qu ...

  4. 原生JS实现的h5小游戏-植物大战僵尸

    代码地址如下: http://www.demodashi.com/demo/12755.html 项目介绍 本项目是利用原生js实现的h5小游戏-植物大战僵尸,主要结合了一下自己对于h5小游戏的理解, ...

  5. html flappybird小游戏代码,原生js实现Flappy Bird小游戏

    这是一个特别简单的用原生js实现的一个小鸟游戏,比较简单,适合新手练习. html结构 css样式 #game { width: 800px; height: 600px; border: 1px s ...

  6. 原生js实现一个连连看小游戏(一)

    前几天使用原生的js写了一个连连看小游戏,地址:连连看(js),基本功能都实现了,运行截图为: 根据游戏规则获取开发思路 创建棋盘格 生成随机不重复数字 映射到棋盘格 鼠标点击事件 寻路,无通路,则到 ...

  7. 使用C++设计贪食蛇小游戏

    说明:所有代码均可在Visual Studio 2013上编译执行.并未测试在其它编译器上编译情况. 游戏规则 贪食蛇游戏要求玩家控制方向键(或WSAD键)来控制小蛇的前进方向,以使蛇吃掉面板上随即位 ...

  8. 嵌入式 贪食蛇小游戏

    (一)程序所包含的的模块 1)用图示的方式展示贪食蛇运行的过程. (二)系统设计过程 贪食蛇详细实现过程: (1)该游戏,首先进入欢迎界面,该技术使用的sdl的动画效果,用事件完成,用SDL_Blit ...

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

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

最新文章

  1. Xamarin ios C#苹果应用开发第二讲配置环境和编写代码
  2. 磁盘 分区 lvm之间await util的统计关系
  3. 阿里云专属数据库,重新定义云数据库新形态
  4. C 语言实例 - 约瑟夫生者死者小游戏
  5. BZOJ.4832.[Lydsy1704月赛]抵制克苏恩(期望DP)
  6. spring Bean的生命周期管理
  7. docker客户端和服务端
  8. php 扫描器源代码,php端口扫描器代码
  9. 云栖大会 | Greenplum 6.0内核优化解读和7.0展望
  10. 亲自动手制作来自MyBatis-Spring官网的chm格式帮助文件
  11. Git错误!:403错误
  12. 少有人知的 Python “重试机制“:tenacity
  13. 记PMP 考试2021/06/20总结(含笔记)
  14. opengl 多边形线框_OpenGL - 在纹理多边形上创建边框
  15. js+HTML实现组织结构图
  16. 两种最为常用的数据挖掘方法论
  17. CANopen eds模型总结
  18. MySQL入门语法(视频学习笔记)
  19. 毕业论文管理系统设计与实现(论文+源码)_kaic
  20. 腾讯通(RTX) 自动关闭 及解决方案

热门文章

  1. html表格中怎么将背景颜色虚化,如何在Photoshop中制作效果惊艳模糊背景!
  2. 什么是你最关键的人脉
  3. excel如何显示多个独立窗口
  4. 从免费共享经济到知识付费系统,都是如何抓住时代风口的
  5. 偏向锁-批量重偏向和批量撤销测试
  6. 正确的选择大于努力_选择正确技术的11个注意事项
  7. Java程序员跳槽之旅,离开京东,14面面试回顾和一点感想
  8. DANet Daul Attention位置和通道注意力(PAM&CAM)keras实现
  9. 鼠标手--IT人士/电脑使用者、网民的职业病,给网友们提个醒
  10. 团队协作工具--worktile