#lang htdp/bsl (require 2htdp/image) (require 2htdp/universe) ; demo from racket-lang.org, ; but expanded with comments and more key-handling. ; Any key inflates the balloon ; a game-state is: a non-negative integer. ; (It represents the balloon's radius.) ; game-state -> image ; Return an image representing the current game-state. (define (draw-balloon b) (circle b "solid" "red")) ; game-state, key -> game-state ; Return a new game-state based on the existing state, and a keypress. ; (define (balloon-handle-key b k) (+ b (keypress->air k))) ; game-state -> game-state ; Return a new game-state after one tick. ; (define (update-balloon b) (max (- b 1) 1)) ; key -> number ; Return how much air is provided by various keys. ; (define (keypress->air key) (cond [(key=? key "a") 5] [(key=? key "up") 20] [(key=? key "left") 10] [else 3])) (big-bang 50 [on-tick update-balloon] [on-key balloon-handle-key] [to-draw draw-balloon 200 200]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Here is a second simple game, where the the state is a number *and* a color. ;; This purpose illustrates how the game-state can be a struct. ; A throwing-star is: (define-struct spinner (color time)) ; make-spinner: color, non-negative integer -> spinner (define DEGS-PER-TICK 5) ; spinner -> image ; Return an image representing the current game-state. (define (draw-spinner spnr) (rotate (remainder (* DEGS-PER-TICK (spinner-time spnr)) 360) (square 80 "solid" (spinner-color spnr)))) ; spinner, key -> game-state ; Return a new spinner based on the existing state, and a keypress. ; (define (spinner-handle-key spnr k) (make-spinner (cond [(key=? k "r") "red"] [(key=? k "g") "green"] [(key=? k "b") "blue"] [(key=? k "escape") (make-color (random 256) (random 256) (random 256) (+ 50 (random (- 256 50))))] [(key=? k "right") "coral"] [(key=? k "left") "darkSlateBlue"] ; search "keyEvent" in racket documentation, for more special keys. [else (spinner-color spnr)]) (spinner-time spnr))) ; game-state -> game-state ; Return a new game-state after one tick. ; (define (update-spinner spnr) (make-spinner (spinner-color spnr) (add1 (spinner-time spnr)))) ; From (big-bang (make-spinner "black" 0) [on-tick update-spinner] [on-key spinner-handle-key] [to-draw draw-spinner 200 300])