From a770dd88e6c55ac7fd67c243ad30f04425e3e175 Mon Sep 17 00:00:00 2001
From: Holden Rohrer
Date: Sun, 8 Aug 2021 23:59:29 -0400
Subject: featureful saving and loading
---
source/spots.d | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 60 insertions(+), 1 deletion(-)
(limited to 'source/spots.d')
diff --git a/source/spots.d b/source/spots.d
index 0f9d8b7..f57ba8f 100644
--- a/source/spots.d
+++ b/source/spots.d
@@ -2,8 +2,9 @@ import std.bigint;
import std.digest.crc;
import std.random : unpredictableSeed;
import std.range;
+import std.stdio;
import lru : LRUCache;
-import deimos.ncurses;
+import std.traits : isSomeString;
private BigInt positive(BigInt n)
{
@@ -27,6 +28,18 @@ struct Spot
_contents = c;
}
+ string toString()
+ {
+ import std.format : format;
+
+ return format("'%c'", _contents);
+ }
+
+ void fromString(S)(S s) if (isSomeString!S)
+ {
+ _contents = cast(char) s[1];
+ }
+
@property contents()
{
return _contents;
@@ -46,6 +59,8 @@ struct Spot
interface SpotSource
{
Spot opIndex(BigInt y, BigInt x);
+ void save(File);
+ void load(File);
}
class RandomSource : SpotSource
@@ -99,12 +114,24 @@ class RandomSource : SpotSource
cache[[y, x]] = ret;
return ret;
}
+
+ public void save(File f)
+ {
+ f.writefln!"%d %f"(seed, density);
+ }
+
+ public void load(File f)
+ {
+ f.readf!"%d %f\n"(seed, density);
+ cache = new LRUCache!(BigInt[2], Spot)(50000);
+ }
}
class OverlaySource : SpotSource
{
private SpotSource _base;
private Spot[BigInt[2]] _overlay;
+ immutable private string terminator = "END OVERLAY\n";
this(SpotSource base)
{
@@ -133,6 +160,38 @@ class OverlaySource : SpotSource
return _base[y, x];
}
+ void save(File f)
+ {
+ _base.save(f);
+ foreach (coord; _overlay.keys())
+ {
+ f.writefln!"%s, %s: %s"(coord[0], coord[1], _overlay[coord]);
+ }
+ f.write(terminator);
+ }
+
+ void load(File f)
+ {
+ import std.conv : to;
+ import std.algorithm.iteration;
+
+ _base.load(f);
+ foreach (char[] line; f.lines)
+ {
+ if (line == terminator)
+ break;
+ auto trim = line.filter!(a => a == ' ' || a == '\r' || a == '\n').array;
+ auto parts = trim.splitter(':');
+ auto ints = parts.moveFront.splitter(',').map!(to!BigInt);
+ BigInt[2] coord;
+ coord[0] = ints.moveFront;
+ coord[1] = ints.front;
+ auto s = new Spot();
+ (*s).fromString(parts.front);
+ _overlay[coord] = *s;
+ }
+ }
+
unittest
{
auto base = new RandomSource(0, 0.0);
--
cgit