-
-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(examples): Game of life example
- Loading branch information
Showing
1 changed file
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |