-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathfigure.go
80 lines (70 loc) · 1.78 KB
/
figure.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
package figure
import (
"io"
"log"
"reflect"
"strings"
)
const ascii_offset = 32
const first_ascii = ' '
const last_ascii = '~'
type figure struct {
phrase string
font
strict bool
color string
}
func NewFigure(phrase, fontName string, strict bool) figure {
font := newFont(fontName)
if font.reverse {
phrase = reverse(phrase)
}
return figure{phrase: phrase, font: font, strict: strict}
}
func NewColorFigure(phrase, fontName string, color string, strict bool) figure {
color = strings.ToLower(color)
if _, found := colors[color]; !found {
log.Fatalf("invalid color. must be one of: %s", reflect.ValueOf(colors).MapKeys())
}
fig := NewFigure(phrase, fontName, strict)
fig.color = color
return fig
}
func NewFigureWithFont(phrase string, reader io.Reader, strict bool) figure {
font := newFontFromReader(reader)
if font.reverse {
phrase = reverse(phrase)
}
return figure{phrase: phrase, font: font, strict: strict}
}
func (figure figure) Slicify() (rows []string) {
for r := 0; r < figure.font.height; r++ {
printRow := ""
for _, char := range figure.phrase {
if char < first_ascii || char > last_ascii {
if figure.strict {
log.Fatal("invalid input.")
} else {
char = '?'
}
}
fontIndex := char - ascii_offset
charRowText := scrub(figure.font.letters[fontIndex][r], figure.font.hardblank)
printRow += charRowText
}
if r < figure.font.baseline || len(strings.TrimSpace(printRow)) > 0 {
rows = append(rows, strings.TrimRight(printRow, " "))
}
}
return rows
}
func scrub(text string, char byte) string {
return strings.Replace(text, string(char), " ", -1)
}
func reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}