您可以帮我添加一种方法,让每个灯具有不同的定时器长度。我正在做一个世界状态/大爆炸程序,它会创建一个在绿色,黄色和红色之间循环的交通信号灯,如果你碰到空格键,它会立即变为绿色。我已经把所有东西都运行了,但是我无法将自动收报机调整为不同,它始终是一个恒定的时间。
(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")
答案 0 :(得分:0)
由于这看起来像是一项学校作业,我不会给你一个完整的解决方案,只有潜在客户。
如果rate-expr
big-bang
的{{1}}是以当前状态为输入的函数,那会更容易,但事实并非如此,所以你需要一个(这种方式。
一种可能性是让你的世界状态变得更复杂:不仅仅是当前的光,它可能是光加上倒计时值。在每个刻度线处,您不会立即更改灯光,而是递减(从中减去1)状态的计数器。当倒计时达到0时,您可以更改灯光并将倒计时重新初始化为取决于新灯光的值。
主要的变化是trafficLightNext
函数和测试,但是程序的其余部分也必须修改,因为状态不同。