/
Sudoku.coffee
142 lines (113 loc) · 2.21 KB
/
Sudoku.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
T = require "node-term-ui"
S = require "sudoku"
x = 0
y = 0
grid = {}
puzzle = {}
pieces = S.makepuzzle()
for px in [0..8]
puzzle[px] = {}
for py in [0..8]
piece = pieces[S.posfor px, py]
puzzle[px][py] = if piece isnt null then piece + 1 else false
draw = ->
grid[x][y].focus()
check = ->
cellError = []
addError = (cell) ->
cell.textColor T.C.r
cellError.push cell
checkNum = (nums, x, y) ->
cell = grid[x][y]
if cell instanceof Answer
if cur = nums[cell.val()]
addError cur
nums[cell.val()] = cell
else if nums[cell.val()]
addError cell
else
if cell not in cellError
cell.textColor T.C.g
nums[cell.val()] = cell
#check each square
for colOffset in [0..2]
for rowOffset in [0..2]
nums = {}
for row in [0..2]
for col in [0..2]
checkNum nums, col + (colOffset * 3), row + (rowOffset * 3)
#check each col and row
for row in [0..8]
cnums = {}
rnums = {}
for col in [0..8]
checkNum cnums, col, row
checkNum rnums, row, col
class SudokuInput extends T.TextInput
constructor: (opts = {}) ->
opts.borders = false
super opts
@x = opts.x
@y = opts.y
@maxLength = 1
charValidation: (val) ->
/[1-9]/.test val
onKey_up: ->
if y > 0 then y--
draw()
onKey_down: ->
if y < 8 then y++
draw()
onKey_left: ->
if x > 0 then x--
draw()
onKey_right: ->
if x < 8 then x++
draw()
onKey_space: ->
@content = []
check()
@drawContent()
@drawCursor()
focus: ->
x = @x
y = @y
super()
key: ->
"#{@x}x#{@y}"
val: ->
parseInt super()
scroll: ->
class Answer extends SudokuInput
constructor: (opts) ->
super opts
@_val = opts.val
drawContent: ->
T.saveFg()
.fg(T.C.m)
.pos(@bounds.x + 1, @bounds.y + 1)
.out("#{@_val}")
.restoreFg()
this
val: ->
parseInt @_val
do (x, y) ->
for x in [0..8]
grid[x] = {}
for y in [0..8]
if puzzle[x][y]
grid[x][y] = new Answer {x, y, val: puzzle[x][y]}
else
grid[x][y] = new SudokuInput {x, y}
grid[x][y].on "change", check
styler = (r) -> if r%3 is 0 then 3 else 1
g = new T.Grid
cols: 9
rows: 9
cellWidth: 1
cellHeight: 1
rowStyle: styler
colStyle: styler
content: grid
T.clear()
g.draw()