;; **************************************** ;; * Csu 211 : 2/11/2008 ;; * Lecture #14 Code ;; * List abbreviations and Start of the "Worm" Game ;; **************************************** ;; List Abbreviations ;; * * * * * * * * * * * * * (define list1 (cons 1 (cons 2 (cons 3 (cons 4 empty))))) (define list2 (list 1 2 3 4)) (define list3 '(1 2 3 4)) (check-expect list1 list2) (check-expect list2 list3) (check-expect list1 list3) ;; Abbr. for accessors ;; * * * * * * * * * * * * * (check-expect (first list1) 1) (check-expect (rest list1) '(2 3 4)) ;; (second lst) => (first (rest lst)) (check-expect (second list1) 2) ;; (third lst) => (first (rest (rest lst))) (check-expect (third list1) 3) ;; (fourth lst) => (first (rest (rest (rest lst)))) (check-expect (fourth list1) 4) ;; Local bindings/definitions ;; * * * * * * * * * * * * * (define (f x) (* x x 5)) (define (r lst) (rest lst)) (define (list2string lst) (cond [(empty? lst) ""] [else (local ((define r (list2string (rest lst))) (define f (first lst)) (define f-str (cond [(string? f) f] [(number? f) (number->string f)] [else (error 'list2string "Un-convertable type")]))) (string-append f-str r))])) (check-expect (f 3) 45) (check-expect (r list1) '(2 3 4)) (check-expect (list2string (cons "Test: " list1)) "Test: 1234") (generate-report) ;; * Worm/Snake Game ;; **************************************** ;; ** LOP is either ;; -- empty ;; -- (cons Posn LOP) ;; ** Snake is a *non-empty* LOP ;; ** Dir is a Symbol that is either ;; 'up, 'down, 'left, or 'right ;; ** Food is a Posn ;; ** World is : (make-world Snake Dir Food) (define-struct world (s d f)) (define a-snake (list (make-posn 200 200) (make-posn 220 200) (make-posn 240 200) (make-posn 260 200))) (define a-food (make-posn 100 100)) (define a-world (make-world a-snake 'up a-food)) (define EMPTY (empty-scene 400 400)) (define GRID 20) ;; draw-snake: Snake -> Scene ;; Draw a Snake (with a black head) into a Scene (define (draw-snake snk) (local ((define p (first snk))) (place-image (circle (- (/ GRID 2) 2) 'solid 'black) (posn-x p) (posn-y p) (draw-snk snk)))) ;; draw-snk: Snake -> Scene ;; Draw a snake into a scene (no head...) (define (draw-snk snk) (cond [(empty? snk) EMPTY] [(cons? snk) (local ((define p (first snk))) (place-image (circle (/ GRID 2) 'solid 'red) (posn-x p) (posn-y p) (draw-snk (rest snk))))])) (draw-snake a-snake)