wasm4fun-input 0.1.0

Input primitives and subsystems for WASM-4 fantasy console
Documentation
// Copyright Claudio Mattera 2022.
//
// Distributed under the MIT License or the Apache 2.0 License at your option.
// See the accompanying files License-MIT.txt and License-Apache-2.0.txt, or
// online at
// https://opensource.org/licenses/MIT
// https://opensource.org/licenses/Apache-2.0

use wasm4fun_core::{
    BUTTON_1, BUTTON_2, BUTTON_DOWN, BUTTON_LEFT, BUTTON_RIGHT, BUTTON_UP, GAMEPAD1, GAMEPAD2,
    GAMEPAD3, GAMEPAD4,
};

/// A gamepad
///
/// Gamepads have 6 buttons: X (confirm), Z (cancel), Left, Right, Up and Down.
/// Multiple buttons can be pressed at the same time.
pub struct GamePad(u8);

impl GamePad {
    /// Open a system gamepad
    ///
    /// # Panics
    ///
    /// This function panic if `index` is larger than 4.
    pub fn open(index: usize) -> &'static Self {
        match index {
            1 => unsafe { &*(GAMEPAD1 as *const Self) },
            2 => unsafe { &*(GAMEPAD2 as *const Self) },
            3 => unsafe { &*(GAMEPAD3 as *const Self) },
            4 => unsafe { &*(GAMEPAD4 as *const Self) },
            _ => panic!("Invalid gamepad"),
        }
    }

    /// Access the X button
    pub fn x(&self) -> bool {
        self.0 & BUTTON_1 != 0
    }

    /// Access the Z button
    pub fn z(&self) -> bool {
        self.0 & BUTTON_2 != 0
    }

    /// Access the D-pad Left button
    pub fn left(&self) -> bool {
        self.0 & BUTTON_LEFT != 0
    }

    /// Access the D-pad Right button
    pub fn right(&self) -> bool {
        self.0 & BUTTON_RIGHT != 0
    }

    /// Access the D-pad Up button
    pub fn up(&self) -> bool {
        self.0 & BUTTON_UP != 0
    }

    /// Access the D-pad Down button
    pub fn down(&self) -> bool {
        self.0 & BUTTON_DOWN != 0
    }
}