forked from skooter500/OOP-2021-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LifeBoard.java
143 lines (126 loc) · 3.39 KB
/
LifeBoard.java
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
package ie.tudublin;
import processing.core.PApplet;
public class LifeBoard {
boolean[][] board;
boolean[][] next;
int size;
float cellSize;
PApplet pa;
public LifeBoard(int size, PApplet pa)
{
board = new boolean[size][size];
next = new boolean[size][size];
this.size = size;
this.pa = pa;
cellSize = pa.width / (float) size;
}
public void randomise()
{
for(int row = 0 ; row < size ; row ++)
{
for(int col = 0 ; col < size ; col ++)
{
board[row][col] = pa.random(1.0f) > 0.5f;
}
}
}
public void update()
{
// If cell is alive
// 2 -3 - Survives
// if a dead cell has 3 neighbours - comes to life
for(int row = 0 ; row < size ; row ++)
{
for (int col = 0 ; col < size ; col ++)
{
int count = countCellsAround(row, col);
if (isAlive(row, col))
{
if (count == 2 || count == 3)
{
next[row][col] = true;
}
else
{
next[row][col] = false;
}
}
else
{
if (count == 3)
{
next[row][col] = true;
}
else
{
next[row][col] = false;
}
}
}
}
boolean[][] temp;
temp = board;
board = next;
next = temp;
}
public int countCellsAround(int row, int col)
{
int count = 0;
// Your bit goes here!
for(int i = row - 1 ; i <= row + 1 ; i ++)
{
for(int j = col -1 ; j <= col + 1; j ++)
{
if (! (i == row && j == col))
{
if (isAlive(i, j))
{
count ++;
}
}
}
}
return count;
}
public void setAlive(int row, int col, boolean alive)
{
if (row >= 0 && row < size && col >= 0 && col < size)
{
board[row][col] = alive;
}
}
public boolean isAlive(int row, int col)
{
if (row >= 0 && row < size && col >= 0 && col < size)
{
return board[row][col];
}
else
{
return false;
}
}
public void render()
{
pa.background(0);
for(int row = 0 ; row < size ; row ++)
{
for(int col = 0 ; col < size ; col ++)
{
float x = PApplet.map(col, 0, size, 0, pa.width);
float y = PApplet.map(row, 0, size, 0, pa.height);
x = cellSize * col;
y = cellSize * row;
if (board[row][col])
{
pa.fill(0, 255, 0);
}
else
{
pa.noFill();
}
pa.rect(x, y, cellSize, cellSize);
}
}
}
}