2014-12-09 12:30:29 +01:00
|
|
|
class Nikoli.Sudoku extends Nikoli.Game
|
|
|
|
constructor: (@board, @name = 'sudoku') ->
|
|
|
|
super @board, @name
|
2014-12-08 12:45:33 +01:00
|
|
|
|
|
|
|
errors: ->
|
|
|
|
solution = @toArray()
|
|
|
|
errors = []
|
|
|
|
|
2014-12-10 12:58:02 +01:00
|
|
|
for i in [0...solution.length]
|
2014-12-08 12:45:33 +01:00
|
|
|
row = solution[i]
|
2014-12-10 12:58:02 +01:00
|
|
|
for j in [0...row.length]
|
2014-12-12 12:18:22 +01:00
|
|
|
cell = new Nikoli.SudokuCell(i, j, solution)
|
2014-12-08 12:45:33 +01:00
|
|
|
|
2014-12-10 12:58:02 +01:00
|
|
|
if cell.value == 0
|
|
|
|
errors.push {row: i, column: j, message: 'The cell has no value.'}
|
|
|
|
else if cell.rowDuplicates() || cell.columnDuplicates() || cell.squareDuplicates({x: Math.floor(i/3)*3, y: Math.floor(j/3)*3}, 3)
|
|
|
|
errors.push {row: i, column: j, message: 'The number appears more than once in the row, column or square.'}
|
2014-12-08 12:45:33 +01:00
|
|
|
|
|
|
|
errors
|
|
|
|
|
|
|
|
generate: (game, solution = false) ->
|
2014-12-12 12:18:22 +01:00
|
|
|
super game, solution, Nikoli.SudokuCell
|
2014-12-08 12:45:33 +01:00
|
|
|
|
|
|
|
toggle: (cell) ->
|
|
|
|
if cell.classList.contains 'black'
|
|
|
|
cell.classList.remove 'black'
|
|
|
|
cell.classList.add 'white'
|
|
|
|
else if cell.classList.contains 'white'
|
|
|
|
cell.classList.remove 'white'
|
|
|
|
else
|
|
|
|
cell.classList.add 'black'
|
|
|
|
|
2014-12-10 12:58:02 +01:00
|
|
|
toArray: (solution = false) ->
|
2014-12-08 12:45:33 +01:00
|
|
|
[].map.call @grid.querySelectorAll('.grid-row'), (row) ->
|
|
|
|
[].map.call row.querySelectorAll('.grid-cell'), (cell) ->
|
|
|
|
if cell.classList.contains('empty')
|
2014-12-10 12:58:02 +01:00
|
|
|
value = parseInt(cell.querySelector('input').value)
|
|
|
|
if isNaN(value)
|
|
|
|
0
|
|
|
|
else
|
|
|
|
if solution then -value else value
|
2014-12-08 12:45:33 +01:00
|
|
|
else
|
|
|
|
parseInt(cell.innerHTML)
|
2014-12-12 12:18:22 +01:00
|
|
|
|
|
|
|
class Nikoli.SudokuCell extends Nikoli.Cell
|
|
|
|
create: (value) ->
|
|
|
|
cell = super
|
|
|
|
if value <= 0
|
|
|
|
cell.classList.add 'empty'
|
|
|
|
cell.innerHTML = "<input type=\"text\" #{if value < 0 then "value=\"#{Math.abs(value)}\"" else ''} />"
|
|
|
|
else
|
|
|
|
cell.classList.add 'white'
|
|
|
|
cell.innerHTML = value
|
|
|
|
|
|
|
|
cell
|