<html>
<head>
<title> My Puzzle </title>
<style>
.tile {
text-align:center;
width:60px;
height:60px;
font-size:32px;
background-color:"white";
border:1px solid black;
box-shadow:black 2px 2px;
}
</style>
<script language="JavaScript">
// 2016.10.10
var tile = [];
var isPlay = false;
var emptyTile = 0;
function init() {
var table = document.getElementById("puzzle");
window.onkeydown = onKeyDown;
window.onkeyup = onKeyUp;
for (var i = 0; i < 5; i++) {
var tr = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var td = document.createElement("td");
td.className="tile";
var idx = i*5 + j;
td.value = idx;
td.index = idx;
td.textContent = (idx === 0) ? "" : idx;
td.onclick = onClick;
tile.push(td);
tr.appendChild(td);
}
table.appendChild(tr);
}
alert("Click to Start!");
for (var i = 0; i < 1000; i++) {
onClick( {srcElement: {index : Math.floor(Math.random() * 25)}})
}
isPlay = true;
}
function onKeyDown(e) {
if (!isPlay) return;
var key = e.keyCode;
var emTile = emptyTile;
console.log("Key : " + key);
console.log("Empty Tile : " + emptyTile);
var x = emTile % 5;
var y = emTile / 5;
switch(key) {
case 37: // LEFT
if (x+1 < 5) {
moveTile(emptyTile+1);
}
break;
case 38: // UP
if (y+1 < 5) {
moveTile(emptyTile+5);
}
break;
case 39: // RIGHT
if (x-1 >= 0) {
moveTile(emptyTile-1);
}
break;
case 40: // DOWN
if (y-1 >= 0) {
moveTile(emptyTile-5);
}
break;
default:
console.log("Error : Never come to here!");
break;
}
}
function onKeyUp(e) {
}
function onClick(e) {
var clkTile = e.srcElement.index;
moveTile(clkTile);
}
function moveTile(clkTile) {
var x = clkTile % 5;
var y = clkTile / 5;
if (x-1 >= 0 && tile[clkTile-1].value == 0) {
swap(clkTile-1, clkTile);
emptyTile = clkTile;
}
else if (x+1 < 5 && tile[clkTile+1].value == 0) {
swap(clkTile+1, clkTile);
emptyTile = clkTile;
}
else if (y-1 >=0 && tile[clkTile-5].value == 0 ) {
swap(clkTile-5, clkTile);
emptyTile = clkTile;
}
else if (y+1 < 5 && tile[clkTile+5].value == 0) {
swap(clkTile+5, clkTile);
emptyTile = clkTile;
}
}
function swap(i, j) {
var tmpValue = tile[i].value;
var tmpContent = tile[i].textContent;
tile[i].value = tile[j].value;
tile[i].textContent = tile[j].textContent;
tile[j].value = tmpValue;
tile[j].textContent = tmpContent;
if (isFinish()) {
alert("Success");
}
}
function isFinish() {
for (var i = 0; i < 5; i++) {
for (var j = 0; j < 5; j++) {
var idx = i*5 + j;
if (idx == 24) {
return true;
}
else if (tile[idx].value != (idx+1)) {
return false;
}
}
}
return true;
}
</script>
</head>
<body onload="init()">
<table id="puzzle" align="center">
</table>
</body>
</html>
'Coding > JavsScript 삽질기' 카테고리의 다른 글
Clock (0) | 2016.10.25 |
---|---|
Timer (0) | 2016.09.29 |
Samll lisp by Javascript (0) | 2016.09.12 |