Skip to content

Instantly share code, notes, and snippets.

@kamath
Last active February 19, 2018 20:15
Show Gist options
  • Select an option

  • Save kamath/fec474e28b74a28dc3d2348941bcb98f to your computer and use it in GitHub Desktop.

Select an option

Save kamath/fec474e28b74a28dc3d2348941bcb98f to your computer and use it in GitHub Desktop.
#|--- DATA DEFINITIONS ---|#
;;A Ball is a (make-ball Number Number Number Number)
(define-struct ball (x y vx vy))
; - where the first Number is the ball's x-coordinate
; - the second Number is the ball's y-coordinate
; - the third Number is the ball's x-velocity
; - the fourth Number is the ball's y-velocity
#|--- CONSTANTS ---|#
(define WIDTH 200)
(define HEIGHT 200)
(define BALL-COLOR 'blue)
(define BALL-RADIUS 6)
(define BALL-SPEED 4)
(define BRICK-COLOR 'red)
(define BRICK-WIDTH 30)
(define BRICK-HEIGHT 10)
(define BRICK-PADDING 10)
(define ROWS 3)
(define COLUMNS 5)
(define PADDLE-COLOR 'purple)
(define PADDLE-WIDTH 40)
(define PADDLE-HEIGHT BRICK-HEIGHT)
(define PADDLE-Y (- HEIGHT (/ PADDLE-HEIGHT 2)))
(define PADDLE-SPEED 5)
(define INITIAL-BALL (make-ball (/ WIDTH 2)
(- HEIGHT PADDLE-HEIGHT (/ BALL-RADIUS 2))
BALL-SPEED 0))
#|--- FUNCTIONS ---|#
;; speed: Ball -> Number
;; compute the speed of the ball
(check-expect (speed INITIAL-BALL) 4)
(define (speed ball)
(sqrt (+ (sqr (ball-vx ball))
(sqr (ball-vy ball)))))
;;new-x-velocity : Ball Number -> Number
;;Produces the new x velocity of a ball that launched off a paddle with this x-coordinate
(define (new-x-velocity ball x)
(inexact->exact
(* .95
(/ (- (ball-x ball) x) (+ (/ PADDLE-WIDTH 2) BALL-RADIUS))
(speed ball))))
(check-expect (new-x-velocity INITIAL-BALL 100) 0)
(check-expect (new-x-velocity (make-ball 60 190 3 4) 100)
(inexact->exact (* 4.75 -40/26)))
;;new-y-velocity : Ball Number -> Number
;;Produces the new y velocity of a ball that launched off a paddle with this x-coordinate
(define (new-y-velocity ball x)
(inexact->exact
(* (- (sqrt (- 1 (sqr (* .95
(/ (- (ball-x ball) x) (+ (/ PADDLE-WIDTH 2) BALL-RADIUS)))))))
(speed ball))))
(check-expect (new-y-velocity INITIAL-BALL 100) -4)
(check-expect (new-y-velocity (make-ball 60 190 3 4) 100)
(inexact->exact (* -5 (sqrt (- 1 (sqr (* .95 -40/26)))))))
;;launch-ball : Ball Number -> Ball
;;Launch ball off paddle with this x-coordinate
(define (launch-ball ball x)
(make-ball (+ (ball-x ball) (new-x-velocity ball x))
(+ (ball-y ball) (new-y-velocity ball x))
(new-x-velocity ball x) (new-y-velocity ball x)))
(check-expect (launch-ball INITIAL-BALL 100)
(make-ball 100 183 0 -4))
(check-expect (launch-ball (make-ball 60 190 3 4) 100)
(make-ball (+ 60 (inexact->exact (* 4.75 -40/26)))
(+ 190 (inexact->exact (* -5 (sqrt (- 1 (sqr (* .95 -40/26)))))))
(inexact->exact (* 4.75 -40/26))
(inexact->exact (* -5 (sqrt (- 1 (sqr (* .95 -40/26))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment