FatCat_Tanks_Challenge/Tank.ts

50 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-12-05 18:52:03 +00:00
export interface ITank {
name: string;
health: number;
attackDelay: number;
}
2023-12-05 19:22:01 +00:00
2023-12-05 18:52:03 +00:00
type BuildTank = (name: string) => ITank;
export const buildTank: BuildTank = (name) => ({
name,
health: 100,
attackDelay: 0,
} as ITank);
2023-12-05 19:16:38 +00:00
type CritMultiplier = (health: number) => number;
const critMultiplier: CritMultiplier = (health) =>
Math.floor(Math.random() * 10) >= 10 - health / 10 ? 1 : 2;
type SetStats = (tank: ITank) => ITank;
const setStats: SetStats = (tank) => ({
...tank,
attackDelay: tank.attackDelay === 0 ? Math.floor(tank.health / 10) : tank.attackDelay - 1,
} as ITank);
type Attack = (_: ITank[], tank: ITank, tIndex: number, tanks: ITank[]) => ITank[];
const attack: Attack = (_acc, tank, _iTank, tanks) => {
2023-12-05 19:22:01 +00:00
// Must refactor this imperative block
2023-12-05 19:16:38 +00:00
if (tank.attackDelay === 0) {
const target = tanks[Math.floor(Math.random() * tanks.length)];
const attackDamage = critMultiplier(tank.health) * tank.health / 100;
target.health -= attackDamage;
};
return tanks.map(setStats);
};
type IsLive = (tank: ITank) => boolean;
const isLive: IsLive = (tank) => tank.health >= 0;
type Attacks = (tanks: ITank[]) => ITank[];
const attacksRound: Attacks = (tanks) =>
tanks
.reduce(attack, tanks)
.filter(isLive);
type Battle = (remainingTanks: ITank[]) => ITank;
export const battleItOut: Battle = (remainingTanks: ITank[]) =>
remainingTanks.length === 1
? remainingTanks[0]
: battleItOut(attacksRound(remainingTanks));