ludus-scripts/ifs.ld

39 lines
1.6 KiB
Plaintext
Raw Normal View History

2024-06-11 21:37:04 +00:00
& Lesson 9: Flipping coins
& Let's try a different version of this random walk. Instead of going an arbitrary amount forward, and an arbitrary amount left or right, let's turn left OR right, let's go forward OR backwards by a fixed amount.
& We need coin flips!
let coin = [true, false] & these are booleans: equivalent to heads and tails
& ^^^^^^^^^^^^^ this is a list with two members
& Lists are like parameters or arguments, but with square brackets
fn flip_coin () -> random (coin)
& ^^^^^^ `random` will pick a random element of a collection
& ^^^^ `coin` is a collection of two elements
let times = random (10, 30) & we'll do this a random number of times
repeat times {
pc! (random (colors))
& `if` is our first conditional form
if flip_coin ()
& ^^ the expression starts with `if`
& ^^^^^^^^^^^^ this is our *condition*
& if the condition is true, run the `then` branch
& if it is false, run the `else` branch
& in this case, our condition is the coin flip
then rt! (0.25)
& ^^^^ `then` gives us the branch to evaluate if true
& ^^^^^^^^^^ in this case, turn right 0.25 turns
else lt! (0.25)
& ^^^^ `else` gives us the branch to evaluate if false
& NB: Ludus requires you have a false branch
& ^^^^^^^^^^ in this case, turn left 0.25 turns
& This whole expression is:
& turn right 50% of the time, turn left 50% of the time
& we don't need newlines before `then` and `else`
& but you can include them!
if flip_coin () then fd! (5) else bk! (5)
}