RacketProjectCapstoneGame-Development

Building a Project (Capstone) in Racket | Schema Programming Part 10

3.72 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

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:

  1. Pick a random number between 1 and 100.
  2. Ask the user for a guess.
  3. Give feedback ("Too high", "Too low").
  4. Track the number of guesses.
  5. 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

  1. start-game: Initializes the game by picking a random number and calling the loop with the initial state (count = 1).
  2. Recursion as Loop: game-loop calls itself to continue the game. This is our "while loop".
  3. cond: Handles the game logic (Win vs Low vs High).
  4. Immutability: We don't change a global guesses variable; 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/gui to 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!

Back to Series Overview

Quick Quiz

In the game loop, how did we update the guess count?

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like