最近学习Vue和webpack,恰好搞个小游戏练练手。
2048游戏规则:css
每次能够选择上下左右其中一个方向去滑动,每滑动一次,全部的数字方块都会往滑动的方向靠拢外,系统也会在空白的地方乱数出现一个数字方块,相同数字的方块在靠拢、相撞时会相加。不断的叠加最终拼凑出2048这个数字就算成功。html
固然有些细微的合并规则,好比:
当向左滑动时,某列2 2 2 2 合并成 4 4 0 0 而非 8 0 0 0
也就是说,同列的某个数字最多只被合并一次。
在线挑战一把?(瞎折腾一阵后发现移动端没法正常显示了,赶忙调试去)
http://www.ccc5.cc/2048/
移动端扫下面的二维码便可(微信会转码,请点击扫描后底部的‘访问原网页’)vue
4x4的方格,用一个16个成员的数组表示。当某个方格没有数字的时候用''表示;node
建立Vue的模板,绑定数据,处理数据与相关class的关系;webpack
把数组看成一个4x4的矩阵,专一数据方面的处理,Dom方面的就交给vue更新ios
<template> <div id="app"> <ul> <li class='box' v-for="num in nums" v-text="num" v-getclass="num" v-getposition="$index" track-by="$index"></li> </ul> <button @click="reset()">重置</button> </div> </template>
其中getclass
与getposition
为自定义指令:git
getclass
根据当前框数字设置不一样的classgithub
getposition
根据当前框的索引位置,设置css样式的top
与left
web
初始化一个长度为16的数组,而后随机选两个地方填入2或者4。算法
<script> export default { data () { return { nums : [] //记录16个框格的数字 } }, ready: function () { localStorage['save'] ? this.nums = JSON.parse(localStorage['save']) : this.reset(); }, methods:{ /*在一个随机的空白位添加2或4 几率9:1*/ randomAdd(){ let arr = this.shuffle(this.blankIndex()); //延时100毫秒添加 setTimeout(_=>{ this.nums.$set(arr.pop(),Math.random()>0.9 ? 4 : 2); },100); }, /*获取当前空白框索引组成的数组*/ blankIndex(){ let arr = []; this.nums.forEach((i,j)=>{ i==='' && arr.push(j); }); return arr; }, /*打乱数组*/ shuffle(arr){ let l = arr.length,j; while(l--){ j = parseInt(Math.random()*l); [arr[l],arr[j]] = [arr[j],arr[l]] } return arr; }, //保存游戏进度 save(){ localStorage['save'] = JSON.stringify(this.nums); }, //重置游戏 reset(){ this.nums = Array(16).fill(''); let i =0; while(i++<2){ //随机添加2个 this.randomAdd(); } } } } </script>
这里有必要说明下,在segmentfault看到不少人洗牌算法习惯这么写:
var arr = arr.sort(_=> { return Math.random() - 0.5 });
可是通过不少人的测试,这样洗牌实际上是不太乱的,具体参考
数组的彻底随机排列:https://www.h5jun.com/post/ar...
如何测试洗牌程序:http://coolshell.cn/articles/...
继续回到主题,数据初始化完成以后,添加两个自定义指令,功能前面已经讲过了,实现也很简单,
方格里面数字不一样,对应的class不同,我这里定义的规则是
数字2对应.s2
数字4对应.s4
...
<script> directives:{ getclass(value) { let classes = this.el.classList; /* //移动端貌似对classList的forEach支持不完善 //我在ios上调试了好久才找到是这里的缘由致使以前移动端无法正常运行 classes.forEach(_=>{ if(/^s\w+$/.test(_))classes.remove(_); });*/ Array.prototype.forEach.call(classes,_=>{ if(/^s\w+$/.test(_))classes.remove(_); }); value ? classes.add('s' + value) : classes.add('empty'); }, getposition(index){ this.el.style.left = index%4*25 + '%'; this.el.style.top = Math.floor(index/4)*25 + '%'; } } </script>
监听4个方向键和移动端的滑动事件,在ready环节处理
ready: function () { document.addEventListener('keyup', this.keyDown); document.querySelector('#app ul').addEventListener('touchstart', this.touchStart); document.querySelector('#app ul').addEventListener('touchend', this.touchEnd); //document上获取touchmove事件 若是是由.box触发的 则禁止屏幕滚动 document.addEventListener('touchmove', e=>{ e.target.classList.contains('box') && e.preventDefault(); }); }, methods:{ touchStart(e){ //在start中记录开始触摸的点 this.start['x'] = e.changedTouches[0].pageX; this.start['y'] = e.changedTouches[0].pageY; }, touchEnd(e){ //handle... }, /* *方向键 事件处理 */ keyDown(e){ //handle... } }
咱们将nums这个数组想象成一个4x4的方阵。
2 2 2 2 x x x x x x x x x x x x
当向左
合并的时候,以第一列来讲,从左至右:
inxde=0位置的2在合并时是不须要动的,index=1位置的2和index=0位置的2数值相同,合并成4,放在index=0的位置,第一列变成4 '' 2 2
index=2位置的2,向左挪到index=1空出的位置,变成4 2 '' 2
,同时,index=3位置的2一直向左运动,直到碰上index=1处的2,两者在这轮都没有过合并,因此这里能够合并为4 4 '' ''
从这里咱们能够看出,向左
运动时,最左的位置,也就是index%4 === 0
的位置,是无需挪动的,其余位置,如有数字,其左侧有空位的话则向左挪动一位,其左侧有个与其相同的数字时,且两者在此轮中没有合并过,则两者合并,空出当前位:
2 2 2 2
=> 4 4 '' ''
4 2 2 2
=> 4 4 2 ''
'' 4 2 2
=> 4 4 '' ''
2 2 4 2
=> 4 4 2 ''
...
若是打算将向上,向右,向下都这么处理一遍并不是不能够,但比较容易出错。咱们既然都将nums想象成了一个4x4的方阵,那么何不将该方阵旋转一下呢。
当向下
运动时,咱们先将nums利用算法将想象中的方阵顺时针旋转一次,而后能够用向左
运动处理的方法合并、移动方格,完毕后再顺时针旋转3次,或者逆时针旋转1次还原便可。
旋转算法:
<script> methods{ //... //arr 须要旋转的数组 //n 顺时针选择n次 T(arr,n){ n=n%4; if(n===0)return arr; var l = arr.length,d = Math.sqrt(l),tmp = []; for(var i=0;i<d;i+=1) for(var j=0;j<d;j+=1) tmp[d-i-1+j*d] = arr[i*d+j]; if(n>1)tmp=this.T(tmp,n-1); return tmp; } //... } </script>
有了这个函数,咱们就只要写向左
运动的处理函数了
<script> move(){ let hasMove = false, //一次操做有移动方块时才添加方块 /* *记录已经合并过一次的位置 避免重复合并 *如 2 2 4 4 在一次合并后应为 4 8 0 0 而非8 4 0 0 */ hasCombin = {}; tmp.forEach((j,k)=>{ while(k%4 && j!==''){ if(tmp[k-1] === ''){ //当前位置的前一位置为空,交换俩位置 tmp[k-1] = j; tmp[k] = ''; hasMove = true; if(hasCombin[k]){//当前位有过合并,随着挪动,也要标记到前面去 hasCombin[k-1] = true; hasCombin[k] = false; } }else if(tmp[k-1] === j && !hasCombin[k] && !hasCombin[k-1]){ //当前位置与前一位置数字相同,合并到前一位置,而后清空当前位置 j *= 2; tmp[k-1] = j; tmp[k] = ''; hasMove = true; hasCombin[k-1] = true; //记录合并位置 }else{ break; } k--; } }); } </script>
详细的方向转换及处理过程
<script> methods:{ /*把数组arr当成矩阵,顺时针转置n次*/ T(arr,n){ n=n%4; if(n===0)return arr; var l = arr.length,d = Math.sqrt(l),tmp = []; for(var i=0;i<d;i+=1) for(var j=0;j<d;j+=1) tmp[d-i-1+j*d] = arr[i*d+j]; if(n>1)tmp=this.T(tmp,n-1); return tmp; }, touchStart(e){ this.start['x'] = e.changedTouches[0].pageX; this.start['y'] = e.changedTouches[0].pageY; }, touchEnd(e){ let curPoint = e.changedTouches[0], x = curPoint.pageX - this.start.x, y = curPoint.pageY - this.start.y, xx = Math.abs(x), yy = Math.abs(y), i = 0; //移动范围过小 不处理 if(xx < 50 && yy < 50)return; if( xx >= yy){ //横向滑动 i = x < 0 ? 0 : 2; }else{//纵向滑动 i = y < 0 ? 3 : 1; } this.handle(i); }, /* *方向键 事件处理 *把上、右、下方向经过旋转 变成左向操做 */ keyDown(e){ //左上右下 分别转置0 3 2 1 次 const map = {37:0,38:3,39:2,40:1}; if(!(e.keyCode in map))return; this.handle(map[e.keyCode]); }, handle(i){ this.move(i); this.save(); }, /*移动滑块 i:转置次数 */ move(i){ let tmp = this.T(this.nums,i),//把任意方向键转置,当成向左移动 hasMove = false, //一次操做有移动方块时才添加方块 /* *记录已经合并过一次的位置 避免重复合并 *如 2 2 4 4 在一次合并后应为 4 8 0 0 而非8 4 0 0 */ hasCombin = {}; tmp.forEach((j,k)=>{ while(k%4 && j!==''){ if(tmp[k-1] === ''){ //当前位置的前一位置为空,交换俩位置 tmp[k-1] = j; tmp[k] = ''; hasMove = true; if(hasCombin[k]){ hasCombin[k-1] = true; hasCombin[k] = false; } }else if(tmp[k-1] === j && !hasCombin[k] && !hasCombin[k-1]){ //当前位置与前一位置数字相同,合并到前一位置,而后清空当前位置 j *= 2; tmp[k-1] = j; tmp[k] = ''; hasMove = true; hasCombin[k-1] = true; //记录合并位置 }else{ break; } k--; } }); this.nums = this.T(tmp,4-i);//转置回去,把数据还给this.nums hasMove && this.randomAdd();//有数字挪动才添加新数字 } } </script>
当全部的16个方格都已经被填满,且横向与纵向都没法合并时,游戏结束
isPass(){ let isOver=true,hasPass=false,tmp = this.T(this.nums,1); this.nums.forEach((i,j)=>{ if(this.nums[j-4] == i || this.nums[j+4] == i || tmp[j-4] == tmp[j] || tmp[j+4] == tmp[j]){ isOver = false; } if(i==2048){ hasPass = true; } }); if(!this.blankIndex().length){ isOver && alert('游戏结束!'); }; }
。。。。。。。。
如何才能PASS?你有本事能够玩到很恐怖的数字。具体能玩到多少须要用数学证实吧,已有知乎大神证实,估计在3884450左右。传送门https://www.zhihu.com/questio...
奉上所有代码app.vue
<template> <div id="app"> <ul> <li class='box' v-for="num in nums" v-text="num" v-getclass="num" v-getposition="$index" track-by="$index"></li> </ul> <button @click="reset()">重置</button> </div> </template> <script> export default { data () { return { start : {}, //记录移动端触摸起始点 nums : [] //记录15个框格的数字 } }, ready: function () { document.addEventListener('keyup', this.keyDown); document.querySelector('#app ul').addEventListener('touchstart', this.touchStart); document.querySelector('#app ul').addEventListener('touchend', this.touchEnd); //document上获取touchmove事件 若是是由.box触发的 则禁止屏幕滚动 document.addEventListener('touchmove', e=>{ e.target.classList.contains('box') && e.preventDefault(); }); localStorage['save'] ? this.nums = JSON.parse(localStorage['save']) : this.reset(); }, directives:{ getclass(value) { let classes = this.el.classList; classes.forEach(_=>{ if(/^s\w+$/.test(_))classes.remove(_); }); value ? classes.add('s' + value) : classes.add('empty'); }, getposition(index){ this.el.style.left = index%4*25 + '%'; this.el.style.top = Math.floor(index/4)*25 + '%'; } }, methods:{ /*在一个随机的空白位添加2或4 几率9:1*/ randomAdd(){ let arr = this.shuffle(this.blankIndex()); //延时100毫秒添加 setTimeout(_=>{ this.nums.$set(arr.pop(),Math.random()>0.9 ? 4 : 2); },100); }, /*获取当前空白隔索引组成的数组*/ blankIndex(){ let arr = []; this.nums.forEach(function(i,j){ i==='' && arr.push(j); }); return arr; }, /*打乱数组*/ shuffle(arr){ let l = arr.length,j; while(l--){ j = parseInt(Math.random()*l); [arr[l],arr[j]] = [arr[j],arr[l]] } return arr; }, /*把数组arr当成矩阵,转置n次*/ /* [1,2, 1次转置变为 [3,1, 3,4] 4,2] */ T(arr,n){ n=n%4; if(n===0)return arr; var l = arr.length,d = Math.sqrt(l),tmp = []; for(var i=0;i<d;i+=1) for(var j=0;j<d;j+=1) tmp[d-i-1+j*d] = arr[i*d+j]; if(n>1)tmp=this.T(tmp,n-1); return tmp; }, touchStart(e){ this.start['x'] = e.changedTouches[0].pageX; this.start['y'] = e.changedTouches[0].pageY; }, touchEnd(e){ let curPoint = e.changedTouches[0], x = curPoint.pageX - this.start.x, y = curPoint.pageY - this.start.y, xx = Math.abs(x), yy = Math.abs(y), i = 0; //移动范围过小 不处理 if(xx < 50 && yy < 50)return; if( xx >= yy){ //横向滑动 i = x < 0 ? 0 : 2; }else{//纵向滑动 i = y < 0 ? 3 : 1; } this.handle(i); }, /* *方向键 事件处理 *把上、右、下方向经过旋转 变成左向操做 */ keyDown(e){ //左上右下 分别转置0 3 2 1 次 const map = {37:0,38:3,39:2,40:1}; if(!(e.keyCode in map))return; this.handle(map[e.keyCode]); }, handle(i){ this.move(i); this.save(); this.isPass();//判断是否过关 }, /*移动滑块 i:转置次数 */ move(i){ let tmp = this.T(this.nums,i),//把任意方向键转置,当成向左移动 hasMove = false, //一次操做有移动方块时才添加方块 /* *记录已经合并过一次的位置 避免重复合并 *如 2 2 4 4 在一次合并后应为 4 8 0 0 而非8 4 0 0 */ hasCombin = {}; tmp.forEach((j,k)=>{ while(k%4 && j!==''){ if(tmp[k-1] === ''){ //当前位置的前一位置为空,交换俩位置 tmp[k-1] = j; tmp[k] = ''; hasMove = true; if(hasCombin[k]){ hasCombin[k-1] = true; hasCombin[k] = false; } }else if(tmp[k-1] === j && !hasCombin[k] && !hasCombin[k-1]){ //当前位置与前一位置数字相同,合并到前一位置,而后清空当前位置 j *= 2; tmp[k-1] = j; tmp[k] = ''; hasMove = true; hasCombin[k-1] = true; //记录合并位置 }else{ break; } k--; } }); this.nums = this.T(tmp,4-i);//转置回去,把数据还给this.nums hasMove && this.randomAdd(); }, save(){ localStorage['save'] = JSON.stringify(this.nums); }, //重置游戏 reset(){ this.nums = Array(16).fill(''); let i =0; while(i++<2){ //随机添加2个 this.randomAdd(); } }, isPass(){ let isOver=true,hasPass=false,tmp = this.T(this.nums,1); this.nums.forEach((i,j)=>{ if(this.nums[j-4] == i || this.nums[j+4] == i || tmp[j-4] == tmp[j] || tmp[j+4] == tmp[j]){ isOver = false; } if(i==2048){ hasPass = true; } }); if(!this.blankIndex().length){ isOver && alert('游戏结束!'); }; } } } </script> <style> @import url(http://fonts.useso.com/css?family=Inknut+Antiqua); @import url(./main.css); </style>
index.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="telephone=no,email=no" name="format-detection"> <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>2048 Game</title> <style> html,body{ width:100%; } body{ display:flex; justify-content: center; align-items: center; overflow:hidden; } </style> </head> <body> <app></app> <script src="bundle.js"></script> </body> </html>
main.js
import Vue from 'vue' import App from './app.vue' new Vue({ el: 'body', components:{App} });
webpack配置
const webpack = require('webpack'); module.exports = { entry: { app:["./app/main.js",'webpack-hot-middleware/client','webpack/hot/dev-server'] }, output: { path: __dirname + "/public",//打包后的文件存放的地方 filename: "bundle.js",//打包后输出文件的文件名 publicPath:'http://localhost:8080/' }, module: { loaders: [ {test: /\.css$/, loader: 'style!css'}, {test: /\.vue$/, loader: 'vue'}, {test: /\.js$/,exclude:/node_modules|vue\/dist|vue-router\/|vue-loader\/|vue-hot-reload-api\// ,loader: 'babel'} ] }, vue:{ loaders:{ js:'babel' } }, babel: { presets: ['es2015','stage-0'], plugins: ['transform-runtime'] }, plugins:[ new webpack.HotModuleReplacementPlugin() ], devServer: { contentBase: "./public",//本地服务器所加载的页面所在的目录 colors: true,//终端中输出结果为彩色 hot: true, inline: true//实时刷新 }, resolve: { extensions: ['', '.js', '.vue'] } }
css就不贴了,Github上托管了:https://github.com/Elity/2048...
好久没写这么长的文章了,累死。花了整整俩小时!!!