;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname 01traffic) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))))) ;; DEMO: modeling a traffic light using 'universe' (not actually used in class) ;; Data description: the state of a traffic ;; light is "red", "yellow" or "green" ;; change-light : light-state -> light-state ;; to compute the next color from the current color (define (change-light color) (cond [(string=? color "green") "yellow"] [(string=? color "yellow") "red"] [(string=? color "red") "green"])) ;; examples (check-expect (change-light "green") "yellow") (check-expect (change-light "yellow") "red") (check-expect (change-light "red") "green") ;; light-image: light-state -> image ;; to render an image of a traffic light (define (light-image color) (cond [(string=? color "red") (stack-bulbs "red" "black" "black")] [(string=? color "yellow") (stack-bulbs "black" "yellow" "black")] [(string=? color "green") (stack-bulbs "black" "black" "green")])) ;; stack-bulbs : color color color -> image ;; purpose: produce an image of three colored circles, each called a "bulb" (define (stack-bulbs top middle bottom) (above (bulb top) BULB-SEPARATOR (bulb middle) BULB-SEPARATOR (bulb bottom))) (define BULB-RADIUS 60) ;; radius of one bulb on the traffic light (define BULB-SEP (/ BULB-RADIUS 2)) ;; distance separating edges of adjacent bulbs ;; bulb : color -> image ;; to produce an image of one bulb in the light, given its color (define (bulb color) (circle BULB-RADIUS "solid" color)) (define BULB-SEPARATOR (square BULB-SEP 0 "white")) ;; a transparent square separating bulbs ;; demo : number -> world ;; given N, launch an animation where the light changes ;; every N seconds (define (demo tick) (big-bang "red" [to-draw light-image] [on-tick change-light tick]))