-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
board.go
145 lines (122 loc) · 2.32 KB
/
board.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"fmt"
"math/rand"
)
type Board struct {
height int
width int
grid [][]Cell
time int
// cells []*Cell
}
func NewBoard(height, width int) *Board {
board := Board{
height: height,
width: width,
}
board.Init()
return &board
}
func Cells(width, height int) [][]Cell {
cells := make([][]Cell, height)
for i := 0; i < height; i++ {
cells[i] = make([]Cell, width)
}
return cells
}
func (b *Board) Init() {
b.grid = Cells(b.width, b.height)
b.link()
}
func (b *Board) link() {
around := [8][2]int{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}
// link
for i := 0; i < b.height; i++ {
for j := 0; j < b.width; j++ {
b.grid[i][j].UnLink()
aroundCells := []*Cell{}
for _, a := range around {
y := i + a[0]
x := j + a[1]
if x < 0 || y < 0 || x >= b.width || y >= b.height {
continue
}
aroundCells = append(aroundCells, &b.grid[y][x])
}
b.grid[i][j].Link(aroundCells)
}
}
}
func (b *Board) Resize(width, height int) {
newGrid := Cells(width, height)
var minHeight int
if b.height > height {
minHeight = height
} else {
minHeight = b.height
}
for i := 0; i < minHeight; i++ {
copy(newGrid[i], b.grid[i])
}
b.grid = newGrid
b.width = width
b.height = height
b.link()
}
func (b *Board) State() [][]Cell {
return b.grid
}
func (b *Board) Random() {
grid := make([][]bool, b.height)
for i := 0; i < b.height; i++ {
grid[i] = make([]bool, b.width)
}
for i := 0; i < b.height; i++ {
for j := 0; j < b.width; j++ {
grid[i][j] = rand.Int()%2 == 0
}
}
b.Set(0, 0, grid)
b.time = 0
}
func (b *Board) Next() {
for i := 0; i < b.height; i++ {
for j := 0; j < b.width; j++ {
b.grid[i][j].CalcNextState()
}
}
for i := 0; i < b.height; i++ {
for j := 0; j < b.width; j++ {
b.grid[i][j].Flush()
}
}
b.time++
}
func (b *Board) Time() int {
return b.time
}
func (b *Board) Print() {
for i := 0; i < b.height; i++ {
for j := 0; j < b.width; j++ {
if b.grid[i][j].state {
fmt.Printf("O")
} else {
fmt.Printf("X")
}
}
fmt.Printf("\n")
}
}
func (b *Board) Set(x, y int, bgrid [][]bool) {
for i, row := range bgrid {
for j, state := range row {
if y+i < b.height && x+j < b.width {
b.grid[y+i][x+j].Set(state)
}
}
}
}
func (b *Board) Get(x, y int) *Cell {
return &b.grid[y][x]
}