簡単な2048ゲーム


2048 var arr; function update() { var n, str = ""; while (arr[n=Math.random()*16>>0]); arr[n] = Math.random()*2+1<<1; for (var i = 0; i < arr.length; i++) str += "<div class='nu"+arr[i]+"'>"+arr[i]+"</div>"; document.getElementById("box").innerHTML = str; } function move(ts,tp,tr) { var moveflag = false; for (var k = 0; k < 4; k++) { var to = ts + k*tp; for (var j = 1; j < 4; j++) { var i = ts + k*tp + j*tr; if (!arr[i]) continue; if (!arr[to]) { arr[to] = arr[i]; } else if (arr[i]==arr[to]) { arr[to] <<= 1; to += tr; } else { to += tr; if (to==i) continue; arr[to] = arr[i]; } delete arr[i]; moveflag = true; } } if (moveflag) { update(); isover(); } } function isover() { for (var i = 0; i < 16; i++) { var v = arr[i]; if (!v || i%4!=0 && v==arr[i-1] || i%4!=3 && v==arr[i+1] || i>3 && v==arr[i-4] || i<12 && v==arr[i+4]) return; } setTimeout('alert("game over");start();', 200); } document.onkeydown = function (e) { switch ((e||event).keyCode) { case 37: move(0,4,1); break; // case 39: move(3,4,-1); break; // case 38: move(0,1,4); break; // case 40: move(12,1,-4); break; // } } function start() { arr = new Array(16); update(); update(); } start();