RosettaCodeData/Task/Forest-fire/D/forest-fire-2.d

69 lines
2.1 KiB
D
Raw Permalink Normal View History

2013-10-27 22:24:23 +00:00
import std.stdio, std.random, std.algorithm, std.typetuple,
simpledisplay;
2013-04-10 16:57:12 -07:00
2013-10-27 22:24:23 +00:00
enum double TREE_PROB = 0.55; // Original tree probability.
enum double F_PROB = 0.01; // Auto combustion probability.
enum double P_PROB = 0.01; // Tree creation probability.
enum worldSide = 600;
2013-04-10 16:57:12 -07:00
2013-10-27 22:24:23 +00:00
enum Cell : ubyte { empty, tree, burning }
alias World = Cell[worldSide][];
2013-04-10 16:57:12 -07:00
immutable white = Color(255, 255, 255),
red = Color(255, 0, 0),
green = Color(0, 255, 0);
void nextState(ref World world, ref World nextWorld,
ref Xorshift rnd, Image img) {
immutable nr = world.length;
immutable nc = world[0].length;
2013-10-27 22:24:23 +00:00
foreach (immutable r, const row; world)
foreach (immutable c, immutable elem; row)
START: final switch (elem) with (Cell) {
case empty:
2013-04-10 16:57:12 -07:00
img.putPixel(c, r, white);
2015-02-20 00:35:01 -05:00
nextWorld[r][c] = rnd.uniform01 < P_PROB ? tree : empty;
2013-04-10 16:57:12 -07:00
break;
2013-10-27 22:24:23 +00:00
case tree:
2013-04-10 16:57:12 -07:00
img.putPixel(c, r, green);
2013-10-27 22:24:23 +00:00
foreach (immutable rowShift; TypeTuple!(-1, 0, 1))
foreach (immutable colShift; TypeTuple!(-1, 0, 1))
2013-04-10 16:57:12 -07:00
if ((r + rowShift) >= 0 && (r + rowShift) < nr &&
(c + colShift) >= 0 && (c + colShift) < nc &&
world[r + rowShift][c + colShift] == Cell.burning) {
nextWorld[r][c] = Cell.burning;
2013-10-27 22:24:23 +00:00
break START;
2013-04-10 16:57:12 -07:00
}
2015-02-20 00:35:01 -05:00
nextWorld[r][c]= rnd.uniform01 < F_PROB ? burning : tree;
2013-10-27 22:24:23 +00:00
break;
2013-04-10 16:57:12 -07:00
2013-10-27 22:24:23 +00:00
case burning:
2013-04-10 16:57:12 -07:00
img.putPixel(c, r, red);
2013-10-27 22:24:23 +00:00
nextWorld[r][c] = empty;
2013-04-10 16:57:12 -07:00
break;
}
swap(world, nextWorld);
}
void main() {
auto rnd = Xorshift(1);
2013-10-27 22:24:23 +00:00
auto world = new World(worldSide);
foreach (ref row; world)
2013-04-10 16:57:12 -07:00
foreach (ref el; row)
2015-02-20 00:35:01 -05:00
el = rnd.uniform01 < TREE_PROB ? Cell.tree : Cell.empty;
2013-10-27 22:24:23 +00:00
auto nextWorld = new World(world[0].length);
2013-04-10 16:57:12 -07:00
auto w= new SimpleWindow(world.length,world[0].length,"ForestFire");
auto img = new Image(w.width, w.height);
w.eventLoop(1, {
2013-10-27 22:24:23 +00:00
auto painter = w.draw;
2013-04-10 16:57:12 -07:00
nextState(world, nextWorld, rnd, img);
painter.drawImage(Point(0, 0), img);
});
}