我正在研究RACKET中的一个非常基本的记忆游戏,向用户提供1到10个7个随机数,并要求他们以相同的顺序输入数字。我可以让它工作一次,但我希望它能持续运行直到用户退出。 (重复主程序)关于如何实现这一点的任何想法???
(require math/base)
; =======================================
; Functions
; =======================================
; set essentially constants
(define lowerLimit 1)
(define upperLimit 11)
(define amount 7)
; builds a list with random integers between lowerLimit and upperLimit
(define (buildSimon x L)
(cond [(= x 0) L]
[else (buildSimon (- x 1) (cons (random-integer lowerLimit upperLimit) L))]))
; adds element to back of the list
(define (addBack L e)
(if (null? L)
(list e)
(cons (first L) (addBack (rest L) e))))
; gets input from user and builds list
(define (getInput n x L)
(cond [(= n 1) (addBack L x)]
[else (getInput (- n 1) (read) (addBack L x))]))
; =======================================
; Main program below here
; =======================================
; Generate new random number sequence
(printf "Simon says: ")
(define sequence (buildSimon amount (list)))
(display sequence) (newline)
(printf "== Memorize and guess ==\n")
(printf "== Type 'go' and hit enter to guess ==\n")
(read)
; Add spacing to hide numbers
(printf "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
(printf "== Type the numbers in order as they appeared. ==\n")
(printf "== Hit ENTER in between each number. ==\n")
; Gather input for comparison
(define answer (getInput amount (read) (list)))
; Do comparison
(if (equal? sequence answer)
(printf "Correct! Congratulations on your perfect memory.\n")
(printf "Wrong! I'm sorry your memory has failed you.\n"))
提前谢谢。
答案 0 :(得分:1)
您可以创建一个包含所有主代码的函数,函数的最后一行递归调用自身。
答案 1 :(得分:0)
如前所述,您可以使用简单的递归函数:
(define (game-loop)
(let ([finished? (run-your-code)])
(unless finished?
(game-loop))))
(game-loop)
其中(run-your-code)
是生成游戏当前状态并根据用户输入决定是否已完成或需要另一次运行的函数。
作为替代方案,您可以使用while loop,但我发现这不如上述解决方案优雅。除非我们考虑使用可变游戏状态,否则代码也不会发生太大变化。然后,代码将是:
(define (game-loop)
(while (done? game-state)
(render-next-step game-state)))
(game-loop)
另一种方法是在无限循环中使用#:break
:
(define (game-loop)
(for ([i (in-naturals)]
#:break (done? game-state))
(render-next-step game-state)))
(game-loop)
再次使用可变游戏状态。
但这些只是一些想法(你可以通过使当前状态成为game-loop
的参数来摆脱可变性。你应该在game-loop
函数中的“主程序在这里”之后封装所有代码,以使事情变得更容易。