forked from davidegp/5x5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictionary.coffee
More file actions
55 lines (48 loc) · 1.69 KB
/
Dictionary.coffee
File metadata and controls
55 lines (48 loc) · 1.69 KB
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
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 [0...@grid.size]
for y in [0...@grid.size]
@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) ->
if str in @usedWords
false
else
str in @wordList
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