(require 2htdp/image) (require 2htdp/universe) ;; replacing my horsecart image with a rectangle of the same size (define horsecart (rectangle 237 146 "solid" "gray")) (define SCENE-WIDTH 500) (define SCENE-HEIGHT 300) (define BACKGROUND (empty-scene SCENE-WIDTH SCENE-HEIGHT)) (define HC-WIDTH (image-width horsecart)) (define HC-HEIGHT (image-height horsecart)) (define HALF-HC-WIDTH (quotient HC-WIDTH 2)) (define HALF-HC-HEIGHT (quotient HC-HEIGHT 2)) (define HC-AT-LEFT ;; xpos when hc at left edge (- 0 HALF-HC-WIDTH)) (define HC-AT-RIGHT ;; xpos when hc at right edge (+ SCENE-WIDTH HALF-HC-WIDTH)) ;; Data definition (define-struct hc (xpos direction)) ;; A World is (make-hc Number Direction) ;; interp: a world-state is a (make-hc x dir) where x is the ;; x coordinate (in pixels) of the center of the horsecart, ;; and dir is the direction that the horsecart is moving in ;; A Direction is one of: ;; - 'left ;; - 'right ;; some worlds... (define w1 (make-hc 100 'left)) (define w2 (make-hc 300 'right)) (define w3 (make-hc -120 'left)) ;; past the left edge (define w4 (make-hc 620 'right)) ;; past the right edge ;; Template #;(define (world-temp a-world) (... (hc-xpos a-world) ... (hc-direction a-world) ...)) ;; draw-hc : World -> Image ;; Given current world curr-hc, produce image of horsecart on scene (define (draw-hc curr-hc) (place-image horsecart (hc-xpos curr-hc) (- SCENE-HEIGHT HALF-HC-HEIGHT) BACKGROUND)) (check-expect (draw-hc w1) (place-image horsecart 100 (- SCENE-HEIGHT HALF-HC-HEIGHT) BACKGROUND)) ;; next-hc : World -> World ;; Given current world curr-hc, produce next world ;; - If moving left: ;; if at left edge, change direction to right ;; otherwise, shift 5 pixels to left ;; - If moving right: ;; if at right edge, change direction to left ;; otherwise, shift 5 pixels to right (define (next-hc curr-hc) (cond [(symbol=? (hc-direction curr-hc) 'left) ;; moving left... (cond [(< (hc-xpos curr-hc) HC-AT-LEFT) ;; if past left edge (make-hc (hc-xpos curr-hc) 'right)] ;; ...then turn right [else ;; otherwise, move 5 pixels to left & keep moving left (make-hc (- (hc-xpos curr-hc) 5) 'left)])] [(symbol=? (hc-direction curr-hc) 'right) (cond [(> (hc-xpos curr-hc) HC-AT-RIGHT) ;; if past right edge (make-hc (hc-xpos curr-hc) 'left)] ;; ...then turn left [else ;; otherwise, move 5 pixels to right & keep moving right (make-hc (+ (hc-xpos curr-hc) 5) 'right)])])) (check-expect (next-hc w1) (make-hc 95 'left)) (check-expect (next-hc w2) (make-hc 305 'right)) (check-expect (next-hc w3) (make-hc -120 'right)) (check-expect (next-hc w4) (make-hc 620 'left)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; init-hc is the initial world we pass to big-bang: horsecart ;; starts at the right end of the screen, moving left (define init-hc (make-hc HC-AT-RIGHT 'left)) (big-bang init-hc (on-tick next-hc) (to-draw draw-hc)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;