2048是几年之前之前挺火的一个小游戏,相比于上一个十滴水小游戏,实现要简单很多,网上也有很多思路,本文是参考妙味课堂的实现。
首先,写好界面,效果如下:
document.onkeydown = function (e) {
switch (e.keyCode){
case 37:
// console.log('left');
run([0,1,2,3]);
run([4,5,6,7]);
run([8,9,10,11]);
run([12,13,14,15]);
break;
case 38:
// console.log('up');
run([0,4,8,12]);
run([1,5,9,13]);
run([2,6,10,14]);
run([3,7,11,15]);
break;
case 39:
// console.log('right');
run([0,1,2,3].reverse());
run([4,5,6,7].reverse());
run([8,9,10,11].reverse());
run([12,13,14,15].reverse());
break;
case 40:
// console.log('down');
run([0,4,8,12].reverse());
run([1,5,9,13].reverse());
run([2,6,10,14].reverse());
run([3,7,11,15].reverse());
break;
}
};
[2,2,2,2] => [4,4,0,0]
[2,0,2,2] => [4,2,0,0]
[2,4,2,2] => [2,4,4,0]
[2,4,4,2] => [2,8,2,0]
[0,2,0,2] => [4,0,0,0]
function _2048(arr){
let newArr = [];
for(var i=0; i
function run(arr) {
let newValue = _2048([
Number(imgs[arr[0]].getAttribute('value')),
Number(imgs[arr[1]].getAttribute('value')),
Number(imgs[arr[2]].getAttribute('value')),
Number(imgs[arr[3]].getAttribute('value'))
])
for(var i=0; i
function create() {
var num = 0;
var random = Math.floor(Math.random()*16);
if(imgs[random].getAttribute('value') == 0){
imgs[random].setAttribute('value',2);
imgs[random].src = `img/cube_2.png`;
}else {
for(var i=0; i