-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameOfLife.cs
132 lines (87 loc) · 3.51 KB
/
GameOfLife.cs
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
using UnityEngine;
using UnityEngine.UI;
public class GameOfLife : MonoBehaviour
{
public GameObject cellPrefab;
Cell[,] cells;
public int NumberOfColloms, NumberOfRows;
public float cellSize = 0.28f;
public float spawnChanceproc = 15;
bool[,] nextState;
//public InputField Cellsize;
void Start()
{
NumberOfColloms = (int)Mathf.Floor((Camera.main.orthographicSize * Camera.main.aspect * 2) / cellSize);
NumberOfRows = (int)Mathf.Floor(Camera.main.orthographicSize * 2 / cellSize);
cells = new Cell[NumberOfColloms, NumberOfRows];
nextState = new bool[NumberOfColloms, NumberOfRows];
for (int y = 0; y < NumberOfRows; y++)
{
//for each column in each row
for (int x = 0; x < NumberOfColloms; x++)
{
//Create our game cell objects, multiply by cellSize for correct world placement
Vector2 newPos = new Vector2(x * cellSize - Camera.main.orthographicSize * Camera.main.aspect,
y * cellSize - Camera.main.orthographicSize);
var newCell = Instantiate(cellPrefab, newPos, Quaternion.identity);
newCell.transform.localScale = Vector2.one * cellSize;
cells[x, y] = newCell.GetComponent<Cell>();
//Random check to see if it should be alive
if (Random.Range(0, 100) < spawnChanceproc)
{
cells[x, y].alive = true;
}
cells[x, y].UpdateStatus();
}
}
}
void Update()
{
for (int y = 0; y < NumberOfRows; y++)
{
for (int x = 0; x < NumberOfColloms; x++)
{
// Check the neighbors of grid[x, y] (left, right, top, bottom, diagonals)
int liveNeighbors = 0;
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0) continue;
// Skip the cell itself
int neighborX = x + j;
int neighborY = y + i;
// Make sure the neighbor is within bounds
if (neighborX >= 0 && neighborX < NumberOfColloms && neighborY >= 0 && neighborY < NumberOfRows)
{
if (cells[neighborX, neighborY].alive)
{
liveNeighbors++;
}
}
}
}
if (cells[x, y].alive && (liveNeighbors < 2 || liveNeighbors > 3))
{
nextState[x, y] = false;
}
else if (cells[x, y].alive == false && liveNeighbors == 3)
{
nextState[x, y] = true;
}
else
{
nextState[x, y] = cells[x,y].alive;
}
}
}
for (int y = 0; y < NumberOfRows; y++)
{
for (int x = 0; x < NumberOfColloms; x++)
{
cells[x, y].alive = nextState[x, y];
cells[x, y].UpdateStatus();
}
}
}
}