wasm4fun_input/gamepad.rs
1// Copyright Claudio Mattera 2022.
2//
3// Distributed under the MIT License or the Apache 2.0 License at your option.
4// See the accompanying files License-MIT.txt and License-Apache-2.0.txt, or
5// online at
6// https://opensource.org/licenses/MIT
7// https://opensource.org/licenses/Apache-2.0
8
9use wasm4fun_core::{
10 BUTTON_1, BUTTON_2, BUTTON_DOWN, BUTTON_LEFT, BUTTON_RIGHT, BUTTON_UP, GAMEPAD1, GAMEPAD2,
11 GAMEPAD3, GAMEPAD4,
12};
13
14/// A gamepad
15///
16/// Gamepads have 6 buttons: X (confirm), Z (cancel), Left, Right, Up and Down.
17/// Multiple buttons can be pressed at the same time.
18pub struct GamePad(u8);
19
20impl GamePad {
21 /// Open a system gamepad
22 ///
23 /// # Panics
24 ///
25 /// This function panic if `index` is larger than 4.
26 pub fn open(index: usize) -> &'static Self {
27 match index {
28 1 => unsafe { &*(GAMEPAD1 as *const Self) },
29 2 => unsafe { &*(GAMEPAD2 as *const Self) },
30 3 => unsafe { &*(GAMEPAD3 as *const Self) },
31 4 => unsafe { &*(GAMEPAD4 as *const Self) },
32 _ => panic!("Invalid gamepad"),
33 }
34 }
35
36 /// Access the X button
37 pub fn x(&self) -> bool {
38 self.0 & BUTTON_1 != 0
39 }
40
41 /// Access the Z button
42 pub fn z(&self) -> bool {
43 self.0 & BUTTON_2 != 0
44 }
45
46 /// Access the D-pad Left button
47 pub fn left(&self) -> bool {
48 self.0 & BUTTON_LEFT != 0
49 }
50
51 /// Access the D-pad Right button
52 pub fn right(&self) -> bool {
53 self.0 & BUTTON_RIGHT != 0
54 }
55
56 /// Access the D-pad Up button
57 pub fn up(&self) -> bool {
58 self.0 & BUTTON_UP != 0
59 }
60
61 /// Access the D-pad Down button
62 pub fn down(&self) -> bool {
63 self.0 & BUTTON_DOWN != 0
64 }
65}