Galton box animation: Difference between revisions

Updated D entry
(Updated D entry)
(Updated D entry)
Line 405:
enum centerH = pinsBaseW + (boxW - (pinsBaseW * 2 - 1)) / 2 - 1;
 
enum Cell : char { empty = ' ',
alias CellBaseType = char;
enum Cell : CellBaseType { empty ball = ' o',
ballwall = 'o|',
wall corner = '|+',
floor corner = '+-',
pin floor = '-.', }
pin = '.' }
 
Cell[boxW][boxH] box; // Galton box. Will be printed upside-down.
Line 418 ⟶ 417:
int x, y; // Position.
 
this(in int x_, in int y_) nothrow @safe @nogc
in {
assert(box[y_][x_] == Cell.empty);
Line 436 ⟶ 435:
return; // Reached the bottom of the box.
 
final switch (box[y - 1][x]) with (Cell) {
finalcase switch (box[y - 1][x]) {empty:
casebox[y][x] = Cell.empty:;
box[y][x] = Cell.empty--;
box[y][x] = y--Cell.ball;
break;
case ball, wall, corner, floor:
// It's frozen. (It always piles on other balls).
elsebreak;
}case pin:
box[y][x] = Cell.ballempty;
xy--;
if (box[y][x - 1] == Cell.empty && box[y][x + 1] == Cell.empty) {
x += uniform(0, 2) * 2 - pin = '.' }1;
box[y][x] = Cell.ball;
breakreturn;
case} ball,else wall,if corner,(box[y][x floor:- 1] == Cell.empty) {
// It's frozen. (It always piles on other balls).x++;
} else break;{
case pin: x--;
box[y][x] = Cell.empty;}
box[y][x] = y--Cell.ball;
if (box[y][x - 1] == Cell.empty &&break;
box[y][x + 1] == Cell.empty) {
x += uniform(0, 2) * 2 - 1;
box[y][x] = Cell.ball;
return;
} else if (box[y][x - 1] == Cell.empty)
x++;
else
x--;
box[y][x] = Cell.ball;
break;
}
}
}
Line 467 ⟶ 464:
void initializeBox() {
// Set ceiling and floor:
box[0][] = (Cell.corner ~ [Cell.floor].replicate(boxW - 2) ~ Cell.corner;
~ Cell.corner)[];
box[$ - 1][] = box[0][];
 
// Set walls:
foreach (immutable r; 1 .. boxH - 1)
box[r][0] = box[r][$ - 1] = Cell.wall;
 
Line 478 ⟶ 474:
foreach (immutable nPins; 1 .. pinsBaseW + 1)
foreach (pin; 0 .. nPins)
box[boxH - 2 - nPins][centerH + 1 - nPins + pin * 2] = Cell.pin;
= Cell.pin;
}
 
void drawBox() {
foreach_reverse (const ref row; box)
writelnwritefln(cast"%(CellBaseType[]%c%)", row);
}
 
Line 495 ⟶ 490:
if (i < nMaxBalls)
balls ~= Ball(centerH, boxH - 2); // Add ball.
drawBox();
 
// Next step for the simulation.