GridWorld.fromString constructor
GridWorld.fromString(
- String x
fromString initializes a world from a multi-line string.
The string argument should be a multi-line string like
'''
...#...
..#.#..
.#.#.#.
...#...
...#...
...#...
'''
The shape must be rectangular (not necessarily square).
Cells are initialized per the rules
'.'
: dead- anything else: alive
Implementation
factory GridWorld.fromString(String x) {
final rawLines = x.split('\n');
final lines = List<List<int>>.empty(growable: true);
for (final line in rawLines) {
if (line.isNotEmpty) {
lines.add(line.codeUnits);
}
}
if (lines.length < 2) {
throw ArgumentError('must supply at least two lines');
}
final nR = lines.length;
final nC = lines[0].length;
for (var i = 1; i < lines.length; i++) {
if (lines[i].length != nC) {
throw ArgumentError('length (${lines[i].length}) of line $i must '
'match length ($nC) of first line');
}
}
final list = List<bool>.filled(nR * nC, false);
// final list = <bool>[].filled(nR * nC,0);
var k = 0;
for (final line in lines) {
for (final ch in line) {
list[k] = ch != GridWorld.chDead;
k++;
}
}
return GridWorld(nR, list);
}