JS实现贪吃蛇游戏


Posted in Javascript onNovember 15, 2019

本文实例为大家分享了JS实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

html部分:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <link rel="stylesheet" href="./css/index.css" rel="external nofollow" >
 <title>贪吃蛇小游戏</title>
</head>
<body>
 <div class="content">
 <div class="btn startBtn"><button></button></div>
 <div class="btn pauseBtn"><button></button></div>
 <div id="snakeWrap">
 
 </div>
 </div>
 <script src="./js/index.js"></script>
</body>
</html>

css部分:

.content{
 width: 640px;
 height: 640px;
 margin: 50px auto;
 position: relative;
}
.btn{
 width: 100%;
 height: 100%;
 position: absolute;
 left: 0;
 top: 0;
 background-color: rgba(0,0,0,0);
 z-index: 1;
}
.btn button{
 background: none;
 border:none;
 background-size: 100% 100%;
 cursor: pointer;
 outline: none;
 position: absolute;
 left: 50%;
 top: 50%;
}
.startBtn button{
 width: 200px;
 height: 150px;
 background-image: url('../images/btn1.gif');
 margin-left: -100px;
 margin-top: -75px;
}
.pauseBtn{
 display: none;
}
.pauseBtn button{
 width: 70px;
 height: 70px;
 background-image: url('../images/btn4.png');
 margin-left: -35px;
 margin-top: -35px;
}
#snakeWrap{
 position: relative;
 width: 600px;
 height: 600px;
 background: #FCE4EC;
 border: 20px solid #F8BBD0;
}
.snakeHead{
 background-image: url('../images/snake.png');
 background-size: cover;
}
.snakeBody{
 background-color: #9CCC65;
 border-radius: 50%;
}
.food{
 background: url('../images/food2.png') no-repeat;
 background-size: 100% 100%;
}

js部分:

var sw = 20, // 一个方块的宽度
 sh = 20, // 高度
 tr = 30, // 行数
 td = 30; // 列数

var snake = null, // 蛇的实例
 food = null, // 食物的实例
 game = null; // 游戏实例

// 方块构造函数
function Square(x,y,classname) {
 this.x = x*sw;
 this.y = y*sh;
 this.class = classname;

 this.viewContent = document.createElement('div');
 this.viewContent.className = this.class;
 this.parent = document.getElementById('snakeWrap');

}

Square.prototype.create = function(){ // 创建方块dom
 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)

}

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');
 snakeHead.create();
 this.head = snakeHead; // 存储蛇头信息
 this.pos.push([2,0]) // 存储蛇头位置
 // 创建蛇身体
 var snakeBody1 = new Square(1,0,'snakeBody');
 snakeBody1.create();
 this.pos.push([1,0]) // 存储蛇身1位置

 var snakeBody2 = new Square(0,0,'snakeBody');
 snakeBody2.create();
 this.tail = snakeBody2; // 存储蛇尾信息
 this.pos.push([0,0]) // 存储蛇身1位置

 // 形成链表关系
 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]){
 // 如果这个条件成立说明现在蛇头要走的下一个点是食物的那个点;
 console.log('吃到食物了');
 this.strategies.eat.call(this);
 return;
 }


 // 下个点什么都不是,走
 this.strategies.move.call(this);
 
};

// 处理碰撞后要做的事
Snake.prototype.strategies = {
 move:function(format) { // 该参数用于决定是否删除蛇尾
 // 创建新身体,在旧蛇头的位置
 var newBody = new Square(this.head.x/sw,this.head.y/sh,'snakeBody');
 // 更新链表的关系
 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');
 
 // 更新链表的关系
 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; //更新this.head
 
 if(!format){ // false: 需要删除(处理吃之外的操作)
 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();
 }
}

snake = new Snake();
// snake.init();

// 创建食物
function createFood(){
 // 食物的随机坐标
 var x = null;
 var y = null;
 var include = true; // 循环跳出的条件,true表示食物坐标在蛇身上,false:表示不在
 while(include){
 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]){
 // 坐标不在蛇身上
 include = false;
 }
 })
 // 生成食物
 food = new Square(x,y,'food');
 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('.startBtn');
 startBtnWrap.style.display = 'block';
}


// 开启游戏
game = new Game();

var startBtn = document.querySelector('.startBtn button');
startBtn.onclick = function(){
 startBtn.parentNode.style.display = 'none';
 game.init();
}

// 暂停游戏
var snakeWrap = document.getElementById('snakeWrap');
var pauseBtn = document.querySelector('.pauseBtn button');
snakeWrap.onclick = function() {
 game.pause();
 pauseBtn.parentNode.style.display='block';
}
pauseBtn.onclick = function() {
 game.start();
 pauseBtn.parentNode.style.display='none';
}

游戏截图:

JS实现贪吃蛇游戏

JS实现贪吃蛇游戏

更多关于Js游戏的精彩文章,请查看专题: 《JavaScript经典游戏 玩不停》

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
用Javascript做flash做的事..才完成的一个类.Auntion Action var 0.1
Feb 23 Javascript
jQuery在html有效在jsp无效的原因及解决方法
Aug 02 Javascript
对new functionName()定义一个函数的理解
May 22 Javascript
jQuery使用before()和after()在元素前后添加内容的方法
Mar 26 Javascript
wangEditor编辑器失去焦点后仍然可以在原位置插入图片分析
May 06 Javascript
JS如何生成一个不重复的ID的函数
Dec 25 Javascript
Vue的事件响应式进度条组件实例详解
Feb 04 Javascript
iview日期控件,双向绑定日期格式的方法
Mar 15 Javascript
JS实现中英文混合文字溢出友好截取功能
Aug 06 Javascript
node链接mongodb数据库的方法详解【阿里云服务器环境ubuntu】
Mar 07 Javascript
vue 项目中当访问路由不存在的时候默认访问404页面操作
Aug 31 Javascript
JS高级程序设计之class继承重点详解
Jul 07 Javascript
Layui表格监听行单双击事件讲解
Nov 14 #Javascript
layui table表格数据的新增,修改,删除,查询,双击获取行数据方式
Nov 14 #Javascript
解决Layui数据表格显示无数据提示的问题
Nov 14 #Javascript
layui写后台表格思路和赋值用法详解
Nov 14 #Javascript
Layui实现主窗口和Iframe层参数传递
Nov 14 #Javascript
layui 弹出层值回传解决方式
Nov 14 #Javascript
vue使用swiper.js重叠轮播组建样式
Nov 14 #Javascript
You might like
PHP中文件缓存转内存缓存的方法
2011/12/06 PHP
php使用filter过滤器验证邮箱 ipv6地址 url验证
2013/12/25 PHP
php网页病毒清除类
2014/12/08 PHP
php删除一个路径下的所有文件夹和文件的方法
2018/02/07 PHP
Laravel框架实现的rbac权限管理操作示例
2019/01/16 PHP
FireFox与IE 下js兼容触发click事件的代码
2008/11/20 Javascript
JavaScript下利用fso判断文件是否存在的代码
2010/12/11 Javascript
如何用JavaScript动态呼叫函数(两种方式)
2013/05/03 Javascript
用javascript为页面添加天气显示实现思路及代码
2013/12/02 Javascript
JS 获取浏览器和屏幕宽高等信息代码
2014/03/31 Javascript
基于 Docker 开发 NodeJS 应用
2014/07/30 NodeJs
Javascript实现鼠标框选操作  不是点击选取
2016/04/14 Javascript
jQuery.Uploadify插件实现带进度条的批量上传功能
2016/06/08 Javascript
SelecT下拉框选中和取值的解决方法
2016/11/22 Javascript
详解JavaScript中的属性和特性
2016/12/08 Javascript
jQuery获取Table某列的值(推荐)
2017/03/03 Javascript
jQuery、layer实现弹出层的打开、关闭功能
2017/06/28 jQuery
vue router2.0二级路由的简单使用
2017/07/05 Javascript
jQuery中each循环的跳出和结束实例
2017/08/16 jQuery
ES6 javascript中class类的get与set用法实例分析
2017/10/30 Javascript
JS构造一个html文本内容成文件流形式发送到后台
2018/07/31 Javascript
layui-laydate时间日历控件使用方法详解
2018/11/15 Javascript
Javascript之高级数组API的使用实例
2019/03/08 Javascript
vux-scroller实现移动端上拉加载功能过程解析
2019/10/08 Javascript
JQuery表单元素取值赋值方法总结
2020/05/12 jQuery
[40:05]DOTA2上海特级锦标赛A组小组赛#1 EHOME VS MVP.Phx第一局
2016/02/25 DOTA
[原创]教女朋友学Python(一)运行环境搭建
2017/11/29 Python
浅析PyTorch中nn.Module的使用
2019/08/18 Python
在PyTorch中Tensor的查找和筛选例子
2019/08/18 Python
python3列表删除大量重复元素remove()方法的问题详解
2021/01/04 Python
施工人员岗位职责
2013/12/12 职场文书
《长相思》听课反思
2014/04/10 职场文书
电子商务系毕业生自荐信
2014/05/29 职场文书
2014年创先争优工作总结
2014/12/11 职场文书
二审代理词范文
2015/05/25 职场文书
赵氏孤儿观后感
2015/06/09 职场文书