From 474adb740c1caca0ae9eaeb1eb65a47e2e9c9d18 Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 22 Oct 2018 19:17:00 +0200 Subject: [PATCH] Split up addRandomPattern function --- lib/src/Simulation.dart | 45 +++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/lib/src/Simulation.dart b/lib/src/Simulation.dart index f6d7a66..8144646 100644 --- a/lib/src/Simulation.dart +++ b/lib/src/Simulation.dart @@ -9,6 +9,10 @@ class Simulation { Grid map; Grid _snapshot; + final int _RANDOM_PATTERN_AMOUNT = 20; + final int _RANDOM_PATTERN_DISPERSAL = 10; + final double _RANDOM_PATTERN_SPREAD_FROM_CENTER = 1 / 3; + RuleSet rules = GameOfLife(); bool dirty = true; @@ -16,7 +20,6 @@ class Simulation { bool _renderEdges = true; bool get renderEdges => _renderEdges; - int _amount; int _dispersal; math.Point get gridSize => math.Point(map.width, map.height); @@ -38,25 +41,41 @@ class Simulation { return map; } - void addRandomPattern({int amount, int dispersal}) { - int _startingSeed = DateTime.now().millisecondsSinceEpoch; - math.Random rng = new math.Random(_startingSeed); - _amount = amount ?? rng.nextInt(20); - _dispersal = dispersal ?? 10; - int cx = rng.nextInt(map.width ~/ 3) + (map.width ~/ 3); - int cy = rng.nextInt(map.height ~/ 3) + (map.height ~/ 3); + void addRandomPattern( + {int seed, int amount, int dispersal, num spreadFromCenter}) { + math.Random rng = _getRNG(seed ?? DateTime.now().millisecondsSinceEpoch); + amount ??= rng.nextInt(_RANDOM_PATTERN_AMOUNT); + dispersal ??= _RANDOM_PATTERN_DISPERSAL; + spreadFromCenter ??= _RANDOM_PATTERN_SPREAD_FROM_CENTER; int sanityCheck = 0; - for (var i = 0; i < (_amount); i++) { + Map changeSet = {}; + for (var i = 0; i < (amount); i++) { sanityCheck++; - getCellState(cx, cy) + math.Point cell = _getRandomPoint(rng, gridSize, spreadFromCenter); + getCellState(cell.x, cell.y) ? i-- - : setCellState( - cx + rng.nextInt(_dispersal), cy + rng.nextInt(_dispersal), true); + : changeSet[map.toIndex(cell.x, cell.y)] = true; if (sanityCheck > 100 && sanityCheck > i * 3) break; } + mergeStateChanges(changeSet); + } - dirty = true; + math.Random _getRNG(int seed) { + math.Random rng = new math.Random(seed); + return rng; + } + + math.Point _getRandomPoint( + math.Random rng, math.Point size, num spreadFromCenter) { + math.Point absoluteSpread = + math.Point(map.width * spreadFromCenter, map.height * spreadFromCenter); + math.Point center = math.Point(map.width / 2, map.height / 2); + num cx = rng.nextInt(absoluteSpread.x.toInt()) + + (center.x - absoluteSpread.x / 2); + num cy = rng.nextInt(absoluteSpread.y.toInt()) + + (center.y - absoluteSpread.y / 2); + return math.Point(cx.toInt(), cy.toInt()); } void setCellState(int x, int y, bool state) {