嗨,你能帮我添加一种方法,使每个灯有不同的计时器长度。我正在做一个世界状态/大爆炸程序,它创建了一个交通灯,它在绿色、黄色和红色之间循环,当你按下空格键时,它会立即变成绿色。我让所有的东西都在运行,但我不能把自动收报机调整成不同的时间,它总是一个恒定的时间。
(require 2htdp/image)
(require 2htdp/universe)
;; =================
;; Constants:
(define WIDTH 600)
(define HEIGHT 350)
(define MTS (empty-scene WIDTH HEIGHT))
(define RAD 50)
(define WIDTH_2 (/ WIDTH 2))
(define CTR-Y (/ HEIGHT 2))
;; =================
;; Functions:
;; trafficLightNext Tests
(check-expect (trafficLightNext "red") "green")
(check-expect (trafficLightNext "yellow") "red")
(check-expect (trafficLightNext "green") "yellow")
;; Traffic Light -> Boolean
;; Find the current-state of a Traffic Light (red, yellow or green)
(define (isRed? current-state)
(string=? "red" current-state))
(define (isYellow? current-state)
(string=? "yellow" current-state))
(define (isGreen? current-state)
(string=? "green" current-state))
;; Traffic Light -> Traffic Light
;; Finds the next state for the Traffic Light
(define (trafficLightNext current-state)
(cond
[(isRed? current-state) "green"]
[(isYellow? current-state) "red"]
[(isGreen? current-state) "yellow"]))
;; Render Tests
(check-expect (bulb "red" "red") (circle RAD "solid" "red"))
(check-expect (bulb "green" "green") (circle RAD "solid" "green"))
(check-expect (bulb "yellow" "red") (circle RAD "outline" "red"))
(define (light=? current-state color)
(string=? current-state color))
;; Traffic Light -> Image
;; Renders the the light
(define (bulb on c)
(if (light=? on c) (circle RAD "solid" c) (circle RAD "outline" c)))
;; Traffic Light -> Image
;; Takes a Traffic Light places the image on the scene
(define (trafficLightRender current-state)
(place-image
(bulb current-state "red")
WIDTH_2
52
(place-image
(bulb current-state "yellow")
WIDTH_2
CTR-Y
(place-image
(bulb current-state "green")
WIDTH_2
298
MTS))))
;; TrafficLight -> TrafficLight
;; Traffic Light changes every second
(define (traffic-light-simulation initial-state)
(big-bang initial-state (on-tick trafficLightNext 1) (to-draw trafficLightRender) (on-key ambulance)))
;; Key -> TrafficLight
;; Changes light to green everytime key is touched
(define (ambulance initial-state key)
(cond [(key=? key " ") "green"]
(else initial-state)))
(check-expect (ambulance "yellow" " ") "green")
(check-expect (ambulance "red" " ") "green")
(check-expect (ambulance "yellow" "d") "yellow")发布于 2014-02-04 15:44:03
由于这看起来像是学校的作业,我不会给你一个完整的解决方案,只有线索。
如果big-bang的on-tick clause的rate-expr是一个接受当前状态作为输入的函数,情况会更简单,但事实并非如此,因此您需要一种(函数式)方法。
一种可能是使你的世界状态变得更复杂:不只是当前的灯光,它可以是灯光加上倒计时值。在每个节拍中,您不会立即更改灯光,而是从状态的计数器中减去(减去1)。当倒计时达到0时,您可以更改灯光并将倒计时重新初始化为依赖于新灯光的值。主要的更改是在trafficLightNext函数和测试中,但程序的其余部分也必须修改,因为状态不同。
https://stackoverflow.com/questions/21541815
复制相似问题