git @ Cat's Eye Technologies Cosmos-Boulders / master src / cosmos-boulders / hardware.js
master

Tree @master (Download .tar.gz)

hardware.js @masterraw · history · blame

// SPDX-FileCopyrightText: In 2019, Chris Pressey, the original author of this work, placed it into the public domain.
// SPDX-License-Identifier: Unlicense
// For more information, please refer to <https://unlicense.org/>


/* --[ Virtual Hardware ]-------------------------------------------------------- */


const Hardware = function() {
    this.init = function(config) {
        this.screen = {};
        this.screen.canvas = config.canvas;
        this.screen.ctx = this.screen.canvas.getContext("2d");
        this.onCoinInserted = config.onCoinInserted;

        this.leftPressed = false;
        this.rightPressed = false;
        this.thrustPressed = false;
        this.firePressed = false;
        this.startPressed = false;

        this.attachListeners(this.screen.canvas);

        config.onSetup(this);

        const $this = this;
        const animator = function() {
            config.onFrameReady($this);
            requestAnimationFrame(animator);
        };
        requestAnimationFrame(animator);
    };

    this.keyMap = {
        '1': 'startPressed',
        'Control': 'firePressed',
        'ArrowLeft': 'leftPressed',
        'ArrowUp': 'thrustPressed',
        'ArrowRight': 'rightPressed',
        49: 'startPressed',
        17: 'firePressed',
        37: 'leftPressed',
        38: 'thrustPressed',
        39: 'rightPressed'
    };

    this.attachListeners = function(element) {
        const $this = this;
        element.addEventListener('keydown', function(e) {
            const keyId = e.key || e.keyCode;
            if (keyId === 'ArrowDown' || keyId === 40) {
                e.cancelBubble = true;
                e.preventDefault();
            }
            const u = $this.keyMap[keyId];
            if (u !== undefined) {
                $this[u] = true;
                e.cancelBubble = true;
                e.preventDefault();
            }
        }, true);
        element.addEventListener('keyup', function(e) {
            const keyId = e.key || e.keyCode;
            const u = $this.keyMap[keyId];
            if (u !== undefined) {
                $this[u] = false;
                e.cancelBubble = true;
                e.preventDefault();
            }
            if (keyId === '5' || keyId === 53) {
                $this.onCoinInserted($this);
            }
        }, true);
    };
};

export { Hardware };