RacketProjectCapstoneGame-Development
Building a Project (Capstone) in Racket | Schema Programming Part 10
3.72 min read
Md Nasim Sheikh
Congratulations! You've learned about lists, recursion, macros, and modules. Now, let's combine these skills into a functional implementation of a classic game: Guess the Number.
Advertisement
The Goal
The program will:
- Pick a random number between 1 and 100.
- Ask the user for a guess.
- Give feedback ("Too high", "Too low").
- Track the number of guesses.
- End when the user wins.
The Implementation
We'll define a recursive game loop that carries the state (target number and guess count).
#lang racket
(define (start-game)
(displayln "Welcome to the Guess the Number Game!")
(displayln "I'm thinking of a number between 1 and 100.")
(game-loop (random 1 101) 1))
(define (game-loop target guesses)
(printf "\nGuess #~a: " guesses)
(define input (read))
(cond
[(not (number? input))
(displayln "Please enter a valid number.")
(game-loop target guesses)]
[(= input target)
(printf "Correct! You won in ~a guesses.\n" guesses)]
[(< input target)
(displayln "Too low!")
(game-loop target (add1 guesses))]
[(> input target)
(displayln "Too high!")
(game-loop target (add1 guesses))]))
; Start!
(start-game)
Breakdown
start-game: Initializes the game by picking a random number and calling the loop with the initial state (count = 1).- Recursion as Loop:
game-loopcalls itself to continue the game. This is our "while loop". cond: Handles the game logic (Win vs Low vs High).- Immutability: We don't change a global
guessesvariable; we pass the new count(add1 guesses)to the next iteration.
Extensions
To practice further, try adding these features:
- Difficulty Levels: Let the user pick Easy (1-50) or Hard (1-1000).
- Save High Score: Write the best score to a file using I/O.
- GUI: Use
racket/guito make a windowed version.
Advertisement
Course Conclusion
Thank you for following this series on Scheme and Racket programming! You now possess a solid foundation in functional programming. Racket is a deep forest with many more paths to explore—web servers, language design, logic programming, and more.
Keep coding, and happy hacking!
Quick Quiz
In the game loop, how did we update the guess count?
Written by
Md Nasim Sheikh
Software Developer at softexForge
Verified Author150+ Projects
Published: