Files
gpd-326-en/Complex_Algorithms/Assets/Scripts/GameOfLife/GameOfLife.cs
T

131 lines
4.3 KiB
C#

using UnityEngine;
namespace DefaultNamespace.GameOfLife
{
public class GameOfLife : MonoBehaviour
{
[SerializeField] private Cell _cellPrefab;
[SerializeField, Range(1, 100)] private int _rows = 50;
[SerializeField, Range(1, 100)] private int _columns = 50;
[SerializeField] private float _isAliveRandomThreshold = 0.5f;
private Cell[] _cells;
private int CalculateIndex(int row, int column) => row * _columns + column;
private void Start()
{
_cells = new Cell[_rows * _columns];
for (int row = 0; row < _rows; row++)
{
for (int column = 0; column < _columns; column++)
{
var cell = Instantiate(_cellPrefab, transform);
cell.name = $"Cell {row:000} / {column:000}";
cell.transform.localPosition = new Vector3(row, column, 0);
_cells[CalculateIndex(row, column)] = cell;
}
}
}
private void SimulateStep()
{
// 1. collect new states
bool[] newStates = new bool[_cells.Length];
// 2. change states - apply rules
for (int x = 0; x < _columns; x++)
{
for (int y = 0; y < _rows; y++)
{
int index = CalculateIndex(x, y);
bool cellState = _cells[index].IsAlive;
int livingNeighbors = CountLivingNeighbors(x, y);
if (cellState)
{
// cell is alive
// rule 1: less than 2 living neighbors -> die
if (livingNeighbors < 2)
{
newStates[index] = false;
}
// rule 2: 2 or 3 living neighbors -> stay alive
if (livingNeighbors is 2 or 3)
{
newStates[index] = true;
}
// rule 3: more than 3 living neighbors -> die
if (livingNeighbors > 3)
{
newStates[index] = false;
}
}
else
{
// cell is dead
// rule 4: exactly 3 living neighbors -> come alive
if (livingNeighbors == 3)
{
newStates[index] = true;
}
}
}
}
// 3. apply new states
for (int i = 0; i < _cells.Length; i++)
{
_cells[i].IsAlive = newStates[i];
}
}
private int CountLivingNeighbors(int row, int column)
{
int count = 0;
for (int dx = -1; dx <= 1; dx++)
{
for (int dy = -1; dy <= 1; dy++)
{
// exception: own cell
if (dx == 0 && dy == 0) continue;
int neighborRow = row + dx;
int neighborColumn = column + dy;
// exception: out of bounds
if (neighborRow < 0 || neighborRow >= _rows) continue;
if (neighborColumn < 0 || neighborColumn >= _columns) continue;
if (_cells[CalculateIndex(neighborRow, neighborColumn)].IsAlive)
{
count++;
}
}
}
return count;
}
private void ResetGrid()
{
for (int i = 0; i < _cells.Length; i++)
{
// _cells[i].IsAlive = false;
_cells[i].IsAlive = Random.value > _isAliveRandomThreshold;
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.S)) SimulateStep();
if (Input.GetKeyDown(KeyCode.R)) ResetGrid();
if (Input.GetKeyDown(KeyCode.Space)) InvokeRepeating(nameof(SimulateStep), 0.0f, 0.5f);
if (Input.GetKeyDown(KeyCode.Escape)) CancelInvoke(nameof(SimulateStep));
}
}
}