首頁 >web前端 >js教程 >JS写的数字拼图小游戏代码[学习参考]_javascript技巧

JS写的数字拼图小游戏代码[学习参考]_javascript技巧

WBOY
WBOY原創
2016-05-16 18:59:251417瀏覽
复制代码 代码如下:





拼图


<script> <BR>var currPos = 9; <BR>function move(event){ <BR>switch(event.keyCode){ <BR>case 37 : <BR>// 左键 <BR>if (currPos % 3 != 0){ <BR>var currTd = document.getElementById("numTd_" + currPos); <BR>var nextTd = document.getElementById("numTd_" + (currPos + 1)); <BR>var temp = nextTd.innerHTML; <BR>nextTd.innerHTML = " "; <BR>currTd.innerHTML = temp; <BR>currPos ++ ; <BR>} <BR>break; <BR>case 38 : <BR>// 上键 <BR>if (currPos < 7){ <BR>var currTd = document.getElementById("numTd_" + currPos); <BR>var nextTd = document.getElementById("numTd_" + (currPos + 3)); <BR>var temp = nextTd.innerHTML; <BR>nextTd.innerHTML = " "; <BR>currTd.innerHTML = temp; <BR>currPos += 3; <BR>} <BR>break; <BR>case 39 : <BR>// 右键 <BR>if (currPos % 3 != 1){ <BR>var currTd = document.getElementById("numTd_" + currPos); <BR>var nextTd = document.getElementById("numTd_" + (currPos - 1)); <BR>var temp = nextTd.innerHTML; <BR>nextTd.innerHTML = " "; <BR>currTd.innerHTML = temp; <BR>currPos -- ; <BR>} <BR>break; <BR>case 40 : <BR>// 下键 <BR>if (currPos > 3){ <BR>var currTd = document.getElementById("numTd_" + currPos); <BR>var nextTd = document.getElementById("numTd_" + (currPos - 3)); <BR>var temp = nextTd.innerHTML; <BR>nextTd.innerHTML = " "; <BR>currTd.innerHTML = temp; <BR>currPos -= 3; <BR>} <BR>break; <BR>default : <BR>break; <BR>} <br><br>if (isWin()){ <BR>alert("恭喜你,过关了!"); <BR>initNums(); <BR>} <br><br>} <br><br>function isWin(){ <BR>for (i = 1; i < 9; i ++ ){ <BR>var numTd = document.getElementById("numTd_" + i); <BR>var numDiv = numTd.getElementsByTagName("div"); <BR>if (i != numTd.innerText){ <BR>return false; <BR>} <BR>} <BR>return true; <br><br>} <br><br>function initNums(){ <BR>var numArr = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9); <BR>var newnewNumArr = new Array(); <br><br>do{ <BR>var tempStr = ""; <BR>for(i in numArr){ <BR>var flag = true; <BR>do{ <BR>tempNum = numArr[parseInt(Math.random() * 100) % 9]; <BR>if (tempStr.search(tempNum) == -1){ <BR>newNumArr[i] = tempNum; <BR>tempStr += tempNum; <BR>flag = false; <BR>} <BR>} <BR>while(flag); <BR>} <BR>}while(inverNum(newNumArr) % 2 == 0); <br><br><BR>var len = newNumArr.length; <BR>for(j = 0; j < len; j ++ ){ <BR>if (newNumArr[j] != 9){ <BR>document.getElementById("numTd_" + (j + 1)).innerHTML = "<div id='numDiv_"+newNumArr[j]+"' class='numDiv'>" + newNumArr[j] + "</script>
";
}
else{
document.getElementById("numTd_" + (j + 1)).innerHTML = " ";
currPos = j + 1;
}
}

// document.getElementById("output").innerText = newNumArr;
}

function inverNum(numArr){
var len = numArr.length;
var count = 0;
for(i = 0; i for(j = i + 1; j if (numArr[j] > numArr[i]){
count ++ ;
}
}
}
// alert("逆序数: "+count);
return count;
}







































陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn