forked from davidegp/5x5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDictionary.coffee
52 lines (45 loc) · 1.67 KB
/
Dictionary.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
class Dictionary
@MIN_WORD_LENGTH: 4
constructor: (@originalWordList, grid) ->
@setGrid grid if grid?
setGrid: (@grid) ->
@wordList = (word for word of @originalWordList when word.length <= @grid.size and word.length >= Dictionary.MIN_WORD_LENGTH)
@usedWords = []
for x in [[email protected]]
for y in [[email protected]]
@markUsed word for word in @wordsThroughTile x,y
markUsed: (str) ->
if str in @usedWords
false
else
@usedWords.push str
true
isWord: (str) ->
str in @wordList
isNewWord: (str) ->
str in @wordList and str not in @usedWords
wordsThroughTile: (x,y) ->
# numbers in JSON come back as strings so coerce into nums
[x, y] = [+x, +y]
grid = @grid
strings = []
for length in [Dictionary.MIN_WORD_LENGTH..grid.size]
range = parseInt(length) - 1
addTiles = (func) ->
strings.push (func(i) for i in [0..range]).join ''
for offset in [0...length]
# Vertical
if grid.inRange(x - offset, y) and grid.inRange(x - offset + range, y)
addTiles (i) -> grid.tiles[x - offset + i][y]
# Horizontal
if grid.inRange(x, y - offset) and grid.inRange(x, y - offset + range)
addTiles (i) -> grid.tiles[x][y - offset + i]
# Diagonal (upper-left to lower-right)
if grid.inRange(x - offset, y - offset) and grid.inRange(x - offset + range, y - offset + range)
addTiles (i) -> grid.tiles[x - offset + i][y - offset + i]
# Diagonal (lower-left to upper-right)
if grid.inRange(x + offset, y - offset) and grid.inRange(x + offset - range, y - offset + range)
addTiles (i) -> grid.tiles[x + offset - i][y - offset + i]
str for str in strings when @isWord str
root = exports ? window
root.Dictionary = Dictionary