-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.go
106 lines (87 loc) · 2.4 KB
/
game.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
package gogameoflife
import (
"time"
"os"
"os/exec"
"fmt"
"github.com/exrook/drawille-go"
"io"
)
// Min delay
// Very naive approach.
// Current desc state used as initial state for each iteration
// Every iteration we print current desk, then create new array (slice) for storing the next state
// Then we set new state as current state
type Game struct {
CurrentGenerationDesk Desk
NextGenerationDesk Desk
InitialDataProvider DataSourceProvider
Canvas drawille.Canvas
}
func NewGame(provider DataSourceProvider) *Game {
return &Game{
InitialDataProvider: provider,
Canvas: drawille.NewCanvas(),
}
}
// Delay should be provided in milliseconds
func (r *Game) Start(delay int) error {
fileContent, err := r.InitialDataProvider.GetData()
if err != nil {
return err
}
r.CurrentGenerationDesk, err = ParseInputData(fileContent, r.InitialDataProvider.GetLiveSymbol())
if err != nil {
return err
}
for {
r.ClearScreen()
r.Render(os.Stdout)
r.NextGeneration()
r.Refresh()
r.Sleep(delay)
}
return nil
}
// Creates new generation of population
// Naive and non-optimal solution. Every iteration new desk created. Hopefully GC will fine with it.
// If necessary, may be optimized to reuse 2 predefined arrays
// with switch() and clear() every iteration
func (r *Game) NextGeneration() Desk {
r.NextGenerationDesk = CreateDefaultDeadDesk(len(r.CurrentGenerationDesk))
for i := range r.CurrentGenerationDesk {
for j := range r.CurrentGenerationDesk {
r.NextGenerationDesk[i][j] = r.CurrentGenerationDesk.GetNewCellState(i, j)
}
}
return r.NextGenerationDesk
}
// Set printed new generation as current generation
// NextGeneration() method will use it as initial data on next iteration
func (r *Game) Refresh() {
r.CurrentGenerationDesk = r.NextGenerationDesk
}
// Clear the terminal (linux only)
func (r *Game) ClearScreen() {
c := exec.Command("clear")
c.Stdout = os.Stdout
c.Run()
}
// Renders current desk to console
// Some package used to emulate pixels in terminal
func (r *Game) Render(out io.Writer) {
r.Canvas.Clear()
for i, x := range r.CurrentGenerationDesk {
for j, v := range x {
if v {
r.Canvas.Set(j, i)
}
}
}
fmt.Fprintf(out, fmt.Sprintf("%s", r.Canvas))
}
// Used for delay between creating new generation
// Used for controlling "screen refresh rate"
func (r Game) Sleep(delay int) {
time.Sleep(time.Millisecond * time.Duration(delay))
}