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

Tree @master (Download .tar.gz)

collision.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 { updatePlayer } from './player.js';
import { updateBoulder } from './boulder.js';
import { updateMissile } from './missile.js';


/* --[ Collision ]-------------------------------------------------------- */


// Returns an array of 3 items: new Player, new List of Missiles, new List of Boulders.
function detectCollisions(player, missiles, boulders) {
    return boulders.reduce(function(accum, boulder) {
        if (boulder.get("mode") == 'GONE') {
            return accum;
        } else if (boulder.get("mode") == 'MOVING') {
            const player = accum[0];
            const missiles = accum[1];
            const boulders = accum[2];
            /* 1. Check collision with player */
            if (player.get("mode") === 'PLAYING' &&
                Math.abs(player.get("x") - boulder.get("x")) < 10 &&
                Math.abs(player.get("y") + 5 - boulder.get("y")) < 10) {
                return [
                    updatePlayer(player, { type: 'EXPLODE' }),
                    missiles,
                    boulders.push(updateBoulder(boulder, { 'type': 'EXPLODE' }))
                ];
            }
            /* 2. Check collision with any missile */
            const missileCollisionResult = missiles.reduce(function(accum, missile) {
                const player = accum[0];
                const boulder = accum[1];
                const missiles = accum[2];
                if (Math.abs(missile.get("x") - boulder.get("x")) < 10 &&
                    Math.abs(missile.get("y") - boulder.get("y")) < 10) {
                    return [
                        updatePlayer(player, { type: 'SCORE_POINTS' }),
                        updateBoulder(boulder, { type: 'EXPLODE' }),
                        missiles.push(updateMissile(missile, { 'type': 'EXPLODE' }))
                    ];
                } else {
                    return [player, boulder, missiles.push(missile)];
                }
            }, [player, boulder, Immutable.List()]);
            return [missileCollisionResult[0], missileCollisionResult[2], boulders.push(missileCollisionResult[1])];
        } else {
            return [accum[0], accum[1], accum[2].push(boulder)];
        }
    }, [player, missiles, Immutable.List()]);
}

export { detectCollisions };