From 06e89cbc5035de86351477828e4c22468d98a4a0 Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Mon, 18 Jul 2022 12:58:44 +0100 Subject: One more example with structs --- examples/entities.micro | 156 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 examples/entities.micro diff --git a/examples/entities.micro b/examples/entities.micro new file mode 100644 index 0000000..63f719f --- /dev/null +++ b/examples/entities.micro @@ -0,0 +1,156 @@ +// +// Example of an entity system +// + +const MAX_ENTS number = 10; + +const UNUSED number = 0; +const QUEUED number = 1; +const ACTIVE number = 2; + +const PLAYER number = 0; +const ENEMY number = 1; +const ITEM number = 2; + +def Entity { + var id number; + + var used number; + var type number; + var x number; + var y number; + var frame number; + var delay number; + + var lives number; + var score number; + + def update() { + println("updating player"); + } + + def erase() { + println(id, " -> erase x:", x, " y:", y, " f:", frame); + } + + def draw() { + println(id, " -> read bg x:", x, " y:", y); + + println(id, " -> blit x:", x, " y:", y, " f:", frame); + } + + def destroy() { + used = UNUSED; + } + + def test(other Entity) bool { + // TODO + return false; + } + + def enemyUpdate() { + println(id, " -> updating enemy ", used); + } + + def enemy() { + type = ENEMY; + update = enemyUpdate; + } +} + +def Game { + var ents [10]Entity; + var next number; + + def spawn(x number, y number) Entity { + var start number = next; + for { + if !ents[next].used { + ents[next].used = QUEUED; + ents[next].x = x; + ents[next].y = y; + ents[next].frame = 0; + ents[next].delay = 0; + ents[next].id = next; + return ents[next]; + } + next = (next + 1) % MAX_ENTS; + if next == start { + panic("out of ents :("); + } + } + } + + var player Entity = spawn(1, 1); + + def erase() { + for e in ents { + if e.used == ACTIVE { + e.erase(); + } + } + } + + def draw() { + for e in ents { + if e.used == ACTIVE { + e.draw(); + } + } + } + + def update() { + for e in ents { + if e.used == ACTIVE { + e.update(); + if e.type != PLAYER && e.test(player) { + if e.type == ENEMY { + player.lives = player.lives - 1; + continue; + } + if e.type == ITEM { + player.score = player.score + 10; + e.destroy(); + continue; + } + } + continue; + } + if e.used == QUEUED { + e.used = ACTIVE; + } + } + } + + def run() { + var loops number; + for loops < 10 { + erase(); + update(); + draw(); + + // buffer SWAP + + if player.lives == 0 { + println("game over"); + break; + } + + loops = loops + 1; + } + + if loops == 10 { + println("out of rounds"); + } + } +} + +var game Game; +game.player.lives = 10; + +game.spawn(1, 2).enemy(); +game.spawn(2, 2).enemy(); +game.spawn(2, 2).enemy(); +game.spawn(2, 2).enemy(); + +game.run(); -- cgit v1.2.3