根据domain analysis中的信息, 我们可以写下
constant (参照 constant)
data definition (参照 changing)
main function(参照 big-bang options)
(require 2htdp/image)
(require 2htdp/universe)
;; =================
;; Constants:
(define WIDTH 600)
(define HEIGHT 400)
(define CTR-Y (/ HEIGHT 2))
(define SPEED 3)
(define MTS (empty-scene WIDTH HEIGHT))
(define CAT-IMG (bitmap/url "https://i.imgur.com/mW5B6Lh.jpg"))
;; =================
;; Data definitions:
(@htdd Cat)
;; Cat is Number
;; interp. x position of the cat in screen coordinates
(define C1 0) ;left edge
(define C2 (/ WIDTH 2)) ;middle
(define C3 WIDTH) ;right edge
#;
(define (fn-for-cat c)
(... c))
(@dd-template-rules atomic-non-distinct) ;; Number
;; =================
(@signature Cat -> Cat)
;; start the world with (main 0)
;;
(define (main c)
(big-bang c ; Cat
(on-tick next-cat) ; Cat -> Cat
(to-draw render-cat) ; Cat -> Image
(on-key handle-key))); Cat -> Cat
接着就可以写next-cat render-cat handle-key这三个“负责人”了
next-cat 负责on-tick, 他负责手上的Cat加工成一只向前走3 pixels的新的Cat
(@signature Cat -> Cat)
;; produce the next cat, by advancing it SPEED pixel(s) to right
(check-expect (next-cat 3) (+ 3 SPEED))
;(define (next-cat c) 0) ;stub
(@template Cat)
(define (next-cat c)
(+ c SPEED))
-
render-cat 负责to-draw, 他负责根据手上的Cat数字所表示的x位置, 把CAT-IMG
放到MTS对应的(x,CTR-Y), 调用到的函数是place-image.
(@signature Cat -> Image)
;; render the cat image at appropriate place on MTS
(check-expect (render-cat 4) (place-image CAT-IMG 4 CTR-Y MTS))
;(define (render c) MTS) ;stub
(@template Cat)
(define (render-cat c)
(place-image CAT-IMG c CTR-Y MTS))
以check-expect (render-cat 4)为例
(place-image CAT-IMG 4 CTR-Y MTS)的
意思是以MTS为背景把CAT-IMG 放到MTS的(4, CTR-Y)这个位置, 值得注意的是, y
轴是从上到下的
-
handle-key 负责handle 检查键盘输入, 一旦他接受到键盘的input,如果检查到
input是否空格键“ ”, 它就会产生一个新的Cat , 就是C1(回到x = 0)
(define C1 0) ;left edge
如果不是空格键的话, 就不发生改变
(@signature Cat -> Cat)
;; when space pressed, reset cat at the strat place
(check-expect (handle-key C2 " ") C1)
(check-expect (handle-key C2 "a") C2)
(@template KeyEvent)
(define (handle-key c ke)
(cond [(key=? ke " ") C1]
[else
c]))
全部写完的话应该是这样一份code javaIsTheBest