Skip to content

Commit

Permalink
feat(examples): Game of life example
Browse files Browse the repository at this point in the history
  • Loading branch information
giann committed Sep 9, 2023
1 parent f2f13ac commit f4ff372
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions examples/game-of-life.buzz
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import "std";
import "io" as io;
import "os";
import "debug";
| import "examples/sdl-wrapped";

object World {
int width,
int height,
[bool] cells,

static fun init(int width, int height) > World {
World world = World{
width = width,
height = height,
cells = [<bool>],
};

for (int i = 0; i < width * height; i = i + 1) {
world.cells.append(random(max: 5) == 1);
}

return world;
}

fun neighbors(int x, int y) > int {
int liveCount = 0;
for (int dy = y - 1; dy <= y + 1; dy = dy + 1) {
for (int dx = x - 1; dx <= x + 1; dx = dx + 1) {
if (dy > 0 and dy > 0 and dx < this.width and dy < this.height and this.cells[dy * this.width + dx]) {
liveCount = liveCount + 1;
}
}
}

return liveCount - if (this.cells[y * this.width + x]) 1 else 0;
}

fun step() > void {
[bool] cells = [<bool>];
for (int y = 0; y < this.height; y = y + 1) {
for (int x = 0; x < this.width; x = x + 1) {
const int coordinate = y * this.width + x;
const int liveNeighbors = this.neighbors(x: x, y: y);

cells.append(liveNeighbors == 3 or (this.cells[coordinate] and liveNeighbors == 2));
}
}

this.cells = cells;
}

fun dump() > void {
for (int y = 0; y < this.height; y = y + 1) {
for (int x = 0; x < this.width; x = x + 1) {
io.stdout.write(
if (this.cells[y * this.width + x])
"x"
else
"."
) catch void;
}
io.stdout.write("\n") catch void;
}
}
}

fun main([str] args) > void {
int? width = if (args.len() > 0) parseInt(args[0]) else null;
int? height = if (args.len() > 1) parseInt(args[1]) else null;

World world = World.init(width: width ?? 10, height: height ?? 10);

while (true) {
io.stdout.write("\027[2J") catch void;

world.dump();
world.step();

sleep(500.0);
}
}

0 comments on commit f4ff372

Please sign in to comment.