-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorld.java
More file actions
105 lines (85 loc) · 2.78 KB
/
World.java
File metadata and controls
105 lines (85 loc) · 2.78 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
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
package com.company;
import java.util.Random;
/*
* This class handles the World object and storing all data related to it
*/
public class World {
private char[][] world;
private int[][] neighbors;
private final int worldSize;
private int generation;
private int alive;
public World(int worldSize) {
this.worldSize = worldSize;
this.world = new char[worldSize][worldSize];
this.neighbors = new int[worldSize][worldSize];
Random random = new Random();
int count = 0;
for (int i = 0; i < worldSize; i++) {
for (int j = 0; j < worldSize; j++) {
world[i][j] = random.nextBoolean() ? 'O' : ' ';
if (world[i][j] == 'O') {
count++;
}
}
}
for (int i = 0; i < worldSize; i++) {
for (int j = 0; j < worldSize; j++) {
neighbors[i][j] = getNumNeighbors(world, i, j);
}
}
alive = count;
generation++;
}
/*
* Get the next generation of the world depending on their neighbors in the previous generation
*/
public void nextGeneration() {
char[][] nextGeneration = new char[worldSize][worldSize];
int[][] nextGenNeighbors = new int[worldSize][worldSize];
int count = 0;
for (int y = 0; y < nextGeneration.length; y++) {
for (int x = 0; x < nextGeneration[y].length; x++) {
int numNeighbors = getNumNeighbors(world, y, x);
nextGenNeighbors[y][x] = numNeighbors;
if (numNeighbors == 3 || (world[y][x] == 'O' && numNeighbors == 2)) {
nextGeneration[y][x] = 'O';
count++;
} else {
nextGeneration[y][x] = ' ';
}
}
}
alive = count;
world = nextGeneration;
neighbors = nextGenNeighbors;
generation++;
}
private int getNumNeighbors(char[][] world, int y, int x) {
int numNeighbors = 0;
for (int i = -1; i < 2; i++) {
int row = y + i < 0 ? worldSize - 1 : y + i;
row = row >= worldSize ? 0 : row;
for (int j = -1; j < 2; j++) {
int col = x + j < 0 ? worldSize - 1 : x + j;
col = col >= worldSize ? 0 : col;
if (!(row == y && col == x) && world[row][col] == 'O') {
numNeighbors++;
}
}
}
return numNeighbors;
}
public char[][] getCharArray() {
return world;
}
public int[][] getNeighborArray() {
return neighbors;
}
public int getGeneration() {
return generation;
}
public int getAlive() {
return alive;
}
}