import {
gameSize,
down,
up,
right,
left,
p1Color,
p2Color,
p1Shot,
p2Shot
} from './constants';
import { GameObject, State } from './interfaces';
const gameObject = (x, y, g, c): GameObject => ({ x, y, g, s: 0, c: c });
const noop = (): void => {};
export const updatePlayer = (
p: GameObject,
key: string,
u,
d,
l,
r
): GameObject => (
key === d
? ((p.x += p.x < gameSize - 1 ? 1 : 0), (p.g = down))
: key === u
? ((p.x += p.x > 0 ? -1 : 0), (p.g = up))
: noop,
key === r
? ((p.y += p.y < gameSize - 1 ? 1 : 0), (p.g = right))
: key === l
? ((p.y += p.y > 0 ? -1 : 0), (p.g = left))
: noop,
p
);
export const addShot = (player: GameObject): GameObject => ({
x: player.x,
y: player.y,
g: player.g
});
export const addShots = (state: State, key: string): void =>
state.shots.push(
key === p1Shot
? addShot(state.players[0])
: key === p2Shot
? addShot(state.players[1])
: []
);
export const updateShots = (shots: GameObject[]): GameObject[] =>
shots
.filter(s => s.x > 0 && s.x < gameSize - 1 && s.y > 0 && s.y < gameSize)
.map(
s => (
s.g === down
? (s.x += 1)
: s.g === up
? (s.x += -1)
: s.g === right
? (s.y += 1)
: s.g === left
? (s.y += -1)
: () => {},
s
)
);
export const initialState: State = {
players: [
gameObject(1, 1, right, p1Color),
gameObject(gameSize - 2, gameSize - 2, left, p2Color)
],
shots: []
};
export const checkCollisions = (state: State): void =>
state.players.forEach((p, i) => {
const collidingShotIndex = state.shots.findIndex(
s => s.x === p.x && s.y === p.y
);
if (collidingShotIndex > -1) {
if (i === 0) {
state.players[1].s += 1;
} else {
state.players[0].s += 1;
}
state.shots.splice(collidingShotIndex, 1);
}
});