Last active
June 24, 2024 08:03
-
-
Save fabioesposito/bd3ca480b1e56ba3a13cf3d3a99db60f to your computer and use it in GitHub Desktop.
Learning about Queues in Gleam
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
import gleam/int | |
import gleam/io | |
import gleam/list | |
import gleam/queue | |
pub type Knight { | |
Knight(id: Int, health: Int) | |
} | |
pub fn main() { | |
let ks = | |
list.range(1, 6) | |
|> list.map(fn(x) { Knight(id: x, health: 100) }) | |
|> list.shuffle | |
game_loop(ks) | |
} | |
pub fn game_loop(ks: List(Knight)) { | |
case ks { | |
[] -> io.debug("no players left") | |
[winner] -> io.debug("player " <> int.to_string(winner.id) <> " wins!") | |
[attacker, defender, ..xs] -> { | |
let d = roll_dice() | |
io.debug( | |
int.to_string(attacker.id) | |
<> " attacked " | |
<> int.to_string(defender.id) | |
<> " with damage " | |
<> int.to_string(d), | |
) | |
let new_defender = Knight(..defender, health: { defender.health - d }) | |
let sequence = | |
queue.from_list(xs) | |
|> queue.push_front(new_defender) | |
|> queue.push_back(attacker) | |
|> queue.to_list | |
|> list.filter(fn(x) { | |
case x.health > 0 { | |
True -> True | |
False -> { | |
io.debug(int.to_string(x.id) <> " eliminated") | |
False | |
} | |
} | |
}) | |
game_loop(sequence) | |
} | |
} | |
} | |
pub fn roll_dice() { | |
int.random(6) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment