You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Scheme猜数字程序添加重玩或按Q退出功能?

为猜数字游戏添加重玩/退出功能

以下是修改后的完整代码,已实现游戏结束后选择重玩或退出的功能:

(#%require (lib "27.ss" "srfi"))
(#%require (only racket/base read-line random flush-output))

(define (guess-game target attempts)
  (display "Guess a number from 1 to 100:")
  (newline)
  (let loop ((attempts-left attempts)
             (low 1)
             (high 100))
    (if (= attempts-left 0)
        (begin
          (display "Out of attempts. The correct number was ")
          (display target)
          (newline)
          (display "Please enter your name:")
          (newline)
          (let ((name (read-line)))
            (display "Good game, ")
            (display name)
            (newline)
            (newline)))
        (begin
          (display "Enter guess ")
          (flush-output)
          (define guess (string->number (read-line)))
          (if (not (integer? guess))
              (begin
                (display "Invalid input. Please enter a valid number.")
                (newline)
                (loop attempts-left low high))
              (if (= guess target)
                  (begin
                    (display "Correct! ")
                    (display (- attempts (- attempts-left 1)))
                    (display " guesses... Please enter your name:")
                    (newline)
                    (let ((name (read-line)))
                      (display "Good game, ")
                      (display name)
                      (newline)
                      (newline)))
                  (if (< guess target)
                      (begin
                        (display "Higher...")
                        (newline)
                        (loop (- attempts-left 1) guess high))
                      (begin
                        (display "Lower...")
                        (newline)
                        (loop (- attempts-left 1) low guess))))))))

(define (game-loop)
  (display "Welcome to the Guess Number Game!")
  (newline)
  (let main-loop ()
    (guess-game (+ (random 99) 1) 5)
    (display "Enter 'r' to replay, or 'q' to quit: ")
    (flush-output)
    (define choice (string-downcase (read-line)))
    (cond
      [(string=? choice "r") (main-loop)]
      [(string=? choice "q") (display "Thanks for playing!")]
      [else
       (display "Invalid choice. Please enter 'r' or 'q'.")
       (newline)
       (main-loop)])))

(game-loop)

关键修改说明

  • 合并重复的#%require语句,精简依赖导入
  • 新增game-loop主循环函数:负责启动游戏,每轮结束后询问用户选择,根据输入执行重玩或退出逻辑
  • 调整guess-game函数:移除原函数末尾生成随机数的逻辑,专注完成单轮游戏流程
  • 添加输入校验:对用户的重玩/退出选择做判断,输入无效时提示并重新询问
  • 修正正确猜测时的次数显示错误:原代码固定显示总次数,现在计算实际使用的猜测次数

内容的提问来源于stack exchange,提问作者Michael Ferguson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 07:42:45