-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameoflife.mcsketch
134 lines (113 loc) · 2.59 KB
/
gameoflife.mcsketch
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
input var x;
input var y;
input var z;
var width = 30;
var height = 30;
var iteration = 0;
~ cells are stored row-wise in a 1D-array
var board = array(width*height);
var paused = true;
fn indexToCoords(index) {
var x = index % width;
var y = index / width;
return [x, y];
}
fn coordsToIndex(x, y) {
return y * width + x;
}
fn nextGeneration() {
var boardCopy = array(length(board));
for(var i = 0; i < length(board); i = i + 1) {
boardCopy[i] = board[i];
i = i + 1;
}
for (var i = 0; i < width; i = i + 1) {
for (var j = 0; j < height; j = j + 1) {
var index = coordsToIndex(i, j);
var alive = board[index];
var aliveNeighbors = 0;
for (var dx = -1; dx < 2; dx = dx +1) {
for (var dy = -1; dy < 2; dy = dy + 1) {
if(dx!=0 || dy!=0) {
var nx = i + dx;
var ny = j + dy;
if(nx < 0) {
nx = width - 1;
}
if(nx >= width) {
nx = 0;
}
if(ny < 0) {
ny = height - 1;
}
if(ny >= height) {
ny = 0;
}
if(board[coordsToIndex(nx, ny)]) {
aliveNeighbors = aliveNeighbors + 1;
}
}
}
}
if(alive) {
boardCopy[index] = aliveNeighbors == 2 || aliveNeighbors == 3;
} else {
boardCopy[index] = aliveNeighbors == 3;
}
}
}
board = boardCopy;
}
fn buildBoard() {
for (var i = 0; i < length(board); i = i + 1) {
var coords = indexToCoords(i);
var bx = x + coords[0];
var bz = z + coords[1];
var material = null;
if(board[i]) {
material = "WHITE_CONCRETE";
} else {
material = "BLACK_CONCRETE";
}
setBlock(bx, y, bz, material);
}
}
fn handleSneak(event) {
if(event["sneaking"]) {
paused = !paused;
}
}
fn handleInteract(event) {
if(!paused) {
return;
}
var xOffset = event["x"] - x;
var yOffset = event["y"] - y;
var zOffset = event["z"] - z;
if(yOffset == 0 && xOffset < width && zOffset < height) {
var index = coordsToIndex(xOffset, zOffset);
board[index] = !board[index];
buildBoard();
}
}
fn setup() {
for (var i = 0; i<length(board); i = i + 1) {
board[i] = false;
}
board[coordsToIndex(1,1)] = true;
board[coordsToIndex(2,2)] = true;
board[coordsToIndex(2,3)] = true;
board[coordsToIndex(1,3)] = true;
board[coordsToIndex(0,3)] = true;
buildBoard();
handle("sneak", handleSneak);
handle("playerInteract", handleInteract);
}
fn tick() {
if(paused) {
return;
}
nextGeneration();
buildBoard();
iteration = iteration + 1;
}