DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript sudoku 數獨智力游戲生成代碼
javascript sudoku 數獨智力游戲生成代碼
編輯:關於JavaScript     
復制代碼 代碼如下:
<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>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved