-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameOfLife.java
More file actions
75 lines (57 loc) · 1.75 KB
/
GameOfLife.java
File metadata and controls
75 lines (57 loc) · 1.75 KB
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
import processing.core.PApplet;
public class GameOfLife extends PApplet {
int w = 8;
int cols, rows;
int[][] board;
public void settings() {
size(800, 800);
cols = width/w;
rows = height/w;
board = new int[cols][rows];
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
board[x][y] = (int) (Math.random() * 2);
}
}
}
public void generate() {
int[][] next = new int[cols][rows];
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
int neighbors = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
neighbors += board[(x + i + cols) % rows][(y + j + rows) % rows];
}
}
neighbors -= board[x][y];
if ((board[x][y] == 1) && (neighbors < 2)) next[x][y] = 0;
else if ((board[x][y] == 1) && (neighbors > 3)) next[x][y] = 0;
else if ((board[x][y] == 0) && (neighbors == 3)) next[x][y] = 1;
else next[x][y] = board[x][y];
}
}
board = next;
}
public void display() {
for ( int i = 0; i < cols;i++) {
for ( int j = 0; j < rows;j++) {
if ((board[i][j] == 1)) fill(0);
else fill(255);
stroke(0);
rect(i*w, j*w, w, w);
}
}
}
public void draw() {
background(255);
generate();
display();
}
public void mousePressed() {
settings();
}
public static void main(String... args){
PApplet.main("GameOfLife");
}
}