;; 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 20.6.1) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
; Worked exercise 20.6.1
(require installed-teachpacks/picturing-programs)

; Model: a posn indicating the location of the dot

(define WIDTH 300)
(define HEIGHT 300)
(define BACKGROUND (empty-scene WIDTH HEIGHT))
(define DOT (circle 3 "solid" "blue"))

; Draw handler
; show-picture : posn -> image
(check-expect (show-picture (make-posn 15 12))
              (place-image DOT 15 12 BACKGROUND))
(check-expect (show-picture (make-posn 27 149))
              (place-image DOT 27 149 BACKGROUND))

(define (show-picture where)
  ; where             a posn         (make-posn 27 149)
  ; (posn-x where)    a number (x)   27
  ; (posn-y where)    a number (y)   149
  ; DOT               a fixed image
  ; BACKGROUND        a fixed image
  ; should be         an image       (place-image DOT 27 149 BACKGROUND)
  (place-image DOT 
               (posn-x where) (posn-y where)
               BACKGROUND)
  )
  
; Key handler
; handle-key : posn key -> posn
(check-expect (handle-key (make-posn 12 19) "e")
              (make-posn 12 19))
(check-expect (handle-key (make-posn 12 19) "left")
              (make-posn 11 19))
(check-expect (handle-key (make-posn 12 19) "right")
              (make-posn 13 19))
(check-expect (handle-key (make-posn 12 19) "up")
              (make-posn 12 18))
(check-expect (handle-key (make-posn 12 19) "down")
              (make-posn 12 20))

(define (handle-key where key)
  ; where          a posn
  ; key            a key (i.e. a string)
  ; (posn-x where) a number (x)
  ; (posn-y where) a number (y)
  (cond [(key=? key "up")
         (make-posn (posn-x where) (- (posn-y where) 1))]
        [(key=? key "down")
         (make-posn (posn-x where) (+ (posn-y where) 1))]
        [(key=? key "left")
         (make-posn (- (posn-x where) 1) (posn-y where))]
        [(key=? key "right")
         (make-posn (+ (posn-x where) 1) (posn-y where))]
        [else    where]
        ))


; Alternate definition, assuming you've done exercise 20.5.4:
;(define (handle-key where key)
;  ; where          a posn
;  ; key            a key (i.e. a string)
;  ; (posn-x where) a number (x)
;  ; (posn-y where) a number (y)
;  (cond [(key=? key "up")
;         (add-posns where (make-posn 0 -1))]
;        [(key=? key "down")
;         (add-posns where (make-posn 0 1))]
;        [(key=? key "left")
;         (add-posns where (make-posn -1 0))]
;        [(key=? key "right")
;         (add-posns where (make-posn 1 0))]
;        [else    where]
;        ))


(big-bang (make-posn (/ WIDTH 2) (/ HEIGHT 2))
          (on-draw show-picture)
          (on-key handle-key))