Last active
June 24, 2024 08:03
-
-
Save fabioesposito/a32bd0590eb78190935e00a1e0249dec to your computer and use it in GitHub Desktop.
Learning about Lists 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 | |
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() | |
let n = Knight(..defender, health: { defender.health - d }) | |
io.debug( | |
int.to_string(attacker.id) | |
<> " attacked " | |
<> int.to_string(defender.id) | |
<> " with damage " | |
<> int.to_string(d), | |
) | |
let seq = case n.health > 0 { | |
True -> { | |
[n, ..xs] | |
} | |
False -> { | |
io.debug(int.to_string(n.id) <> " eliminated") | |
xs | |
} | |
} | |
let seq = list.append(seq, [attacker]) | |
game_loop(seq) | |
} | |
} | |
} | |
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