-
Notifications
You must be signed in to change notification settings - Fork 1
/
game.go
88 lines (71 loc) · 1.55 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
package main
import (
"fmt"
"math/rand"
"time"
)
const rows int = 64
const cols int = 128
func main() {
// seed the random number generator
rand.Seed(time.Now().UTC().UnixNano())
// initialize world
var world = make([][]rune, rows)
for y := 0; y < rows; y++ {
world[y] = make([]rune, cols)
for x := 0; x < cols; x++ {
world[y][x] = getRandomValue()
}
}
// let the world life
for {
printWorld(world)
world = evolveWorld(world)
time.Sleep(time.Second / 4)
}
}
func getRandomValue() rune {
if rand.Intn(10) == 0 {
return 'X'
}
return ' '
}
func printWorld(myworld [][]rune) {
// clear screen
fmt.Print("\033[H\033[2J")
for y := range myworld {
fmt.Println(string(myworld[y]))
}
}
func evolveWorld(myworld [][]rune) [][]rune {
var newworld = make([][]rune, rows)
for y, row := range myworld {
newworld[y] = make([]rune, cols)
for x, current := range row {
var neighborCount = getNumOfNeighbors(myworld, x, y)
var newVal rune
if current == ' ' && neighborCount == 3 {
newVal = 'X'
} else if current == 'X' && (neighborCount < 2 || neighborCount > 3) {
newVal = ' '
} else {
newVal = current
}
newworld[y][x] = newVal
}
}
return newworld
}
func getNumOfNeighbors(myworld [][]rune, x int, y int) int {
var num int = 0
for i := -1; i <= 1; i++ {
for j := -1; j <= 1; j++ {
var currentX = x + i
var currentY = y + j
if currentX >= 0 && currentX < cols && currentY >= 0 && currentY < rows && (i != 0 || j != 0) && myworld[currentY][currentX] == 'X' {
num++
}
}
}
return num
}