-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcrossword.go
More file actions
113 lines (96 loc) · 2.08 KB
/
crossword.go
File metadata and controls
113 lines (96 loc) · 2.08 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
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
package crossword
import (
"fmt"
"slices"
"strconv"
"strings"
)
type Cell struct {
Char rune
CharIdx int
}
func (c Cell) String() string {
return string(c.Char)
}
func (c Cell) Empty() bool {
return c.Char == rune(0)
}
func NewGrid(size int) Grid {
grid := make(Grid, size)
for y := range size {
grid[y] = make([]Cell, size)
}
return grid
}
type Grid [][]Cell
type Placement struct {
ID int
Word Word
X int
Y int
Vertical bool
// Solved reveals the characters of the word when it's rendered.
Solved bool
}
func (p Placement) ClueID() string {
label := fmt.Sprintf("%d", p.ID)
if p.Word.Label != nil {
label = *p.Word.Label
}
if p.Vertical {
return fmt.Sprintf("D%s", label)
}
return fmt.Sprintf("A%s", label)
}
type Word struct {
Word string
Clue string
Label *string
// The number of letters in the original words(s). Since they are concatinated, we need this
// to know the letter counts for multiple words.
LettersCounts []int
// CharacterHints allows subset of characters to be revealed (e.g. []int{0} would reveal
// the first char of a word by default)
CharacterHints []int
}
func (w Word) LetterCountStr() string {
if len(w.LettersCounts) == 0 {
return fmt.Sprintf("%d", len(w.Word))
}
parts := make([]string, len(w.LettersCounts))
for i, n := range w.LettersCounts {
parts[i] = strconv.Itoa(n)
}
return strings.Join(parts, ",")
}
type Crossword struct {
Grid Grid
Words []Placement
TotalScore int
}
func (cw *Crossword) Solve() {
for k := range cw.Words {
cw.Words[k].Solved = true
}
}
func (cw *Crossword) CellPlacements(cellX, cellY int) []Placement {
var placements []Placement
for _, pl := range cw.Words {
if pl.Vertical {
if pl.X == cellX && cellY >= pl.Y && cellY < pl.Y+len(pl.Word.Word) {
placements = append(placements, pl)
}
} else {
if pl.Y == cellY && cellX >= pl.X && cellX < pl.X+len(pl.Word.Word) {
placements = append(placements, pl)
}
}
}
slices.SortFunc(placements, func(a, b Placement) int {
if a.Vertical {
return 1
}
return -1
})
return placements
}