// 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 { makeGame, updateGame } from './game.js';
/* --[ InputContext objects ]-------------------------------------------------------- */
function makeInputContext() {
return Immutable.Map({
game: makeGame(),
leftPressed: false,
rightPressed: false,
thrustPressed: false,
firePressed: false
});
}
// Reducer that takes an InputContext and an Action and returns a new InputContext.
// Action must be one of: FRAME_READY | COIN_INSERTED
function updateInputContext(inputContext, action) {
if (typeof inputContext === 'undefined') return makeInputContext();
const game = inputContext.get("game");
if (action.type === 'FRAME_READY') {
const leftPressed = inputContext.get("leftPressed");
const rightPressed = inputContext.get("rightPressed");
const thrustPressed = inputContext.get("thrustPressed");
const firePressed = inputContext.get("firePressed");
const startPressed = inputContext.get("startPressed");
const game2 = (action.leftPressed !== leftPressed ||
action.rightPressed !== rightPressed ||
action.thrustPressed !== thrustPressed ||
action.firePressed !== firePressed ||
action.startPressed !== startPressed) ?
updateGame(game, {
type: "CONTROLS_CHANGED",
leftPressed: action.leftPressed,
rightPressed: action.rightPressed,
thrustPressed: action.thrustPressed,
firePressed: action.firePressed,
startPressed: action.startPressed,
prev: {
leftPressed: leftPressed,
rightPressed: rightPressed,
thrustPressed: thrustPressed,
firePressed: firePressed,
startPressed: startPressed
}
}) : game;
const game3 = updateGame(game2, { type: "FRAME_READY" });
return inputContext.set("game", game3)
.set("leftPressed", action.leftPressed)
.set("rightPressed", action.rightPressed)
.set("thrustPressed", action.thrustPressed)
.set("firePressed", action.firePressed)
.set("startPressed", action.startPressed);
} else if (action.type === 'COIN_INSERTED') {
return inputContext.set("game", updateGame(game, action));
}
throw new Error("Unhandled action: " + action.type);
}
export { updateInputContext };