javascript sudoku 数独智力游戏生成代码
代码如下:
<p><input value="Get New SuDoKu" type="button" onclick="onLoadTable()" id="refreshButton" /></p> <table border="1" style="border-color: Red;" id="mainTable"> <tbody> </tbody> </table> <script type="text/javascript" language="javascript">// <![CDATA[ var sudokuArray = [[],[],[],[],[],[],[],[],[],[]]; function onLoadTable() { do { sudokuArray = getNewArray(); sudokuArray = getSudokuArray(sudokuArray); } while(!checkArray(sudokuArray)) //document.getElementById("result").innerHTML=checkArray(sudokuArray); var table = document.getElementById("mainTable"); table.removeChild(table.firstChild); for(var i=0;i<9;i++) { table.insertRow(i); for(var j=0;j<9;j++) { table.rows[i].insertCell(j); table.rows[i].cells[j].innerHTML = sudokuArray[i][j];//Math.round(Math.random()*8+1); setStyle(i,j,table.rows[i].cells[j]); } } } function getSudokuArray(filledArray) { var failed = false; for(var i=0;i<9;i++) { for(var j=0;j<9;j++) { var tempArray = getAvaildableArray(i, j, filledArray); if(tempArray.length > 0) { filledArray[i][j] = tempArray[Math.round(Math.random()*(tempArray.length-1))]; } else { //window.location.reload(); } } } return filledArray; } function checkArray(array) { for(var i=0;i<9;i++) { for(var j=0;j<9;j++) { if(array[i][j] == undefined) { return false; } } } return true; } function getAvaildableArray(rowIndex, cellIndex, array) { var availdableArray = [1,2,3,4,5,6,7,8,9]; for(var n=0;n<9;n++) { if(!isNaN(array[rowIndex][n]) && array[rowIndex][n] != undefined) { availdableArray[array[rowIndex][n]-1] = NaN; } if(!isNaN(array[n][cellIndex]) && array[n][cellIndex] != undefined) { availdableArray[array[n][cellIndex]-1] = NaN; } } var rowStartIndex = Math.floor(rowIndex/3); var cellStartIndex = Math.floor(cellIndex/3); for(var x=rowStartIndex*3;x<rowStartIndex+3;x++) { for(var y=cellStartIndex*3;y<cellStartIndex+3;y++) { if(!isNaN(array[x][y]) || array[x][y] != undefined) { availdableArray[array[x][y]-1] = NaN; } } } var returnArray = []; for(var m=0;m<9;m++) { if(!isNaN(availdableArray[m])) { returnArray.push(availdableArray[m]); } } return returnArray; } function getNewArray() { return [[],[],[],[],[],[],[],[],[],[]]; } function setStyle(rowIndex,cellIndex,cell) { cell.height="20"; cell.width="20"; if(cellIndex%3==2) { cell.style.borderRightColor="red"; } if(cellIndex%3==0) { cell.style.borderLeftColor="red"; } if(rowIndex%3==2) { cell.style.borderBottomColor="red"; } if(rowIndex%3==0) { cell.style.borderTopColor="red"; } } // ]]></script>
相关推荐
zrtlin 2020-11-09
xuebingnan 2020-11-05
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
softwear 2020-08-21
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25
Aveiox 2020-06-23
dragonzht 2020-06-17