- Show 2 lines of context before and after errors (dimmed) - Fix guessing_game.lux to be non-interactive for testing - Use binary search simulation to demonstrate game logic Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
45 lines
1.4 KiB
Plaintext
45 lines
1.4 KiB
Plaintext
// Number guessing game - demonstrates Random and Console effects
|
|
//
|
|
// Expected output:
|
|
// Welcome to the Guessing Game!
|
|
// Target number: 42
|
|
// Simulating guesses...
|
|
// Guess 50: Too high!
|
|
// Guess 25: Too low!
|
|
// Guess 37: Too low!
|
|
// Guess 43: Too high!
|
|
// Guess 40: Too low!
|
|
// Guess 41: Too low!
|
|
// Guess 42: Correct!
|
|
// Found in 7 attempts!
|
|
|
|
// Game logic - check a guess against the secret
|
|
fn checkGuess(guess: Int, secret: Int): String =
|
|
if guess == secret then "Correct"
|
|
else if guess < secret then "Too low"
|
|
else "Too high"
|
|
|
|
// Binary search simulation to find the number
|
|
fn binarySearch(low: Int, high: Int, secret: Int, attempts: Int): Int with {Console} = {
|
|
let mid = (low + high) / 2
|
|
let result = checkGuess(mid, secret)
|
|
Console.print("Guess " + toString(mid) + ": " + result + "!")
|
|
|
|
if result == "Correct" then attempts
|
|
else if result == "Too low" then binarySearch(mid + 1, high, secret, attempts + 1)
|
|
else binarySearch(low, mid - 1, secret, attempts + 1)
|
|
}
|
|
|
|
fn main(): Unit with {Console} = {
|
|
Console.print("Welcome to the Guessing Game!")
|
|
// Use a fixed "secret" for reproducible output
|
|
let secret = 42
|
|
Console.print("Target number: " + toString(secret))
|
|
Console.print("Simulating guesses...")
|
|
|
|
let attempts = binarySearch(1, 100, secret, 1)
|
|
Console.print("Found in " + toString(attempts) + " attempts!")
|
|
}
|
|
|
|
let output = run main() with {}
|