-
PHP Sudoku
Hi all,
I was originally going to post this in the Games forum, but this is more of a PHP question, rather than a Flash Games question, therefore I have put it here.
If this is the incorrect forum, please could a mod move it (sorry!)
I have been working on creating a script to randomly generate a full sudoku grid of numbers. This would be sent to flash, with a few numbers hidden, giving the user a unique experience each time they played the game.
My first step, is to create the sudoku grid using PHP, and I've tried various methods, but alas I cant seems to get to a full solution.
Towards the end of the script, it always seems to fail to add between 2-6 numbers based on the fact that the row/column already has the number to add.
On script execution, a random number is chosen, and then checked to ensure that it there is no number that is the same within the same row,column and grid space (there are 9 'grid spaces' within the full sudoku grid)
Ive added my code below. if anyone is willing to suggest any ways that I would be able to get this to work correctly, I would be greatly appreaciative.
Thanks
jagopth
Running the code here =>
http://www.icepets.com/test/sud.php
PHP Code:
<?php
$attempt = 0; while($attempt<3){ $attempt++; $playnum = 0; $rownum = 0; $colnum = 0; $allnums = array(); print '<br /><br /><table style="margin:auto; width:400px;">'; while($rownum<9){ $rownum++; $colnum=0; print '<tr>'; while($colnum<9){ $colnum++; $currtry = array(); print '<td>'; while(count($currtry)<9){ $thisnum = rand(1,9); if(!in_array($thisnum,$currtry)){ //Check Vertical $rowloop = 1; $allowNumber = "yes"; while($rowloop<=9){ $rowCheck = $allnums[$rownum][$rowloop]; if($rowCheck==$thisnum){ $allowNumber = "no"; } $rowloop++; } //Check Horizontal $colloop = 1; while($colloop<=9){ $colCheck = $allnums[$colloop][$colnum]; if($colCheck==$thisnum){ $allowNumber = "no"; } $colloop++; } //Check Grid if($rownum<=3){ $baserow = 1; }else if($rownum<=6){ $baserow = 4; }else{ $baserow = 7; } if($colnum<=3){ $basecol = 1; }else if($colnum<=6){ $basecol = 4; }else{ $basecol = 7; } $full9 = 0; while($full9<9){ $full9++; if($full9==4 || $full9==7){ $baserow++; $basecol-=3; } $grid_num = $allnums[$baserow][$basecol]; if($grid_num==$thisnum){ $allowNumber = "no"; $full9 = 10; } $basecol++; } if($allowNumber=="no"){ array_push($currtry,$thisnum); }else{ $allnums[$rownum][$colnum] = $thisnum; array_push($currtry,1,2,3,4,5,6,7,8,9); print $thisnum; $playnum++; } } } print '</td>'; } print '</tr>'; } print '</table>'; if($playnum==81){ break; print "<br /><br />FULL GRID!"; } } ?>
Last edited by jagopth; 07-26-2010 at 08:39 AM.
Reason: corrected some typos
howdy pardner!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|