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

Tree @master (Download .tar.gz)

boulder.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/>


import { SCREEN_WIDTH, SCREEN_HEIGHT, countDownToMode, updatePosition } from './utils.js';


/* --[ Boulder objects ]-------------------------------------------------------- */


function makeBoulder(i) {
    return Immutable.Map({
        x: Math.floor(Math.random() * SCREEN_WIDTH),
        y: Math.floor(Math.random() * SCREEN_HEIGHT),
        vx: Math.random() - 1.0,
        vy: Math.random() - 1.0,
        mode: 'APPEARING',  // APPEARING | MOVING | EXPLODING | GONE
        timer: 60
    });
}


function makeBoulders() {
    const boulders = [];
    for (let i = 0; i < 8; i++) {
        boulders.push(makeBoulder(i));
    }
    return Immutable.List(boulders);
}


// Reducer that takes a Boulder and an Action and returns a new Boulder.
// Action must be one of: STEP | EXPLODE
function updateBoulder(boulder, action) {
    if (action.type === 'STEP') {
        if (boulder.get("mode") === 'APPEARING') {
            return countDownToMode(boulder, 'MOVING');
        } else if (boulder.get("mode") === 'MOVING') {
            return updatePosition(boulder);
        } else if (boulder.get("mode") === 'EXPLODING') {
            return countDownToMode(boulder, 'GONE');
        } else {
            return boulder;
        }
    } else if (action.type === 'EXPLODE') {
        if (boulder.get("mode") === 'MOVING') {
            return boulder.set("mode", 'EXPLODING').set("timer", 50);
        } else {
            return boulder;
        }
    }
    throw new Error("Unhandled action: " + action.type);
}


export { makeBoulders, updateBoulder };