examples: Add game controller test.
[chickadee.git] / examples / game-controller.scm
1 (use-modules (chickadee)
2 (chickadee math vector)
3 (chickadee render font)
4 (chickadee render sprite)
5 (chickadee render texture)
6 (ice-9 match))
7
8 (define controller #f)
9 (define atlas #f)
10 (define button-icons
11 `((dpad-down ,(vec2 110.0 140.0) 7 25)
12 (dpad-right ,(vec2 170.0 210.0) 9 27)
13 (dpad-left ,(vec2 50.0 210.0) 8 26)
14 (dpad-up ,(vec2 110.0 280.0) 6 24)
15 (a ,(vec2 450.0 140.0) 0 18)
16 (b ,(vec2 510.0 210.0) 1 19)
17 (x ,(vec2 390.0 210.0) 2 20)
18 (y ,(vec2 450.0 280.0) 3 21)
19 (back ,(vec2 190.0 330.0) 11 29)
20 (guide ,(vec2 280.0 330.0) 12 30)
21 (start ,(vec2 370.0 330.0) 10 28)
22 (left-stick ,(vec2 110.0 20.0) 13 31)
23 (right-stick ,(vec2 450.0 20.0) 13 31)
24 (left-shoulder ,(vec2 110.0 390.0) 4 22)
25 (right-shoulder ,(vec2 450.0 390.0) 5 23)))
26 (define no-controller-msg "no controller detected :'(")
27 (define no-controller-msg-pos #f)
28 (define controller-name-pos #f)
29
30 (define (center-text text)
31 (/ (- 640.0 (font-line-width (default-font) text)) 2.0))
32
33 (define (load)
34 (set! no-controller-msg-pos (vec2 (center-text no-controller-msg) 240.0))
35 (set! atlas (split-texture (load-image "images/controller-buttons.png")
36 80 80)))
37
38 (define (controller-add new-controller)
39 (set! controller (or controller new-controller))
40 (set! controller-name-pos
41 (vec2 (center-text (controller-name controller)) 440.0)))
42
43 ;; FIXME: I couldn't think of a decent way to display the analog
44 ;; left/right trigger buttons, so they are omitted.
45 (define (draw alpha)
46 (if controller
47 (begin
48 (draw-text (controller-name controller) controller-name-pos)
49 (for-each (match-lambda
50 (((and (or 'left-stick 'right-stick) button)
51 p released pressed)
52 (let ((pressed? (controller-button-pressed? controller
53 button))
54 (x (controller-axis controller
55 (if (eq? button 'left-stick)
56 'left-x
57 'right-x)))
58 (y (controller-axis controller
59 (if (eq? button 'left-stick)
60 'left-y
61 'right-y))))
62 (draw-sprite (texture-atlas-ref atlas released)
63 p)
64 (when (or pressed? (not (zero? x)) (not (zero? y)))
65 (draw-sprite (texture-atlas-ref atlas pressed)
66 (vec2+ p (vec2 (* x 16.0) (* y -16.0)))))))
67 ((button p released pressed)
68 (let ((pressed? (controller-button-pressed? controller
69 button)))
70 (draw-sprite (texture-atlas-ref
71 atlas
72 (if pressed? pressed released))
73 p))))
74 button-icons))
75 (draw-text no-controller-msg no-controller-msg-pos)))
76
77 (run-game #:load load #:draw draw #:controller-add controller-add)