Game development with RUBY
July 21st, 2009We were fascinated when we developed a 9*9 sudoku puzzle game since everyone enjoy solving sudoku puzzles that comes in the daily newspaper. But then writing code for creating one is not going to be a smooth job. Initially, we started working out a 3*3 sudoku algorithm to generate an 2-dimensional array of 3 rows and 3 columns that has numbers 1,2 and 3.
Each cell is inserted with a random number from 1 to 3 that satisfies the condition that the numbers is not occured in the same row and the same column. A 3*3 solution matrix was successful with little logic. Next is to generate a 9*9 pack of numbers that forms a sudoku table. The former algorithm can be reengineered? There came the real puzzle. A 9*9 sudoku grid is divided into 9 - 3*3 boxes and the conditions for inserting the random values into the 9*9 2-dimensional array is increased by 1.
-
The values in each of the rows must be unique.
-
The values in each of the columns must be unique.
- The values in the each of the boxes must be unique as well.
Eventually the code was satisfied by 3 methods that check the above 3 conditions respectively and got the 9*9 array of sudoku solution matrix. The most wanted 3 methods are:
#Method to check the elements in a row are unique
def rowcheck(rand,row)
for i in 0…$array1.length
if($array1[row][i]==rand)
return false
else
next
end
end
return true
end
#Method to check the elements in a col are unique
def colcheck(rand,col)
for i in 0…8
if($arr1[i][col]==rand)
return false
else
next
end
end
end
#Method to check the elements in boxes are unique
def boxcheck(rand,row,col) #The condition has to be checked for each boxes
if(row<3 and col<3) #Box1
for i in 0..2
for j in 0..2
if($arr1[i][j]==rand)
return false
else
next
end
end
end
end
The random number that passes through all the 3 checking methods will have to be assigned into the array. Yippee! finally, the sudoku table was generated.
Then the left over task is the GUI part which is fulfilled by effective GUI toolkit, Ruby Tk. The puzzle ended with a sudoku grid that displays few values from the source array that is been generated by the code and allows the user to fill the rest of the cells (using event handling). Each cell in the grid holds a button and when the user clicks a button, it waits for the input from the keyboard. The number is assigned to the button once the user presses the right number that corresponds to the sudoku table.
-Ruby Team