亲宝软件园·资讯

展开

javascript sudoku 数独智力游戏生成代码

人气:0
复制代码 代码如下:

<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))
/https://img.qb5200.com/download-x/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>

加载全部内容

相关教程
猜你喜欢
用户评论