feat: improve error messages with context lines
- 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>
This commit is contained in:
@@ -1,25 +1,44 @@
|
||||
// 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!
|
||||
|
||||
fn gameLoop(secret: Int, attempts: Int): Unit with {Console} = {
|
||||
Console.print("Guess the number (1-100), attempt " + toString(attempts) + ":")
|
||||
let guess = Console.readInt()
|
||||
if guess == secret then
|
||||
Console.print("Correct! You got it in " + toString(attempts) + " attempts!")
|
||||
else if guess < secret then {
|
||||
Console.print("Too low!")
|
||||
gameLoop(secret, attempts + 1)
|
||||
}
|
||||
else {
|
||||
Console.print("Too high!")
|
||||
gameLoop(secret, attempts + 1)
|
||||
}
|
||||
// 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, Random} = {
|
||||
fn main(): Unit with {Console} = {
|
||||
Console.print("Welcome to the Guessing Game!")
|
||||
Console.print("I'm thinking of a number between 1 and 100...")
|
||||
let secret = Random.int(1, 100)
|
||||
gameLoop(secret, 1)
|
||||
// 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 {}
|
||||
|
||||
Reference in New Issue
Block a user