-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
79 lines (65 loc) · 1.41 KB
/
main.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
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"os"
"strconv"
"time"
)
const (
clearEscapeCode = "\033[H\033[2J"
)
func main() {
filename, speed, err := parseFlags()
if err != nil {
fmt.Println(err.Error())
return
}
input, err := readLinesOfFile(filename)
if err != nil {
fmt.Println(err.Error())
return
}
cells, err := newCells(input)
if err != nil {
fmt.Println(err.Error())
return
}
for {
os.Stdout.WriteString(clearEscapeCode)
cells = cells.generate()
cells.print(os.Stdout)
time.Sleep(time.Second / time.Duration(speed))
}
}
func parseFlags() (string, int, error) {
var filename string
var speedStr string
flag.StringVar(&filename, "i", "", "input filename")
flag.StringVar(&speedStr, "s", "2", "playback speed in fps (1~30)")
flag.Parse()
if len(filename) == 0 {
return "", 0, errors.New("please provide an input file path")
}
speed, err := strconv.Atoi(speedStr)
if err != nil || speed < 1 || speed > 30 {
return "", 0, errors.New("please provide a valid playback speed")
}
return filename, speed, nil
}
func readLinesOfFile(filename string) ([]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("opening input file failed, %s", err.Error())
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
lines = append(lines, line)
}
return lines, nil
}