-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserialize.go
127 lines (111 loc) · 2.54 KB
/
serialize.go
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
package gridspech
import (
"strings"
)
func stringToTileData(s string) TileData {
var data TileData
if strings.Contains(s, "_") {
data.Type = TypeHole
} else {
data.Color = TileColor(s[0] - '0')
data.Sticky = strings.Contains(s, "/")
data.Type = TypeBlank
switch {
case strings.Contains(s, "k"):
data.Type = TypeCrown
case strings.Contains(s, "e"):
data.Type = TypeGoal
case strings.Contains(s, "m1"):
data.Type = TypeDot1
case strings.Contains(s, "m2"):
data.Type = TypeDot2
case strings.Contains(s, "m3"):
data.Type = TypeDot3
case strings.Contains(s, "j1"):
data.Type = TypeJoin1
case strings.Contains(s, "j2"):
data.Type = TypeJoin2
}
if strings.Contains(s, "^") {
data.ArrowNorth = true
}
if strings.Contains(s, ">") {
data.ArrowEast = true
}
if strings.Contains(s, "v") {
data.ArrowSouth = true
}
if strings.Contains(s, "<") {
data.ArrowWest = true
}
}
return data
}
func emptyLine(s string) bool {
return !strings.ContainsAny(s, "_0123456789")
}
func stripEmptyLines(lines []string) []string {
if emptyLine(lines[0]) {
lines = lines[1:]
}
if emptyLine(lines[len(lines)-1]) {
lines = lines[:len(lines)-1]
}
return lines
}
// MakeGridFromString takes a string and converts it into a Grid.
func MakeGridFromString(str string, maxColors int) Grid {
var grid Grid
lines := strings.Split(str, "\n")
lines = stripEmptyLines(lines)
height := len(lines)
width := len(strings.Fields(lines[0]))
grid.Tiles = make([][]Tile, width)
for x := range grid.Tiles {
grid.Tiles[x] = make([]Tile, height)
}
grid.MaxColors = maxColors
for y := 0; y < height; y++ {
row := strings.Fields(lines[height-y-1])
for x := 0; x < width; x++ {
cur := row[x]
data := stringToTileData(cur)
grid.Tiles[x][y] = Tile{
Data: data,
Coord: TileCoord{X: x, Y: y},
}
}
}
return grid
}
func (g Grid) String() string {
var longest int
tileStrs := make([][]string, g.Width())
for i := range tileStrs {
tileStrs[i] = make([]string, g.Height())
}
for y := 0; y < g.Height(); y++ {
for x := 0; x < g.Width(); x++ {
str := g.TileAt(x, y).Data.String()
tileStrs[x][y] = str
if len(str) > longest {
longest = len(str)
}
}
}
var sb strings.Builder
for y := g.Height() - 1; y >= 0; y-- {
if y < g.Height()-1 {
sb.WriteByte('\n')
}
for x := 0; x < g.Width(); x++ {
tileStr := tileStrs[x][y]
padded := tileStr + strings.Repeat(" ", longest-len(tileStr))
if x > 0 {
sb.WriteString(" ")
}
sb.WriteString(padded)
}
}
return sb.String()
}