-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBoardState.cs
122 lines (98 loc) · 3.21 KB
/
BoardState.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
using System;
using System.IO;
namespace Pobs.GameOfLife
{
public class BoardState
{
public BoardState(int width, int height)
{
Width = width;
Height = height;
_cells = new bool[width * height];
}
public int Width { get; }
public int Height { get; }
public bool AllCellsDead { get; internal set; }
private readonly bool[] _cells;
internal void SetCellState(int x, int y, bool value)
{
_cells[(y * Height) + x] = value;
}
public (bool, int) GetCellState(int x, int y)
{
return (GetValue(x, y), GetNeighbours(x, y));
}
private bool GetValue(int idx)
{
if (idx < 0 || idx > (Height * Width))
return false;
return _cells[idx];
}
private bool GetValue(int x, int y) => GetValue((y * Height) + x);
public ReadOnlySpan<bool> GetRow(int row)
{
if (row > Height || row < 0)
{
throw new ArgumentException("Specified row was outside of range");
}
return _cells.AsSpan(row * Width, Width);
}
private int GetNeighbours(int x, int y)
{
var count = 0;
for (var j = -1; j < 1; j++)
{
for (var i = -1; i < 1; i++)
{
if (j == 0 && i == 0)
continue;
if (GetValue(x + i, y + j))
count++;
}
}
return count;
}
public static BoardState CreateRandomState(int width, int height)
{
var random = new Random();
var state = new BoardState(width, height);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
state.SetCellState(x, y, random.Next(0, 3) == 0);
}
}
return state;
}
public static BoardState FromFile(string filename)
{
if (!File.Exists(filename))
{
throw new ArgumentException($"No file with name {filename} exists.", nameof(filename));
}
var content = File.ReadAllText(filename);
var rows = content.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var width = rows[0].Length;
var height = rows.Length;
var state = new BoardState(width, height);
for (var y = 0; y < height; y++)
{
var row = rows[y];
if (row.Length != width)
{
throw new InvalidDataException("Not all rows are of identical length, file is invalid for Game of Life.");
}
for (var x = 0; x < row.Length; x++)
{
var cell = row[x];
if (cell != '_')
{
state.SetCellState(x, y, true);
}
}
}
return state;
}
}
}