前言

这是一个网页版本的贪吃蛇项目,用了html和js实现,代码有很多注释,方便阅读,是一个不错的练手项目。

代码

1.html代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>GluttonousSnake</title><link rel = "stylesheet" href="../index.css">
</head>
<body><div class="content"><div class="btn statrtBtn"><input type = "image" src="../startGame.png"></div><div class="btn pausBtn"><input type = "image" src="../start.png"></div><div id = "snakeWrap"></div></div><script src = "index.js" ></script>
</body>
</html>

2.css样式

.content{width: 640px;height: 640px;margin: 100px auto;position: relative;
}
.btn{width: 100%;height: 100%;position: absolute;left: 0;top: 0;background-color: rgba(0,0,0,0.3);z-index: 2;
}.btn input{background: none;border: none;background-size: 100% 100%;cursor: pointer;outline: none;position: absolute;left: 50%;top:50%;
}.statrtBtn input
{width: 200px;height: 200px;margin-left: -100px;margin-top: -100px;
}.pausBtn{display: none;
}.pausBtn input{width: 128px;height: 128px;margin-left: -64px;margin-top: -64px;
}#snakeWrap{width: 600px;height: 600px;background: #225675;border: 20px solid #7dd9ff;position: relative;
}
#snakeWrap div{width: 20px;height: 20px;
}
.snakeBody{background-color: #9ddbb1;border-radius: 50%;
}

3.js代码

var sw = 20,//一个格子的宽sh = 20,//格子的高度tr = 30,//行数td = 30;var snake = null;
var food = null;//食物的实例
var game = null;//构造函数(构造方格)
function Square(x,y,classnmae,src)
{this.x = x*sw;this.y = y*sh;this.class = classnmae;//创建标签并添加标签this.viewContent = document.createElement('img');//格子对应的DOM元素this.viewContent.className = this.class;this.viewContent.src = src;this.parent = document.getElementById('snakeWrap');//格子的父级
}//创建格子DOM(添加)
Square.prototype.create = function ()
{this.viewContent.style.position = 'absolute';this.viewContent.style.width = sw + 'px';this.viewContent.style.height = sh + 'px';this.viewContent.style.left = this.x + 'px';this.viewContent.style.top = this.y + 'px';this.parent.appendChild(this.viewContent);//添加到页面
};
//删除格子DOM元素
Square.prototype.remove = function ()
{this.parent.removeChild(this.viewContent);
}//蛇的构造函数
function Snake()
{this.head = null;//保存蛇头的信息this.tail = null;this.pos = [];//保存蛇身方格的位置//存储蛇走的方向this.directionNum = {left:{x:-1,y:0,rotate:180},right:{x:1,y:0,rotate:0},up:{x:0,y:-1,rotate:-90},down:{x:0,y:1,rotate:90}}
}//初始化蛇
Snake.prototype.init = function ()
{//创建蛇头var snakeHead = new Square(2,0,'snakeHead', "../snake.png");snakeHead.create();this.head = snakeHead;//存储蛇头信息this.pos.push([2,0]);//存储蛇头的坐标//创建蛇身体第一个var snakeBody1 = new Square(1,0,'snakeBody',"../body.png");snakeBody1.create();this.pos.push([1,0]);//创建蛇身体第二个var snakeBody2 = new Square(0,0,'snakeBody',"../body.png");snakeBody2.create();this.tail = snakeBody2;//把蛇尾的信息存起来this.pos.push([0,0]);//让蛇形成链表关系snakeHead.last = null;snakeHead.next = snakeBody1;snakeBody1.last = snakeHead;snakeBody1.next = snakeBody2;snakeBody2.last = snakeBody1;snakeBody2.next = null;//给蛇添加一个属性,用来表示蛇走的方向this.direction = this.directionNum.right;
};//获取蛇头的下一个位置对应的元素
Snake.prototype.getNextPos = function ()
{//蛇头要走的下一个点的坐标var nextPos = [this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y];//下一个点是自己,代表撞到了自己,游戏结束var selfCollied = false;this.pos.forEach(function (value){if(value[0] == nextPos[0] && value[1] == nextPos[1]){selfCollied = true;}});if(selfCollied){console.log("撞到自己了!");this.strategies.die.call(this);return;}//下一个点是围墙,游戏结束if(nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > td-1 || nextPos[1] > tr -1 ){console.log("撞墙了!");this.strategies.die.call(this);return;}//条件成立,蛇头撞到食物if(food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]){this.strategies.eat.call(this);return;}//下一个点没有标记,继续走this.strategies.move.call(this);//this指向实例
}//使用call方法,能调用父类的实例
Snake.prototype.strategies ={move:function (format)//参数决定要不要删除最后一个方块{//创建新身体(在旧蛇头的位置)var newBody = new Square(this.head.x/sw,this.head.y/sh,'snakeBody',"../body.png");//更新链表的关系newBody.next = this.head.next;newBody.next.last = newBody;newBody.last = null;this.head.remove();//把旧蛇头从位置上删除newBody.create();//创建新的蛇头(蛇头下一个移动的点)var newHead = new Square(this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y,'snakeHead',"../snake.png");//更新链表的关系newHead.next = newBody;newHead.last = null;newBody.last = newHead;//旋转蛇头图像方向newHead.viewContent.style.transform = 'rotate('+this.direction.rotate+'deg)';newHead.create();//蛇身上的每一个坐标都要更新this.pos.splice(0,0,[this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y]);//更新蛇头的位置this.head = newHead;if(!format)//删除蛇尾{this.tail.remove();this.tail = this.tail.last;this.pos.pop();}},eat:function (){this.strategies.move.call(this,true);createFood();game.score ++;},die:function (){game.over();},
}//1.开始创建蛇头
snake = new Snake();
//2.碰撞后处理的事件
function createFood()
{//食物方格的随机坐标//1.食物不能出现在墙上//2.食物不能出现在蛇的身上var x = null;var y = null;var includeSnake = true;//为ture表示生成在蛇身上,那么就要继续生成食物while (includeSnake){x = Math.round(Math.random()*(td-1));y = Math.round(Math.random()*(tr-1));snake.pos.forEach(function (value){if(x != value[0] && y != value[1]){includeSnake = false;}});//生成食物food = new Square(x,y,'food',"../food.png");food.pos = [x,y];//存储食物坐标,用与判断是否与蛇头相撞var foodDom = document.querySelector('.food');if(foodDom){foodDom.style.left = x*sw+'px';foodDom.style.top = y*sh+'px';}else{food.create();}}
}function Game()
{this.timer = null;this.score = 0;
}Game.prototype.init = function ()
{snake.init();createFood();document.onkeydown = function (ev){if(ev.which === 37 && snake.direction != snake.directionNum.right)//用户按下左键时,蛇的移动方向不能是向右{snake.direction = snake.directionNum.left;}else if(ev.which === 38 && snake.direction != snake.directionNum.down){snake.direction = snake.directionNum.up;}else if(ev.which === 39 && snake.direction != snake.directionNum.left){snake.direction = snake.directionNum.right;}else if(ev.which === 40 && snake.direction != snake.directionNum.up){snake.direction = snake.directionNum.down;}}this.start();
}Game.prototype.start = function ()
{this.timer = setInterval(function (){snake.getNextPos();},200);
}Game.prototype.pause = function ()
{clearInterval(this.timer);
}Game.prototype.over = function ()
{clearInterval(this.timer);alert("当前得分为:" + this.score);//游戏回到最初的状态var snakeWrap = document.getElementById('snakeWrap');snakeWrap.innerHTML = '';snake = new Snake();game = new Game();var startBtnWrap = document.querySelector('.statrtBtn');startBtnWrap.style.display = 'block';}//开启游戏
game = new Game();
var startBtn = document.querySelector('.statrtBtn input');
startBtn.onclick = function ()
{startBtn.parentNode.style.display = 'none';game.init();
};//暂停游戏
var snakeWrap = document.getElementById('snakeWrap');
var pauseBtn = document.querySelector('.pausBtn input');
snakeWrap.onclick = function ()
{game.pause();pauseBtn.parentNode.style.display = 'block';
}pauseBtn.onclick = function ()
{game.start();pauseBtn.parentNode.style.display = 'none';
}

4.实现效果

5.整个项目的源码与资源:https://download.csdn.net/download/matt45m/85073431

javascript实战项目——网页版贪吃蛇相关推荐

  1. 基于JavaScript实现的网页版贪吃蛇

    效果截图 实现原理 通过div布局来实现贪吃蛇小游戏,html+JavaScript实现, 通过方向键的上下左右实现蛇的移动 首先,地图为一个二维数组 Map[*][*] 蛇的坐标分为X轴和Y轴 即 ...

  2. H5网页版贪吃蛇源代码

    H5网页版贪吃蛇源代码,新建文本文档,将下面的代码复制粘贴到文本文档,然后保存文件.重命名文件及后缀名为index.html.将文章最下面的两个图片保存下来,蓝色背景大图重命名为back.jpg,骷髅 ...

  3. 网页版贪吃蛇(HTML 5)

    (文字描述太繁琐了, 贪吃蛇算法很经典不多说, 那个伪播放器,不值一提.) 源码: 网页版贪吃蛇 [http://files.cnblogs.com/crystalplus/%E4%B8%A4%E4% ...

  4. 软件实习项目2——贪吃喵(猫吃鱼版贪吃蛇)(代码实现)

    软件实习项目2--贪吃喵(猫吃鱼版贪吃蛇)(代码实现) 类变量的定义以及类的初始化__init__ 一.游戏的逻辑 1.猫头的生成 2.鱼的生成 3.猫头和鱼骨的移动 4.按下键盘,改变方向 二.主窗 ...

  5. 软件实习项目2——贪吃喵(猫吃鱼版贪吃蛇)(实验准备与设计)

    软件实习项目2--贪吃喵(猫吃鱼版贪吃蛇)(实验准备与设计) 实验内容 编程语言以及开发环境的选择 实验思路(游戏设计) 一.游戏的逻辑设计 1.猫头的生成 2.鱼的生成 3.猫头和鱼骨的移动 4.按 ...

  6. 软件实习项目2——贪吃喵(猫吃鱼版贪吃蛇)(成品展示)

    软件实习项目2--贪吃喵(猫吃鱼版贪吃蛇)(成品展示) 成品展示 1.开始游戏界面 2.游戏主界面 3.结束游戏界面 视频演示 成品展示 1.开始游戏界面 速度选择: 猫咪类型选择: 2.游戏主界面 ...

  7. 简易贪吃蛇小游戏java版_用GUI实现java版贪吃蛇小游戏

    本文实例为大家分享了java版贪吃蛇小游戏的具体代码,供大家参考,具体内容如下 项目结构 新建一个JFrame窗口,作为程序入口 public class GameStart{ public stat ...

  8. 如何用python制作贪吃蛇以及AI版贪吃蛇

    用python制作普通贪吃蛇 哈喽,大家不知道是上午好还是中午好还是下午好还是晚上好! 贪吃蛇,应该是90后小时候的记忆(连我这个00后也不例外),今天,我们就用python这款编程语言来实现贪吃蛇 ...

  9. html5+javascript+css实现---网页版坦克大战---无需运行环境

    html5+javascript+css实现-网页版坦克大战-无需运行环境,只需一个浏览器,重拾少年情. 运行环境-除老版IE浏览器都可以: 源码需要请:点赞留言邮箱: 可以跳关,回退关卡.支持双人坦 ...

最新文章

  1. 上线前一个小时,dubbo这个问题可把我折腾惨了
  2. 【java下午茶系列】java三重奏之封装
  3. mysql 函数,关键字,特性
  4. windows卸载程序提示“请等待当前程序完成卸载或更改“问题解决方法,windows卸载卡进程问题解决方法
  5. Tomcat+Nginx+Memcached集群部署
  6. 核心技术靠化缘是要不来的——自己动手写ORM框架
  7. 【Spark】Spark基础教程知识点
  8. 我是服务的执政官-服务发现和注册工具consul简介
  9. 面趣 | 马云在面试中出的一道题,据说只有一个人答对……
  10. mysql8.0.20 64位安装教程_MySQL8.0.20压缩版本安装教程图文详解
  11. 非刚性配准(Non-rigid ICP )
  12. 【比原链】比原启动后去哪里连接别的节点
  13. 大数据排重算法-布隆算法(BloomFilter)
  14. 掌门教育微服务体系 Solar(下)
  15. 让chrome浏览器支持ajax跨域
  16. 终极解决maya渲染层丢材质,变线框等问题
  17. 函数的单调性与极值点
  18. 关于应用界面引导性的设计模式
  19. ubutnu18+cuda11.1+cudnn8.0.4+nvidia-driver-465
  20. 内网穿透工具---frp使用教程

热门文章

  1. python读取二进制数据中的while循环_在Python中读取二进制文件并循环遍历每个字节...
  2. MySQL流程控制if、case、循环结构while的使用语法
  3. getline读取不等待输入的问题
  4. C++中的hash_map和map的区别
  5. 小白视觉第一步保存图片
  6. Faster R-CNN论文笔记——FR
  7. 微服务架构下分布式事务解决方案 —— 阿里GTS
  8. Java 多线程:synchronized 关键字用法(修饰类,方法,静态方法,代码块)
  9. JavaScript 内置对象(二):Date 对象(构造函数、属性和方法)
  10. SpringMVC运行报错 unable to find resource 'XXX.vm' in any resource loader