An animation of a traffic light

PROBLEM:

Design an animation of a traffic light.Your program should show a traffic light that is red, then green,then yellow, then red etc. For this program, your changing world state data definition should be an enumeration. To make your lights change at a reasonable speed, you can use the
rate option to on-tick. If you say, for example, (on-tick next-color 1)
then big-bang will wait 1 second between calls to next-color.

 

Solution:

(require 2htdp/image)
(require 2htdp/universe)

;; Constant
(define WIDTH 400)
(define HEIGHT 200)
(define CTR-X (/ WIDTH 2))
(define CTR-Y (/ HEIGHT 2))
(define MTS (empty-scene WIDTH HEIGHT))
(define RED .)
(define GREEN .)
(define YELLOW .)

;; Data Definition
;; TrafficLight is one of:
;; -“red”
;; -“green”
;; -“yellow”
;; interp. the color of the traffic light
;; <examples are redundant for enumeration>
#;
(define (fn-for-traffic-light l)
(cond [(string=? l “red”) (…)]
[(string=? l “green”) (…)]
[(string=? l “yellow”) (…)]))
;; Template rule used:
;; -Atomic Distinct: “red”
;; -Atomic Distinct: “green”
;; -Atomic Distinct: “yellow”

;; Function:

;; TrafficLight -> TrafficLight
;; start with (main “red”)
(define (main tl)
(big-bang tl
(on-tick next-color 1)
(to-draw render)))
;; TrafficLight -> TrafficLight
;; produce the next color
(check-expect (next-color “red”) “green”)
(check-expect (next-color “green”) “yellow”)
(check-expect (next-color “yellow”) “red”)
;(define (next-color tl) “red”)
; template used from TrafficLight
(define (next-color l)
(cond [(string=? l “red”) “green”]
[(string=? l “green”) “yellow”]
[(string=? l “yellow”) “red”]))

;; TrafficLight -> Image
;; render the appropriate image for traffic light
(check-expect (render “red”) (place-image RED CTR-X CTR-Y MTS))
(check-expect (render “green”) (place-image GREEN CTR-X CTR-Y MTS))
(check-expect (render “yellow”) (place-image YELLOW CTR-X CTR-Y MTS))
; (define (render tl) MTS)
; template used from TrafficLight
(define (render tl)
(cond [(string=? tl “red”) (place-image RED CTR-X CTR-Y MTS)]
[(string=? tl “green”) (place-image GREEN CTR-X CTR-Y MTS)]
[(string=? tl “yellow”) (place-image YELLOW CTR-X CTR-Y MTS)]))

All the 6 tests passed.

 

Leave a Reply

Your email address will not be published. Required fields are marked *