From feb81da471cdf7d86d987c771e40c06f93c3aa10 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Mon, 1 Feb 2021 02:41:03 +0100 Subject: [PATCH] Add prettier configuration --- .eslintrc.js | 46 +- .prettierrc | 6 + .travis.yml | 2 +- .vscode/launch.json | 62 +-- .vscode/settings.json | 7 +- README.md | 1 + index.ts | 59 ++- package.json | 4 +- src/actions.spec.ts | 6 +- src/actions.ts | 45 +- src/algorithms/shortest-path.ts | 28 +- src/algorithms/spanning-tree.ts | 43 +- src/available-command.ts | 482 ++++++++++++--------- src/buildings.ts | 24 +- src/engine.spec.ts | 163 ++++--- src/engine.ts | 530 ++++++++++++++--------- src/enums.ts | 198 +++++---- src/events.spec.ts | 11 +- src/events.ts | 49 ++- src/faction-boards/ambas.spec.ts | 4 +- src/faction-boards/ambas.ts | 6 +- src/faction-boards/baltaks.spec.ts | 8 +- src/faction-boards/baltaks.ts | 10 +- src/faction-boards/bescods.spec.ts | 4 +- src/faction-boards/bescods.ts | 12 +- src/faction-boards/firaks.spec.ts | 11 +- src/faction-boards/firaks.ts | 6 +- src/faction-boards/geodens.spec.ts | 16 +- src/faction-boards/geodens.ts | 4 +- src/faction-boards/gleens.spec.ts | 38 +- src/faction-boards/gleens.ts | 8 +- src/faction-boards/hadsch-hallas.spec.ts | 2 +- src/faction-boards/hadsch-hallas.ts | 12 +- src/faction-boards/index.ts | 6 +- src/faction-boards/itars.spec.ts | 8 +- src/faction-boards/itars.ts | 8 +- src/faction-boards/ivits.spec.ts | 67 +-- src/faction-boards/ivits.ts | 6 +- src/faction-boards/lantids.spec.ts | 44 +- src/faction-boards/lantids.ts | 8 +- src/faction-boards/nevlas.spec.ts | 16 +- src/faction-boards/nevlas.ts | 16 +- src/faction-boards/taklons.spec.ts | 8 +- src/faction-boards/taklons.ts | 4 +- src/faction-boards/terrans.ts | 10 +- src/faction-boards/types.ts | 45 +- src/faction-boards/xenos.ts | 6 +- src/factions.spec.ts | 4 +- src/factions.ts | 32 +- src/federation.spec.ts | 125 +++--- src/federation.ts | 10 +- src/gaia-hex.ts | 24 +- src/map.spec.ts | 68 +-- src/map.ts | 148 +++++-- src/planets.ts | 16 +- src/player-data.spec.ts | 14 +- src/player-data.ts | 208 ++++++--- src/player.spec.ts | 18 +- src/player.ts | 465 +++++++++++++------- src/research-tracks.ts | 40 +- src/research.spec.ts | 38 +- src/reward.spec.ts | 29 +- src/reward.ts | 34 +- src/sector.ts | 10 +- src/tiles/boosters.spec.ts | 19 +- src/tiles/boosters.ts | 2 +- src/tiles/federations.spec.ts | 7 +- src/tiles/federations.ts | 4 +- src/tiles/index.ts | 4 +- src/tiles/scoring.ts | 12 +- src/tiles/techs.spec.ts | 28 +- src/tiles/techs.ts | 3 +- src/utils.ts | 2 +- tsconfig.json | 22 +- tslint.json | 4 +- wrapper.ts | 65 +-- 76 files changed, 2192 insertions(+), 1422 deletions(-) create mode 100644 .prettierrc diff --git a/.eslintrc.js b/.eslintrc.js index 35592005..6c9f2769 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,35 +1,31 @@ module.exports = { root: true, env: { - node: true + node: true, }, parserOptions: { - ecmaVersion: 2020 + ecmaVersion: 2020, }, - parser: '@typescript-eslint/parser', - plugins: [ - '@typescript-eslint', - ], + parser: "@typescript-eslint/parser", + plugins: ["@typescript-eslint"], extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/eslint-recommended', - 'plugin:@typescript-eslint/recommended', + "eslint:recommended", + "plugin:@typescript-eslint/eslint-recommended", + "plugin:@typescript-eslint/recommended", ], rules: { - 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', - 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', - semi: ['error', 'always'], - '@typescript-eslint/no-non-null-assertion': 'off', - '@typescript-eslint/consistent-type-assertions': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-empty-function': 'off', - '@typescript-eslint/no-unused-vars': 'off', - '@typescript-eslint/explicit-function-return-type': 'off', - '@typescript-eslint/no-use-before-define': 'off', - '@typescript-eslint/no-namespace': 'off', - 'no-inner-declarations': 'off', - 'no-return-assign': 'off', - 'no-fallthrough': 'off', - quotes: 'off' - } + "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", + "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off", + "@typescript-eslint/no-non-null-assertion": "off", + "@typescript-eslint/consistent-type-assertions": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/no-unused-vars": "off", + "@typescript-eslint/explicit-function-return-type": "off", + "@typescript-eslint/no-use-before-define": "off", + "@typescript-eslint/no-namespace": "off", + "no-inner-declarations": "off", + "no-return-assign": "off", + "no-fallthrough": "off", + }, }; diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000..8b1f2819 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,6 @@ +{ + "tabWidth": 2, + "useTabs": false, + "printWidth": 120, + "trailingComma": "es5" +} diff --git a/.travis.yml b/.travis.yml index 66c56734..fbbe7375 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,4 @@ language: node_js node_js: -- node + - node diff --git a/.vscode/launch.json b/.vscode/launch.json index ee57d109..13ca10c9 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,32 +1,32 @@ { - "version": "0.2.0", - "configurations": [ - { - "name": "Native typescript", - "type": "node", - "request": "launch", - "program": "${workspaceRoot}/node_modules/ts-node/dist/bin.js", - "args": ["server.ts"], - "cwd": "${workspaceRoot}", - "protocol": "inspector" - }, - { - "name": "Current TS File", - "type": "node", - "request": "launch", - "program": "${workspaceRoot}/node_modules/ts-node/dist/bin.js", - "args": ["${relativeFile}"], - "cwd": "${workspaceRoot}", - "protocol": "inspector" - }, - { - "name": "Current TS Test File", - "type": "node", - "request": "launch", - "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha", - "args": ["-r", "ts-node/register", "${relativeFile}"], - "cwd": "${workspaceRoot}", - "protocol": "inspector" - } - ] -} \ No newline at end of file + "version": "0.2.0", + "configurations": [ + { + "name": "Native typescript", + "type": "node", + "request": "launch", + "program": "${workspaceRoot}/node_modules/ts-node/dist/bin.js", + "args": ["server.ts"], + "cwd": "${workspaceRoot}", + "protocol": "inspector" + }, + { + "name": "Current TS File", + "type": "node", + "request": "launch", + "program": "${workspaceRoot}/node_modules/ts-node/dist/bin.js", + "args": ["${relativeFile}"], + "cwd": "${workspaceRoot}", + "protocol": "inspector" + }, + { + "name": "Current TS Test File", + "type": "node", + "request": "launch", + "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha", + "args": ["-r", "ts-node/register", "${relativeFile}"], + "cwd": "${workspaceRoot}", + "protocol": "inspector" + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json index d31eb293..a5aabc7b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,5 @@ { - "editor.tabSize": 2, - "tslint.autoFixOnSave": true -} \ No newline at end of file + "editor.tabSize": 2, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true +} diff --git a/README.md b/README.md index 53586a8c..cc4e3ea3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # gaia-engine + Javascript engine for Gaia Project. ## Demo diff --git a/index.ts b/index.ts index ead733f8..4daa3e1a 100644 --- a/index.ts +++ b/index.ts @@ -2,24 +2,59 @@ import Engine from "./src/engine"; import Player from "./src/player"; import PlayerData from "./src/player-data"; import factions from "./src/factions"; -import Event, {EventSource} from "./src/events"; +import Event, { EventSource } from "./src/events"; import AvailableCommand from "./src/available-command"; import tiles from "./src/tiles"; import Reward from "./src/reward"; -import factionBoards from './src/faction-boards'; -import SpaceMap from './src/map'; -import researchTracks from './src/research-tracks'; +import factionBoards from "./src/faction-boards"; +import SpaceMap from "./src/map"; +import researchTracks from "./src/research-tracks"; -export {Condition, Planet, Resource, Operator, ResearchField, Faction, Command, Building, Booster, Federation, BoardAction} from "./src/enums"; -export {TechTile, AdvTechTile, ScoringTile, FinalTile, TechTilePos, AdvTechTilePos, Phase, Round, Player as PlayerEnum, Expansion} from "./src/enums"; -export {BrainstoneArea} from './src/enums'; -export {GaiaHexData, GaiaHex} from "./src/gaia-hex"; -export {terraformingStepsRequired, planetNames} from './src/planets'; +export { + Condition, + Planet, + Resource, + Operator, + ResearchField, + Faction, + Command, + Building, + Booster, + Federation, + BoardAction, +} from "./src/enums"; +export { + TechTile, + AdvTechTile, + ScoringTile, + FinalTile, + TechTilePos, + AdvTechTilePos, + Phase, + Round, + Player as PlayerEnum, + Expansion, +} from "./src/enums"; +export { BrainstoneArea } from "./src/enums"; +export { GaiaHexData, GaiaHex } from "./src/gaia-hex"; +export { terraformingStepsRequired, planetNames } from "./src/planets"; export { boardActions } from "./src/actions"; export { FactionBoard, factionBoard } from "./src/faction-boards"; -export {roundScorings, finalScorings} from './src/tiles/scoring'; -export {LogEntry, EngineOptions} from './src/engine'; +export { roundScorings, finalScorings } from "./src/tiles/scoring"; +export { LogEntry, EngineOptions } from "./src/engine"; -export { Player, PlayerData, Event, factions, AvailableCommand, tiles, Reward, SpaceMap, researchTracks, factionBoards, EventSource }; +export { + Player, + PlayerData, + Event, + factions, + AvailableCommand, + tiles, + Reward, + SpaceMap, + researchTracks, + factionBoards, + EventSource, +}; export default Engine; diff --git a/package.json b/package.json index 11f15474..7bf04868 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,9 @@ "build": "npm run clean && tsc", "clean": "rm -Rf dist", "lint": "eslint . --ext .ts", - "test": "npm run lint && npm run just-test", + "prettier": "npx --yes -- prettier --write .", + "prettier-check": "npx --yes -- prettier --check .", + "test": "npm run lint && npm run pretier-check && npm run just-test", "just-test": "mocha -r ts-node/register src/**/*.spec.ts src/*.spec.ts" }, "contributors": [ diff --git a/src/actions.spec.ts b/src/actions.spec.ts index 141017f5..f4bbf6bd 100644 --- a/src/actions.spec.ts +++ b/src/actions.spec.ts @@ -1,6 +1,6 @@ -import { expect } from 'chai'; -import Engine from './engine'; -import { Player } from './enums'; +import { expect } from "chai"; +import Engine from "./engine"; +import { Player } from "./enums"; const parseMoves = Engine.parseMoves; diff --git a/src/actions.ts b/src/actions.ts index f3da39fb..7fb19b54 100644 --- a/src/actions.ts +++ b/src/actions.ts @@ -1,7 +1,7 @@ -import { BoardAction } from './enums'; +import { BoardAction } from "./enums"; // QIC to extend range is already included in the distance calculation -export const freeActions = [ +export const freeActions = [ { cost: "4pw", income: "1q" }, { cost: "3pw", income: "1o" }, { cost: "1q", income: "1o" }, @@ -9,45 +9,42 @@ export const freeActions = [ { cost: "1pw", income: "1c" }, { cost: "1k", income: "1c" }, { cost: "1o", income: "1c" }, - { cost: "1o", income: "1t" } + { cost: "1o", income: "1t" }, ]; export const freeActionsHadschHallas = [ { cost: "4c", income: "1q" }, { cost: "3c", income: "1o" }, - { cost: "4c", income: "1k" } + { cost: "4c", income: "1k" }, ]; export const freeActionsTerrans = [ { cost: "4tg", income: "1q" }, { cost: "3tg", income: "1o" }, { cost: "4tg", income: "1k" }, - { cost: "1tg", income: "1c" } + { cost: "1tg", income: "1c" }, ]; -export const freeActionsItars = [ - { cost: "4tg", income: "tech" } -]; +export const freeActionsItars = [{ cost: "4tg", income: "tech" }]; -export const freeActionsNevlas = [ - { cost: "1t-a3", income: "1k" } -]; +export const freeActionsNevlas = [{ cost: "1t-a3", income: "1k" }]; export const freeActionsNevlasPI = [ { cost: "4pw", income: "1o,1c" }, - { cost: "6pw", income: "2o" } + { cost: "6pw", income: "2o" }, ]; -export const freeActionsBaltaks = [ - { cost: "1gf", income: "1q" } -]; +export const freeActionsBaltaks = [{ cost: "1gf", income: "1q" }]; /** Temporarily increase range of all ships */ -export const freeActionsMoveShip = [{ - cost: "1q", income: "range+2" -}]; +export const freeActionsMoveShip = [ + { + cost: "1q", + income: "range+2", + }, +]; -export const boardActions = { +export const boardActions = { [BoardAction.Power1]: { cost: "7pw", income: ["3k"] }, [BoardAction.Power2]: { cost: "5pw", income: ["2step"] }, [BoardAction.Power3]: { cost: "4pw", income: ["2o"] }, @@ -57,9 +54,9 @@ export const boardActions = { [BoardAction.Power7]: { cost: "3pw", income: ["2t"] }, [BoardAction.Qic1]: { cost: "4q", income: ["tech"] }, [BoardAction.Qic2]: { cost: "3q", income: [">fed"] }, - [BoardAction.Qic3]: { cost: "2q", income: ["3vp", "pt > vp"]}, - [BoardAction.ShipPower1]: { cost: "5pw", income: ["range+3"]}, - [BoardAction.ShipPower2]: { cost: "3pw", income: ["q"]}, - [BoardAction.ShipPower3]: { cost: "3pw", income: ["move-all"]}, - [BoardAction.ShipQic1]: { cost: "1q", income: ["ship"]} + [BoardAction.Qic3]: { cost: "2q", income: ["3vp", "pt > vp"] }, + [BoardAction.ShipPower1]: { cost: "5pw", income: ["range+3"] }, + [BoardAction.ShipPower2]: { cost: "3pw", income: ["q"] }, + [BoardAction.ShipPower3]: { cost: "3pw", income: ["move-all"] }, + [BoardAction.ShipQic1]: { cost: "1q", income: ["ship"] }, }; diff --git a/src/algorithms/shortest-path.ts b/src/algorithms/shortest-path.ts index c86c83fa..b9d2f80c 100644 --- a/src/algorithms/shortest-path.ts +++ b/src/algorithms/shortest-path.ts @@ -1,15 +1,20 @@ -import {Hex, Grid} from "hexagrid"; +import { Hex, Grid } from "hexagrid"; import { flatten, difference } from "lodash"; -export default function shortestPath(starts: Hex[], dests: Hex[], grid: Grid, costOf = (hex: Hex) => 1): {path: Hex[]; cost: number} { +export default function shortestPath( + starts: Hex[], + dests: Hex[], + grid: Grid, + costOf = (hex: Hex) => 1 +): { path: Hex[]; cost: number } { const destSet: Set> = new Set(dests); - const pathTo: Map, {path: Hex[]; cost: number}> = new Map(); + const pathTo: Map, { path: Hex[]; cost: number }> = new Map(); for (const start of starts) { - pathTo.set(start, {path: [start], cost: costOf(start)}); + pathTo.set(start, { path: [start], cost: costOf(start) }); if (destSet.has(start)) { - return {path: [start], cost: costOf(start)}; + return { path: [start], cost: costOf(start) }; } } @@ -17,7 +22,7 @@ export default function shortestPath(starts: Hex[], dests: Hex[], grid: let toExpandNext = []; let minToDest = grid.size + 1; - let bestPath: {path: Hex[]; cost: number}; + let bestPath: { path: Hex[]; cost: number }; let minDistance = 0; const distanceToNextDest = (path: Hex[], excl: Hex[]) => { @@ -29,10 +34,10 @@ export default function shortestPath(starts: Hex[], dests: Hex[], grid: path = bestPath ? difference(path, bestPath.path.slice(1, -1)) : path; - return Math.min(...flatten(path.map(x => targets.map(y => grid.distance(x, y))))); + return Math.min(...flatten(path.map((x) => targets.map((y) => grid.distance(x, y))))); }; - const isBetter = (path: {path: Hex[]; cost: number}) => { + const isBetter = (path: { path: Hex[]; cost: number }) => { if (path.cost < minToDest) { return true; } @@ -60,7 +65,7 @@ export default function shortestPath(starts: Hex[], dests: Hex[], grid: const extendedPath = { cost: curPath.cost + costOf(neighbour), - path: [...curPath.path, neighbour] + path: [...curPath.path, neighbour], }; pathTo.set(neighbour, extendedPath); @@ -69,7 +74,10 @@ export default function shortestPath(starts: Hex[], dests: Hex[], grid: if (destSet.has(neighbour) && isBetter(extendedPath)) { minToDest = extendedPath.cost; bestPath = extendedPath; - minDistance = distanceToNextDest(extendedPath.path.slice(1, -1), [extendedPath.path[0], extendedPath.path[extendedPath.path.length - 1]]); + minDistance = distanceToNextDest(extendedPath.path.slice(1, -1), [ + extendedPath.path[0], + extendedPath.path[extendedPath.path.length - 1], + ]); } } } diff --git a/src/algorithms/spanning-tree.ts b/src/algorithms/spanning-tree.ts index 21d32850..bec6d05e 100644 --- a/src/algorithms/spanning-tree.ts +++ b/src/algorithms/spanning-tree.ts @@ -1,11 +1,17 @@ import { inRange, minBy, maxBy, uniq, difference, sortBy } from "lodash"; import { Grid, Hex } from "hexagrid"; -import shortestPath from './shortest-path'; -import {sumBy} from 'lodash'; -import assert from 'assert'; +import shortestPath from "./shortest-path"; +import { sumBy } from "lodash"; +import assert from "assert"; type algorithms = "exhaustive" | "heuristic"; -export default function spanningTree(destGroups: Hex[][], grid: Grid, maxAdditional, algorithm: algorithms, costOf: (hex: Hex) => number) { +export default function spanningTree( + destGroups: Hex[][], + grid: Grid, + maxAdditional, + algorithm: algorithms, + costOf: (hex: Hex) => number +) { // Choose which algorithm to use. // By the way, the heuristic always gives the best solution if destGroups.length <= 3 (maybe even with 4?) // The breadthwidth algorithm always gives the best solution anyway but is slower @@ -17,12 +23,17 @@ export default function spanningTree(destGroups: Hex[][], grid: Grid, maxA } } -function spanningTreeWithHeuristic(destGroups: Hex[][], grid: Grid>, maxAdditional = -1, costOf = (hex: Hex) => 1): {path: Hex[]; cost: number} | undefined { +function spanningTreeWithHeuristic( + destGroups: Hex[][], + grid: Grid>, + maxAdditional = -1, + costOf = (hex: Hex) => 1 +): { path: Hex[]; cost: number } | undefined { const destHexes: Hex[] = [].concat(...destGroups); const destHexesSet = new Set(destHexes); if (destGroups.length <= 1) { - return {path: destHexes, cost: sumBy(destHexes, costOf)}; + return { path: destHexes, cost: sumBy(destHexes, costOf) }; } const destGroupsMap: Map, Hex[]> = new Map(); @@ -32,14 +43,22 @@ function spanningTreeWithHeuristic(destGroups: Hex[][], grid: Grid> } } - const [minQ, maxQ] = [minBy(destHexes, 'q').q, maxBy(destHexes, 'q').q]; - const [minR, maxR] = [minBy(destHexes, 'r').r, maxBy(destHexes, 'r').r]; - const [minS, maxS] = [minBy(destHexes, 's').s, maxBy(destHexes, 's').s]; + const [minQ, maxQ] = [minBy(destHexes, "q").q, maxBy(destHexes, "q").q]; + const [minR, maxR] = [minBy(destHexes, "r").r, maxBy(destHexes, "r").r]; + const [minS, maxS] = [minBy(destHexes, "s").s, maxBy(destHexes, "s").s]; const startingPoints: Array> = []; if (destGroups.length > 2) { // We pick all the hexes that are in the middle of the federation buildings, and try to create a network from them - startingPoints.push(...[...grid.values()].filter(hex => !destHexesSet.has(hex) && inRange(hex.q, minQ + 1, maxQ) && inRange(hex.r, minR + 1, maxR) && inRange(hex.s, minS + 1, maxS))); + startingPoints.push( + ...[...grid.values()].filter( + (hex) => + !destHexesSet.has(hex) && + inRange(hex.q, minQ + 1, maxQ) && + inRange(hex.r, minR + 1, maxR) && + inRange(hex.s, minS + 1, maxS) + ) + ); } for (const group of destGroups) { startingPoints.push(group[0]); @@ -63,7 +82,7 @@ function spanningTreeWithHeuristic(destGroups: Hex[][], grid: Grid> do { const hexSet = new Set>(hexes); - const path = shortestPath(hexes, toReach, grid, hex => hexSet.has(hex) ? 0 : costOf(hex)); + const path = shortestPath(hexes, toReach, grid, (hex) => (hexSet.has(hex) ? 0 : costOf(hex))); if (!path) { hexes = undefined; @@ -82,7 +101,7 @@ function spanningTreeWithHeuristic(destGroups: Hex[][], grid: Grid> } if (bestSolution) { - return {path: bestSolution, cost: minScore}; + return { path: bestSolution, cost: minScore }; } } diff --git a/src/available-command.ts b/src/available-command.ts index ec590fe7..409f6a51 100644 --- a/src/available-command.ts +++ b/src/available-command.ts @@ -1,12 +1,28 @@ -import { Command, Faction, Building, Planet, Booster, Resource, Player, Operator, BoardAction, ResearchField, TechTilePos, AdvTechTilePos, Phase, SubPhase, Expansion } from './enums'; -import Engine from './engine'; -import { range, difference } from 'lodash'; -import factions from './factions'; -import { upgradedBuildings } from './buildings'; -import Reward from './reward'; -import { boardActions, freeActions, freeActionsTerrans, freeActionsItars, freeActionsMoveShip } from './actions'; -import * as researchTracks from './research-tracks'; -import { isAdvanced } from './tiles/techs'; +import { + Command, + Faction, + Building, + Planet, + Booster, + Resource, + Player, + Operator, + BoardAction, + ResearchField, + TechTilePos, + AdvTechTilePos, + Phase, + SubPhase, + Expansion, +} from "./enums"; +import Engine from "./engine"; +import { range, difference } from "lodash"; +import factions from "./factions"; +import { upgradedBuildings } from "./buildings"; +import Reward from "./reward"; +import { boardActions, freeActions, freeActionsTerrans, freeActionsItars, freeActionsMoveShip } from "./actions"; +import * as researchTracks from "./research-tracks"; +import { isAdvanced } from "./tiles/techs"; const ISOLATED_DISTANCE = 3; const UPGRADE_RESEARCH_COST = "4k"; @@ -28,22 +44,38 @@ export function generate(engine: Engine, subPhase: SubPhase = null, data?: any): } switch (subPhase) { - case SubPhase.ChooseTechTile: return possibleTechTiles(engine, player); - case SubPhase.CoverTechTile: return possibleCoverTechTiles(engine, player); - case SubPhase.UpgradeResearch: return possibleResearchAreas(engine, player, "", data); - case SubPhase.PlaceLostPlanet: return possibleSpaceLostPlanet(engine, player); - case SubPhase.ChooseFederationTile: return possibleFederationTiles(engine, player, "pool"); - case SubPhase.RescoreFederationTile: return possibleFederationTiles(engine, player, "player"); - case SubPhase.BuildMine: return possibleMineBuildings(engine, player, false); - case SubPhase.BuildMineOrGaiaFormer: return possibleMineBuildings(engine, player, true, data); - case SubPhase.DeliverTrade: return [{name: Command.DeliverTrade, player, data}]; - case SubPhase.SpaceStation: return possibleSpaceStations(engine, player); - case SubPhase.PISwap: return possiblePISwaps(engine, player); - case SubPhase.DowngradeLab: return possibleLabDowngrades(engine, player); - case SubPhase.BrainStone: return [{name: Command.BrainStone, player, data}]; - case SubPhase.PlaceShip: return possibleShips(engine, player); - case SubPhase.PickRewards: return [{name: Command.PickReward, player, data: {rewards: engine.player(player).data.toPick.rewards}}]; - case SubPhase.MoveShip: return possibleShipMovements(engine, player); + case SubPhase.ChooseTechTile: + return possibleTechTiles(engine, player); + case SubPhase.CoverTechTile: + return possibleCoverTechTiles(engine, player); + case SubPhase.UpgradeResearch: + return possibleResearchAreas(engine, player, "", data); + case SubPhase.PlaceLostPlanet: + return possibleSpaceLostPlanet(engine, player); + case SubPhase.ChooseFederationTile: + return possibleFederationTiles(engine, player, "pool"); + case SubPhase.RescoreFederationTile: + return possibleFederationTiles(engine, player, "player"); + case SubPhase.BuildMine: + return possibleMineBuildings(engine, player, false); + case SubPhase.BuildMineOrGaiaFormer: + return possibleMineBuildings(engine, player, true, data); + case SubPhase.DeliverTrade: + return [{ name: Command.DeliverTrade, player, data }]; + case SubPhase.SpaceStation: + return possibleSpaceStations(engine, player); + case SubPhase.PISwap: + return possiblePISwaps(engine, player); + case SubPhase.DowngradeLab: + return possibleLabDowngrades(engine, player); + case SubPhase.BrainStone: + return [{ name: Command.BrainStone, player, data }]; + case SubPhase.PlaceShip: + return possibleShips(engine, player); + case SubPhase.PickRewards: + return [{ name: Command.PickReward, player, data: { rewards: engine.player(player).data.toPick.rewards } }]; + case SubPhase.MoveShip: + return possibleShipMovements(engine, player); case SubPhase.BeforeMove: { return [ ...possibleBuildings(engine, player), @@ -52,29 +84,36 @@ export function generate(engine: Engine, subPhase: SubPhase = null, data?: any): ...possibleBoardActions(engine, player), ...possibleSpecialActions(engine, player), ...possibleFreeActions(engine, player), - ...possibleRoundBoosters(engine, player) + ...possibleRoundBoosters(engine, player), ]; } - case SubPhase.AfterMove: return [...possibleFreeActions(engine, player), {name: Command.EndTurn, player}]; - default: break; + case SubPhase.AfterMove: + return [...possibleFreeActions(engine, player), { name: Command.EndTurn, player }]; + default: + break; } switch (engine.phase) { - case Phase.SetupInit: return [{ name: Command.Init }]; - case Phase.SetupBoard: return [{name: Command.RotateSectors, player}]; - case Phase.SetupShip: return possibleShips(engine, player); - case Phase.SetupFaction: return [ - { - name: Command.ChooseFaction, - player, - data: difference( - Object.values(Faction), - engine.setup.map(f => f), - engine.setup.map(f => factions.opposite(f)) - ) - } - ]; - case Phase.SetupAuction: return possibleBids(engine, player); + case Phase.SetupInit: + return [{ name: Command.Init }]; + case Phase.SetupBoard: + return [{ name: Command.RotateSectors, player }]; + case Phase.SetupShip: + return possibleShips(engine, player); + case Phase.SetupFaction: + return [ + { + name: Command.ChooseFaction, + player, + data: difference( + Object.values(Faction), + engine.setup.map((f) => f), + engine.setup.map((f) => factions.opposite(f)) + ), + }, + ]; + case Phase.SetupAuction: + return possibleBids(engine, player); case Phase.SetupBuilding: { const planet = engine.player(player).planet; const buildings = []; @@ -82,22 +121,23 @@ export function generate(engine: Engine, subPhase: SubPhase = null, data?: any): for (const hex of engine.map.toJSON()) { if (hex.data.planet === planet && !hex.data.building) { buildings.push({ - building: - engine.player(player).faction !== Faction.Ivits - ? Building.Mine - : Building.PlanetaryInstitute, + building: engine.player(player).faction !== Faction.Ivits ? Building.Mine : Building.PlanetaryInstitute, coordinates: hex.toString(), - cost: '~' + cost: "~", }); } } - return [{name: Command.Build, player, data: { buildings }}]; + return [{ name: Command.Build, player, data: { buildings } }]; } - case Phase.SetupBooster: return possibleRoundBoosters(engine, player); - case Phase.RoundIncome: return possibleIncomes(engine, player); - case Phase.RoundGaia: return possibleGaiaFreeActions(engine, player); - case Phase.RoundLeech: return possibleLeech(engine, player); + case Phase.SetupBooster: + return possibleRoundBoosters(engine, player); + case Phase.RoundIncome: + return possibleIncomes(engine, player); + case Phase.RoundGaia: + return possibleGaiaFreeActions(engine, player); + case Phase.RoundLeech: + return possibleLeech(engine, player); } return []; @@ -106,7 +146,7 @@ export function generate(engine: Engine, subPhase: SubPhase = null, data?: any): export function possibleBuildings(engine: Engine, player: Player) { const map = engine.map; const pl = engine.player(player); - const {data} = pl; + const { data } = pl; const buildings = []; for (const hex of engine.map.toJSON()) { @@ -152,44 +192,52 @@ export function possibleBuildings(engine: Engine, player: Player) { const upgraded = upgradedBuildings(building, engine.player(player).faction); for (const upgrade of upgraded) { - const {cost, possible} = engine.player(player).canBuild(hex.data.planet, upgrade, {isolated, existingBuilding: building}); + const { cost, possible } = engine + .player(player) + .canBuild(hex.data.planet, upgrade, { isolated, existingBuilding: building }); if (possible) { buildings.push({ building: upgrade, cost: Reward.toString(cost), coordinates: hex.toString(), - upgrade: true + upgrade: true, }); } } } else if (pl.canOccupy(hex)) { // planet without building // Check if the range is enough to access the planet - const distance = Math.min(...data.occupied.filter(loc => loc.isRangeStartingPoint(player)).map(loc => map.distance(hex, loc))); - const qicNeeded = Math.max(Math.ceil( (distance - data.range - data.temporaryRange) / QIC_RANGE_UPGRADE), 0); + const distance = Math.min( + ...data.occupied.filter((loc) => loc.isRangeStartingPoint(player)).map((loc) => map.distance(hex, loc)) + ); + const qicNeeded = Math.max(Math.ceil((distance - data.range - data.temporaryRange) / QIC_RANGE_UPGRADE), 0); const building = hex.data.planet === Planet.Transdim ? Building.GaiaFormer : Building.Mine; // No need for terra forming if already occupied by another faction - const planet = (hex.occupied() ? pl.planet : hex.data.planet); - const {possible, cost, steps} = pl.canBuild(planet, building, {addedCost: [new Reward(qicNeeded, Resource.Qic)]}); + const planet = hex.occupied() ? pl.planet : hex.data.planet; + const { possible, cost, steps } = pl.canBuild(planet, building, { + addedCost: [new Reward(qicNeeded, Resource.Qic)], + }); if (possible) { - buildings.push({ - building, - coordinates: hex.toString(), - cost: Reward.toString(cost), - steps + buildings.push({ + building, + coordinates: hex.toString(), + cost: Reward.toString(cost), + steps, }); } } } // end for hex if (buildings.length > 0) { - return [{ - name: Command.Build, - player, - data: { buildings } - }]; + return [ + { + name: Command.Build, + player, + data: { buildings }, + }, + ]; } return []; @@ -200,21 +248,26 @@ export function possibleShips(engine: Engine, player: Player) { const pl = engine.player(player); for (const hex of pl.data.occupied) { - if (hex.buildingOf(player) === Building.Mine || pl.faction === Faction.Ivits && hex.buildingOf(player) === Building.PlanetaryInstitute) { + if ( + hex.buildingOf(player) === Building.Mine || + (pl.faction === Faction.Ivits && hex.buildingOf(player) === Building.PlanetaryInstitute) + ) { // Lantids need their PI before getting a ship from a shared mine if (!hex.isMainOccupier(player) && !pl.data.hasPlanetaryInstitute()) { continue; } - locations.push({coordinates: hex.toString()}); + locations.push({ coordinates: hex.toString() }); } } if (locations.length > 0) { - return [{ - name: Command.PlaceShip, - player, - data: {locations} - }]; + return [ + { + name: Command.PlaceShip, + player, + data: { locations }, + }, + ]; } else { pl.data.shipsToPlace = 0; } @@ -233,19 +286,22 @@ export function possibleShipMovements(engine: Engine, player: Player) { const maxRange = pl.shipMovementRange + (pl.data.spendablePowerTokens() ? 1 : 0); const costs = {}; - range(baseRange + 1, maxRange + 1).forEach(val => { + range(baseRange + 1, maxRange + 1).forEach((val) => { costs[val] = new Reward(val - baseRange, Resource.ChargePower).toString(); }); - const commands: AvailableCommand[] = [...possibleFreeActions(engine, player, {moveShips: true}), { - name: Command.MoveShip, - player, - data: { - ships: pl.data.movableShipLocations.map(loc => ({coordinates: loc})), - range: maxRange, - costs - } - }]; + const commands: AvailableCommand[] = [ + ...possibleFreeActions(engine, player, { moveShips: true }), + { + name: Command.MoveShip, + player, + data: { + ships: pl.data.movableShipLocations.map((loc) => ({ coordinates: loc })), + range: maxRange, + costs, + }, + }, + ]; return commands; } @@ -253,7 +309,7 @@ export function possibleShipMovements(engine: Engine, player: Player) { export function possibleSpaceStations(engine: Engine, player: Player) { const map = engine.map; const pl = engine.player(player); - const {data} = pl; + const { data } = pl; const buildings = []; for (const hex of map.toJSON()) { @@ -262,36 +318,45 @@ export function possibleSpaceStations(engine: Engine, player: Player) { continue; } - const distance = Math.min(...data.occupied.filter(loc => loc.isRangeStartingPoint(player)).map(loc => map.distance(hex, loc))); - const qicNeeded = Math.max(Math.ceil( (distance - data.range - data.temporaryRange) / QIC_RANGE_UPGRADE), 0); - const {possible, cost, steps} = pl.canBuild(pl.planet, Building.SpaceStation, {addedCost: [new Reward(qicNeeded, Resource.Qic)]}); + const distance = Math.min( + ...data.occupied.filter((loc) => loc.isRangeStartingPoint(player)).map((loc) => map.distance(hex, loc)) + ); + const qicNeeded = Math.max(Math.ceil((distance - data.range - data.temporaryRange) / QIC_RANGE_UPGRADE), 0); + const { possible, cost, steps } = pl.canBuild(pl.planet, Building.SpaceStation, { + addedCost: [new Reward(qicNeeded, Resource.Qic)], + }); if (possible) { buildings.push({ building: Building.SpaceStation, coordinates: hex.toString(), - cost: Reward.toString(cost) + cost: Reward.toString(cost), }); } } if (buildings.length > 0) { - return [{name: Command.Build, player, data: { buildings }}]; + return [{ name: Command.Build, player, data: { buildings } }]; } return []; } -export function possibleMineBuildings(engine: Engine, player: Player, acceptGaiaFormer: boolean, data?: {buildings?: [{building: Building; coordinates: string; cost: string; steps?: number}]}) { +export function possibleMineBuildings( + engine: Engine, + player: Player, + acceptGaiaFormer: boolean, + data?: { buildings?: [{ building: Building; coordinates: string; cost: string; steps?: number }] } +) { if (data && data.buildings) { - return [{name: Command.Build, player, data}]; + return [{ name: Command.Build, player, data }]; } const commands = []; const [buildingCommand] = possibleBuildings(engine, player); if (buildingCommand) { - buildingCommand.data.buildings = buildingCommand.data.buildings.filter(bld => { + buildingCommand.data.buildings = buildingCommand.data.buildings.filter((bld) => { // If it's a gaia-former upgradable to a mine, it doesn't count if (bld.upgrade) { return false; @@ -317,19 +382,23 @@ export function possibleSpecialActions(engine: Engine, player: Player) { for (const event of pl.events[Operator.Activate]) { if (!event.activated) { - if (event.rewards[0].type === Resource.DowngradeLab && (pl.data.buildings[Building.ResearchLab] === 0 || pl.data.buildings[Building.TradingStation] >= pl.maxBuildings(Building.TradingStation))) { + if ( + event.rewards[0].type === Resource.DowngradeLab && + (pl.data.buildings[Building.ResearchLab] === 0 || + pl.data.buildings[Building.TradingStation] >= pl.maxBuildings(Building.TradingStation)) + ) { continue; } if (event.rewards[0].type === Resource.PISwap && pl.data.buildings[Building.Mine] === 0) { continue; } // If the action decreases rewards, the player must have them - if (!pl.canPay(Reward.negative(event.rewards.filter(rw => rw.count < 0)))) { + if (!pl.canPay(Reward.negative(event.rewards.filter((rw) => rw.count < 0)))) { continue; } specialacts.push({ income: event.action().rewards, // Reward.toString(event.rewards), - spec: event.spec + spec: event.spec, }); } } @@ -338,7 +407,7 @@ export function possibleSpecialActions(engine: Engine, player: Player) { commands.push({ name: Command.Special, player, - data: { specialacts } + data: { specialacts }, }); } @@ -348,28 +417,32 @@ export function possibleSpecialActions(engine: Engine, player: Player) { export function possibleBoardActions(engine: Engine, player: Player) { const commands = []; - let poweracts = BoardAction.values(Expansion.All).filter(pwract => engine.boardActions[pwract] && engine.player(player).canPay(Reward.parse(boardActions[pwract].cost))); + let poweracts = BoardAction.values(Expansion.All).filter( + (pwract) => engine.boardActions[pwract] && engine.player(player).canPay(Reward.parse(boardActions[pwract].cost)) + ); // Prevent using the rescore action if no federation token if (engine.player(player).data.tiles.federations.length === 0) { - poweracts = poweracts.filter(act => act !== BoardAction.Qic2); + poweracts = poweracts.filter((act) => act !== BoardAction.Qic2); } if (poweracts.length > 0) { commands.push({ name: Command.Action, player, - data: { poweracts: poweracts.map(act => ({ - name: act, - cost: boardActions[act].cost, - income: boardActions[act].income - }))} + data: { + poweracts: poweracts.map((act) => ({ + name: act, + cost: boardActions[act].cost, + income: boardActions[act].income, + })), + }, }); } return commands; } -export function possibleFreeActions(engine: Engine, player: Player, data?: {moveShips: boolean}) { +export function possibleFreeActions(engine: Engine, player: Player, data?: { moveShips: boolean }) { // free action - spend const pl = engine.player(player); const acts = []; @@ -386,7 +459,11 @@ export function possibleFreeActions(engine: Engine, player: Player, data?: {move pool = freeActionsTerrans; } else if (pl.canGaiaItars()) { pool = freeActionsItars; - commands.push({name: Command.Decline, player, data: {offers: [{offer: Resource.TechTile, cost: new Reward(4, Resource.GainTokenGaiaArea).toString()}]}}); + commands.push({ + name: Command.Decline, + player, + data: { offers: [{ offer: Resource.TechTile, cost: new Reward(4, Resource.GainTokenGaiaArea).toString() }] }, + }); } burnDisabled = true; @@ -406,13 +483,17 @@ export function possibleFreeActions(engine: Engine, player: Player, data?: {move if (data && data.moveShips) { maxPay = Math.min(maxPay, 1); } - if ( maxPay > 0 ) { - acts.push({cost: freeAction.cost, income: freeAction.income, range: maxPay > 1 ? range(1, maxPay + 1) : undefined}); + if (maxPay > 0) { + acts.push({ + cost: freeAction.cost, + income: freeAction.income, + range: maxPay > 1 ? range(1, maxPay + 1) : undefined, + }); } } if (acts.length > 0) { - commands.push({name: Command.Spend, player, data: { acts }}); + commands.push({ name: Command.Spend, player, data: { acts } }); } // free action - burn @@ -420,7 +501,7 @@ export function possibleFreeActions(engine: Engine, player: Player, data?: {move commands.push({ name: Command.BurnPower, player, - data: range(1, engine.player(player).data.burnablePower() + 1) + data: range(1, engine.player(player).data.burnablePower() + 1), }); } @@ -429,24 +510,26 @@ export function possibleFreeActions(engine: Engine, player: Player, data?: {move export function possibleLabDowngrades(engine: Engine, player: Player) { const pl = engine.player(player); - const spots = pl.data.occupied.filter(hex => hex.buildingOf(player) === Building.ResearchLab); + const spots = pl.data.occupied.filter((hex) => hex.buildingOf(player) === Building.ResearchLab); if (!spots) { return []; } - return [{ - name: Command.Build, - player, - data: { - buildings: spots.map(hex => ({ - building: Building.TradingStation, - coordinates: hex.toString(), - cost: "~", - downgrade: true - })) - } - }] as AvailableCommand[]; + return [ + { + name: Command.Build, + player, + data: { + buildings: spots.map((hex) => ({ + building: Building.TradingStation, + coordinates: hex.toString(), + cost: "~", + downgrade: true, + })), + }, + }, + ] as AvailableCommand[]; } export function possibleResearchAreas(engine: Engine, player: Player, cost?: string, data?: any) { @@ -460,12 +543,12 @@ export function possibleResearchAreas(engine: Engine, player: Player, cost?: str if (data) { if (data.bescods) { - const minArea = Math.min(...fields.map(field => pl.data.research[field])); - avFields = fields.filter(field => pl.data.research[field] === minArea); + const minArea = Math.min(...fields.map((field) => pl.data.research[field])); + avFields = fields.filter((field) => pl.data.research[field] === minArea); } else if (data.pos) { avFields = [data.pos]; } else if (data.zero) { - avFields = fields.filter(field => pl.data.research[field] === 0); + avFields = fields.filter((field) => pl.data.research[field] === 0); } } @@ -473,7 +556,10 @@ export function possibleResearchAreas(engine: Engine, player: Player, cost?: str // end of the track reached const destTile = pl.data.research[field] + 1; - if (destTile === researchTracks.lastTile(field) && engine.players.some(pla => pla.data.research[field] === destTile)) { + if ( + destTile === researchTracks.lastTile(field) && + engine.players.some((pla) => pla.data.research[field] === destTile) + ) { continue; } @@ -484,9 +570,8 @@ export function possibleResearchAreas(engine: Engine, player: Player, cost?: str tracks.push({ field, to: destTile, - cost + cost, }); - } } @@ -494,7 +579,7 @@ export function possibleResearchAreas(engine: Engine, player: Player, cost?: str commands.push({ name: Command.UpgradeResearch, player, - data: { tracks } + data: { tracks }, }); } @@ -503,7 +588,7 @@ export function possibleResearchAreas(engine: Engine, player: Player, cost?: str commands.push({ name: Command.Decline, player, - data: { offers: [{offer: Command.UpgradeResearch}] } + data: { offers: [{ offer: Command.UpgradeResearch }] }, }); } return commands; @@ -519,8 +604,8 @@ export function possibleSpaceLostPlanet(engine: Engine, player: Player) { if (hex.data.planet !== Planet.Empty || hex.data.federations || hex.data.building) { continue; } - const distance = Math.min(...data.occupied.map(loc => engine.map.distance(hex, loc))); - const qicNeeded = Math.max(Math.ceil( (distance - data.range) / QIC_RANGE_UPGRADE), 0); + const distance = Math.min(...data.occupied.map((loc) => engine.map.distance(hex, loc))); + const qicNeeded = Math.max(Math.ceil((distance - data.range) / QIC_RANGE_UPGRADE), 0); if (qicNeeded > data.qics) { continue; @@ -529,7 +614,7 @@ export function possibleSpaceLostPlanet(engine: Engine, player: Player) { spaces.push({ building: Building.Mine, coordinates: hex.toString(), - cost: qicNeeded > 0 ? new Reward(qicNeeded, Resource.Qic).toString() : "~" + cost: qicNeeded > 0 ? new Reward(qicNeeded, Resource.Qic).toString() : "~", }); } @@ -537,7 +622,7 @@ export function possibleSpaceLostPlanet(engine: Engine, player: Player) { commands.push({ name: Command.PlaceLostPlanet, player, - data: { spaces } + data: { spaces }, }); } @@ -546,22 +631,22 @@ export function possibleSpaceLostPlanet(engine: Engine, player: Player) { export function possibleRoundBoosters(engine: Engine, player: Player) { const commands = []; - const boosters = engine.isLastRound ? [] : Booster.values(Expansion.All).filter(booster => engine.tiles.boosters[booster]); + const boosters = engine.isLastRound + ? [] + : Booster.values(Expansion.All).filter((booster) => engine.tiles.boosters[booster]); - commands.push( - { - name: engine.phase === Phase.SetupBooster ? Command.ChooseRoundBooster : Command.Pass, - player, - data: { boosters } - } - ); + commands.push({ + name: engine.phase === Phase.SetupBooster ? Command.ChooseRoundBooster : Command.Pass, + player, + data: { boosters }, + }); return commands; } export function possibleFederations(engine: Engine, player: Player) { const commands = []; - const possibleTiles = Object.keys(engine.tiles.federations).filter(key => engine.tiles.federations[key] > 0); + const possibleTiles = Object.keys(engine.tiles.federations).filter((key) => engine.tiles.federations[key] > 0); if (possibleTiles.length > 0) { if (engine.options.noFedCheck) { @@ -570,8 +655,8 @@ export function possibleFederations(engine: Engine, player: Player) { player, data: { tiles: possibleTiles, - federations: [] - } + federations: [], + }, }); } else { const possibleFeds = engine.player(player).availableFederations(engine.map, engine.options.flexibleFederations); @@ -582,12 +667,15 @@ export function possibleFederations(engine: Engine, player: Player) { player, data: { tiles: possibleTiles, - federations: possibleFeds.map(fed => ({ + federations: possibleFeds.map((fed) => ({ planets: fed.planets, satellites: fed.satellites, - hexes: fed.hexes.map(hex => hex.toString()).sort().join(',') - })) - } + hexes: fed.hexes + .map((hex) => hex.toString()) + .sort() + .join(","), + })), + }, }); } } @@ -606,7 +694,7 @@ export function possibleIncomes(engine: Engine, player: Player) { commands.push({ name: Command.ChooseIncome, player, - data: descs + data: descs, }); } return commands; @@ -628,44 +716,49 @@ export function possibleLeech(engine: Engine, player: Player) { // TODO: Remove first part of test when legacy games are finished. const isTrade = engine.lastLeechSource && engine.lastLeechSource.tradeDelivery === player; - if ( pl.data.leechPossible > 0) { + if (pl.data.leechPossible > 0) { const extraPower = pl.faction === Faction.Taklons && pl.data.hasPlanetaryInstitute() && !isTrade; const maxLeech = pl.maxLeech(); - const offers: Array<{offer: string; cost: string}> = []; + const offers: Array<{ offer: string; cost: string }> = []; if (isTrade) { offers.push({ offer: "1t", - cost: "~" + cost: "~", }); } if (extraPower) { - offers.push({ - offer: `${maxLeech}${Resource.ChargePower},1t`, - cost: new Reward(Math.max(maxLeech - 1, 0), Resource.VictoryPoint).toString() - }, { - offer: `1t,${pl.maxLeech(true)}${Resource.ChargePower}`, - cost: new Reward(Math.max(pl.maxLeech(true) - 1, 0), Resource.VictoryPoint).toString() - }); + offers.push( + { + offer: `${maxLeech}${Resource.ChargePower},1t`, + cost: new Reward(Math.max(maxLeech - 1, 0), Resource.VictoryPoint).toString(), + }, + { + offer: `1t,${pl.maxLeech(true)}${Resource.ChargePower}`, + cost: new Reward(Math.max(pl.maxLeech(true) - 1, 0), Resource.VictoryPoint).toString(), + } + ); } else { offers.push({ offer: `${maxLeech}${Resource.ChargePower}`, - cost: new Reward(Math.max(maxLeech - 1, 0), Resource.VictoryPoint).toString() + cost: new Reward(Math.max(maxLeech - 1, 0), Resource.VictoryPoint).toString(), }); } - [Command.ChargePower, Command.Decline].map(name => commands.push({ - name, - player, - data: { - // Kept for compatibility with older viewer - offer: offers[0].offer, - // Kept for compatibility with older viewer - cost: offers[0].cost, - // new format - offers - } - })); + [Command.ChargePower, Command.Decline].map((name) => + commands.push({ + name, + player, + data: { + // Kept for compatibility with older viewer + offer: offers[0].offer, + // Kept for compatibility with older viewer + cost: offers[0].cost, + // new format + offers, + }, + }) + ); } return commands; @@ -674,11 +767,11 @@ export function possibleLeech(engine: Engine, player: Player) { export function possibleCoverTechTiles(engine: Engine, player: Player) { const commands = []; - const tiles = engine.player(player).data.tiles.techs.filter(tl => tl.enabled && !isAdvanced(tl.pos)); + const tiles = engine.player(player).data.tiles.techs.filter((tl) => tl.enabled && !isAdvanced(tl.pos)); commands.push({ name: Command.ChooseCoverTechTile, player, - data: {tiles} + data: { tiles }, }); return commands; @@ -687,8 +780,8 @@ export function possibleCoverTechTiles(engine: Engine, player: Player) { export function possibleFederationTiles(engine: Engine, player: Player, from: "pool" | "player") { const commands = []; - const possibleTiles = Object.keys(engine.tiles.federations).filter(key => engine.tiles.federations[key] > 0); - const playerTiles = engine.player(player).data.tiles.federations.map(fed => fed.tile); + const possibleTiles = Object.keys(engine.tiles.federations).filter((key) => engine.tiles.federations[key] > 0); + const playerTiles = engine.player(player).data.tiles.federations.map((fed) => fed.tile); commands.push({ name: Command.ChooseFederationTile, @@ -696,8 +789,8 @@ export function possibleFederationTiles(engine: Engine, player: Player, from: "p data: { tiles: from === "player" ? playerTiles : possibleTiles, // Tiles that are rescored just add the rewards, but don't take the token - rescore: from === "player" - } + rescore: from === "player", + }, }); return commands; @@ -710,10 +803,10 @@ export function possibleTechTiles(engine: Engine, player: Player) { // tech tiles that player doesn't already have for (const tilePos of TechTilePos.values(engine.expansions)) { - if (!data.tiles.techs.find(tech => tech.tile === engine.tiles.techs[tilePos].tile)) { + if (!data.tiles.techs.find((tech) => tech.tile === engine.tiles.techs[tilePos].tile)) { tiles.push({ tile: engine.tiles.techs[tilePos].tile, - pos: tilePos + pos: tilePos, }); } } @@ -730,20 +823,20 @@ export function possibleTechTiles(engine: Engine, player: Player) { if (data.research[tilePos.slice("adv-".length)] < 4) { continue; } - if (!data.tiles.techs.some(tech => tech.enabled && !isAdvanced(tech.pos))) { + if (!data.tiles.techs.some((tech) => tech.enabled && !isAdvanced(tech.pos))) { continue; } tiles.push({ tile: engine.tiles.techs[tilePos].tile, - pos: tilePos + pos: tilePos, }); } if (tiles.length > 0) { commands.push({ name: Command.ChooseTechTile, player, - data: { tiles } + data: { tiles }, }); } @@ -768,23 +861,24 @@ export function possiblePISwaps(engine: Engine, player: Player) { commands.push({ name: Command.PISwap, player, - data: { buildings } + data: { buildings }, }); } return commands; } - export function possibleBids(engine: Engine, player: Player) { const commands = []; const bids = []; - for ( const faction of engine.setup) { - const bid = engine.players.find(pl => pl.faction == faction) ? engine.players.find(pl => pl.faction == faction).data.bid : -1; + for (const faction of engine.setup) { + const bid = engine.players.find((pl) => pl.faction == faction) + ? engine.players.find((pl) => pl.faction == faction).data.bid + : -1; bids.push({ faction, - bid: range( bid + 1, bid + 10) + bid: range(bid + 1, bid + 10), }); } @@ -792,7 +886,7 @@ export function possibleBids(engine: Engine, player: Player) { commands.push({ name: Command.Bid, player, - data: { bids } + data: { bids }, }); } diff --git a/src/buildings.ts b/src/buildings.ts index 7145e390..12e3e097 100644 --- a/src/buildings.ts +++ b/src/buildings.ts @@ -2,10 +2,16 @@ import { Building, Faction } from ".."; export function upgradedBuildings(currentBuilding: Building, faction: Faction): Building[] { switch (currentBuilding) { - case Building.GaiaFormer: return [Building.Mine]; - case Building.Mine: return [Building.TradingStation]; - case Building.TradingStation: return faction === Faction.Bescods ? [Building.Academy1, Building.Academy2, Building.ResearchLab] : [Building.PlanetaryInstitute, Building.ResearchLab]; - case Building.ResearchLab: return faction === Faction.Bescods ? [Building.PlanetaryInstitute] : [Building.Academy1, Building.Academy2]; + case Building.GaiaFormer: + return [Building.Mine]; + case Building.Mine: + return [Building.TradingStation]; + case Building.TradingStation: + return faction === Faction.Bescods + ? [Building.Academy1, Building.Academy2, Building.ResearchLab] + : [Building.PlanetaryInstitute, Building.ResearchLab]; + case Building.ResearchLab: + return faction === Faction.Bescods ? [Building.PlanetaryInstitute] : [Building.Academy1, Building.Academy2]; } return []; @@ -13,14 +19,16 @@ export function upgradedBuildings(currentBuilding: Building, faction: Faction): export function stdBuildingValue(building: Building): number { switch (building) { - case Building.Mine: return 1; + case Building.Mine: + return 1; case Building.TradingStation: - case Building.ResearchLab: return 2; + case Building.ResearchLab: + return 2; case Building.PlanetaryInstitute: case Building.Academy1: - case Building.Academy2: return 3; + case Building.Academy2: + return 3; } return 0; } - diff --git a/src/engine.spec.ts b/src/engine.spec.ts index 981c1e5c..f61877c8 100644 --- a/src/engine.spec.ts +++ b/src/engine.spec.ts @@ -1,21 +1,26 @@ import { expect } from "chai"; import Engine from "./engine"; import { AssertionError } from "assert"; -import { Player, Federation, Operator, AdvTechTilePos, Building, Condition, BrainstoneArea, Phase, Command, Faction } from "./enums"; +import { + Player, + Federation, + Operator, + AdvTechTilePos, + Building, + Condition, + BrainstoneArea, + Phase, + Command, + Faction, +} from "./enums"; describe("Engine", () => { it("should throw when trying to build on the wrong place", () => { - const moves = [ - "init 2 randomSeed", - "p1 faction terrans", - "p2 faction xenos", - "p1 build m 0x0", - ]; + const moves = ["init 2 randomSeed", "p1 faction terrans", "p2 faction xenos", "p1 build m 0x0"]; expect(() => new Engine(moves)).to.throw(); }); - it("should export playerToMove in JSON", () => { const moves = parseMoves(` init 2 randomSeed @@ -135,7 +140,8 @@ describe("Engine", () => { }); it("should throw when upgrading without resources", () => { - const engine = new Engine(parseMoves(` + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction terrans p2 faction firaks @@ -149,12 +155,13 @@ describe("Engine", () => { p2 build m 3x-2. p1 build ts -5x0. p2 build ts -1x-1. - `)); + `) + ); expect(() => engine.move("p1 build ts -4x2")).to.throw(); }); - it ("should throw when building out of range", () => { + it("should throw when building out of range", () => { const moves = parseMoves(` init 2 randomSeed p1 faction terrans @@ -171,7 +178,7 @@ describe("Engine", () => { expect(() => engine.move("p1 build -1x0")).to.throw(); }); - it ("should not spend a qic when building a mine nearby", () => { + it("should not spend a qic when building a mine nearby", () => { const moves = parseMoves(` init 2 randomSeed p1 faction terrans @@ -216,7 +223,10 @@ describe("Engine", () => { engine.move("p1 build m -3x1"); - expect(engine.player(Player.Player1).data.qics).to.equal(qicCount, "Building a mine from a gaia former doest NOT need a qic"); + expect(engine.player(Player.Player1).data.qics).to.equal( + qicCount, + "Building a mine from a gaia former doest NOT need a qic" + ); }); it("should allow this 4 player game", () => { @@ -265,24 +275,24 @@ describe("Engine", () => { expect(() => new Engine(moves)).to.not.throw(); }); - it("should handle this full 2 player game", function() { + it("should handle this full 2 player game", function () { this.timeout(10000); - const engine = new Engine(fullGame(), {noFedCheck: true}); + const engine = new Engine(fullGame(), { noFedCheck: true }); expect(engine.player(Player.Player1).data.victoryPoints).to.equal(130); expect(engine.player(Player.Player2).data.victoryPoints).to.equal(124); }); - it ("should be able to load/save state", function() { + it("should be able to load/save state", function () { this.timeout(10000); let state: any = null; - const baseLine = new Engine([], {noFedCheck: true}); + const baseLine = new Engine([], { noFedCheck: true }); const moveList = fullGame(); for (const move of moveList.slice(0, moveList.length - 1)) { baseLine.move(move); if (!state) { - const engine = new Engine([move], {noFedCheck: true}); + const engine = new Engine([move], { noFedCheck: true }); state = JSON.parse(JSON.stringify(engine)); } else { const engine = Engine.fromData(state); @@ -290,21 +300,41 @@ describe("Engine", () => { state = JSON.parse(JSON.stringify(engine)); } - expect(state.players[Player.Player1].data.knowledge).to.equal(baseLine.players[Player.Player1].data.knowledge, "Error loading move " + move); - expect(state.players[Player.Player2].income).to.equal(baseLine.players[Player.Player2].toJSON().income, "Error loading move " + move); - expect(state.players[Player.Player2].events[Operator.Income].length).to.equal(baseLine.players[Player.Player2].events[Operator.Income].length, "Error loading move " + move); - expect(state.players[Player.Player2].data.ores).to.equal(baseLine.players[Player.Player2].data.ores, "Error loading move " + move); + expect(state.players[Player.Player1].data.knowledge).to.equal( + baseLine.players[Player.Player1].data.knowledge, + "Error loading move " + move + ); + expect(state.players[Player.Player2].income).to.equal( + baseLine.players[Player.Player2].toJSON().income, + "Error loading move " + move + ); + expect(state.players[Player.Player2].events[Operator.Income].length).to.equal( + baseLine.players[Player.Player2].events[Operator.Income].length, + "Error loading move " + move + ); + expect(state.players[Player.Player2].data.ores).to.equal( + baseLine.players[Player.Player2].data.ores, + "Error loading move " + move + ); } const endEngine = Engine.fromData(state); - expect(endEngine.player(Player.Player1).data.victoryPoints).to.equal(baseLine.player(Player.Player1).data.victoryPoints); - expect(endEngine.player(Player.Player2).data.victoryPoints).to.equal(baseLine.player(Player.Player2).data.victoryPoints); + expect(endEngine.player(Player.Player1).data.victoryPoints).to.equal( + baseLine.player(Player.Player1).data.victoryPoints + ); + expect(endEngine.player(Player.Player2).data.victoryPoints).to.equal( + baseLine.player(Player.Player2).data.victoryPoints + ); const lastMove = moveList.pop(); endEngine.move(lastMove); baseLine.move(lastMove); - expect(endEngine.player(Player.Player1).data.victoryPoints).to.equal(baseLine.player(Player.Player1).data.victoryPoints); - expect(endEngine.player(Player.Player2).data.victoryPoints).to.equal(baseLine.player(Player.Player2).data.victoryPoints); + expect(endEngine.player(Player.Player1).data.victoryPoints).to.equal( + baseLine.player(Player.Player1).data.victoryPoints + ); + expect(endEngine.player(Player.Player2).data.victoryPoints).to.equal( + baseLine.player(Player.Player2).data.victoryPoints + ); }); it("should be able to load state from an empty game", () => { @@ -458,7 +488,7 @@ describe("Engine", () => { expect(() => new Engine([...moves, "p2 income 1t,1t"])).to.not.throw(); }); - it ("should add a mine to a federation through a nearby satellite", () => { + it("should add a mine to a federation through a nearby satellite", () => { const moves = parseMoves(` init 2 randomSeed p1 faction terrans @@ -495,11 +525,11 @@ describe("Engine", () => { `); const engine = new Engine(moves); const structure = engine.player(Player.Player1).eventConditionCount(Condition.StructureFed); - engine.move('terrans action power2. build m -5x5.'); - expect( engine.player(Player.Player1).eventConditionCount(Condition.StructureFed) ).to.be.equal(structure + 1 ); + engine.move("terrans action power2. build m -5x5."); + expect(engine.player(Player.Player1).eventConditionCount(Condition.StructureFed)).to.be.equal(structure + 1); }); - it ("should give step vps", () => { + it("should give step vps", () => { const moves = parseMoves(` init 2 SGAMBATA p1 faction nevlas @@ -552,13 +582,13 @@ describe("Engine", () => { `); const engine = new Engine(moves); const vps = engine.player(Player.Player1).data.victoryPoints; - engine.move('nevlas action power6. build m -1x3.'); - expect( engine.player(Player.Player1).data.victoryPoints ).to.be.equal(vps + 2 ); - expect( engine.player(Player.Player1).data.temporaryStep ).to.be.equal(0 ); + engine.move("nevlas action power6. build m -1x3."); + expect(engine.player(Player.Player1).data.victoryPoints).to.be.equal(vps + 2); + expect(engine.player(Player.Player1).data.temporaryStep).to.be.equal(0); }); describe("autoChargePower", () => { - it ("should leech 1pw and not do anything on 2pw", () => { + it("should leech 1pw and not do anything on 2pw", () => { const moves = parseMoves(` init 2 SGAMBATA p1 faction nevlas @@ -581,13 +611,13 @@ describe("Engine", () => { expect(engine.moveHistory.slice(-1).pop()).to.equal("terrans charge 1pw"); /* Test with 2pw leech */ - engine.move('terrans build ts -3x-2.'); + engine.move("terrans build ts -3x-2."); // tslint:disable-next-line no-unused-expression expect(engine.autoChargePower()).to.be.false; expect(engine.moveHistory.length).to.equal(moves.length + 2); }); - it ("should not leech 1pw when brainstone may move", () => { + it("should not leech 1pw when brainstone may move", () => { const moves = parseMoves(` init 2 randomSeed p1 faction terrans @@ -614,7 +644,7 @@ describe("Engine", () => { expect(engine.findAvailableCommand(Player.Player2, Command.ChargePower)).to.not.be.undefined; }); - it ("should leech 2pw when player's auto charge value is 2", () => { + it("should leech 2pw when player's auto charge value is 2", () => { const moves = parseMoves(` init 2 SGAMBATA p1 faction nevlas @@ -673,7 +703,7 @@ describe("Engine", () => { }); describe("auction", () => { - it ("should allow auction, everyone is fine wiht the current", () => { + it("should allow auction, everyone is fine wiht the current", () => { const moves = Engine.parseMoves(` init 2 djfjjv4k p1 faction geodens @@ -681,15 +711,13 @@ describe("auction", () => { p1 bid geodens 1 p2 bid itars 1 `); - const engine = new Engine(moves, {auction: true}); + const engine = new Engine(moves, { auction: true }); expect(engine.players[0].faction).to.equal(Faction.Geodens); expect(engine.players[1].faction).to.equal(Faction.Itars); - - }); - it ("should allow auction, geodens are good", () => { + it("should allow auction, geodens are good", () => { const moves = Engine.parseMoves(` init 2 djfjjv4k p1 faction geodens @@ -701,7 +729,7 @@ describe("auction", () => { p1 bid itars 1 `); - const engine = new Engine(moves, {auction: true}); + const engine = new Engine(moves, { auction: true }); expect(engine.players[1].data.bid).to.equal(4); expect(engine.players[0].data.bid).to.equal(1); @@ -709,7 +737,7 @@ describe("auction", () => { expect(engine.players[1].faction).to.equal(Faction.Geodens); }); - it ("should allow auction, everyone is fine wiht the current", () => { + it("should allow auction, everyone is fine wiht the current", () => { const moves = Engine.parseMoves(` init 2 djfjjv4k p1 faction geodens @@ -718,10 +746,10 @@ describe("auction", () => { p2 bid geodens 0 `); - expect(() => new Engine(moves, {auction: true})).to.not.throw(); + expect(() => new Engine(moves, { auction: true })).to.not.throw(); }); - it ("should throw, wrong bid", () => { + it("should throw, wrong bid", () => { const moves = Engine.parseMoves(` init 2 djfjjv4k p1 faction geodens @@ -730,11 +758,10 @@ describe("auction", () => { p2 bid itars 0 `); - expect(() => new Engine(moves, {auction: true})).to.throw(); + expect(() => new Engine(moves, { auction: true })).to.throw(); }); - - it ("should allow auction, 3 players", () => { + it("should allow auction, 3 players", () => { const moves = Engine.parseMoves(` init 3 djfjjv4k p1 faction geodens @@ -751,19 +778,18 @@ describe("auction", () => { p1 bid itars 1 `); - const engine = new Engine(moves, {auction: true}); + const engine = new Engine(moves, { auction: true }); expect(engine.players[2].data.bid).to.equal(6); - expect(engine.players[1].data.bid).to.equal(2); - expect(engine.players[0].data.bid).to.equal(1); + expect(engine.players[1].data.bid).to.equal(2); + expect(engine.players[0].data.bid).to.equal(1); expect(engine.players[0].faction).to.equal(Faction.Itars); expect(engine.players[1].faction).to.equal(Faction.Taklons); expect(engine.players[2].faction).to.equal(Faction.Geodens); - }); - it ("should throw auction, faction is not in list", () => { + it("should throw auction, faction is not in list", () => { const moves = Engine.parseMoves(` init 2 djfjjv4k p1 faction geodens @@ -772,10 +798,10 @@ describe("auction", () => { p2 bid terrans 1 `); - expect(() => new Engine(moves, {auction: true})).to.throw(); + expect(() => new Engine(moves, { auction: true })).to.throw(); }); - it ("should throw auction, bid is wrong", () => { + it("should throw auction, bid is wrong", () => { const moves = Engine.parseMoves(` init 2 djfjjv4k p1 faction geodens @@ -784,10 +810,10 @@ describe("auction", () => { p2 bid itars 1 `); - expect(() => new Engine(moves, {auction: true})).to.throw(); + expect(() => new Engine(moves, { auction: true })).to.throw(); }); - it ("should throw auction, bid is not in the range", () => { + it("should throw auction, bid is not in the range", () => { const moves = Engine.parseMoves(` init 2 djfjjv4k p1 faction geodens @@ -796,10 +822,10 @@ describe("auction", () => { p2 bid itars 12 `); - expect(() => new Engine(moves, {auction: true})).to.throw(); + expect(() => new Engine(moves, { auction: true })).to.throw(); }); - it ("should support auction and then go to building phase", () => { + it("should support auction and then go to building phase", () => { const moves = Engine.parseMoves(` init 2 randomSeed p1 faction terrans @@ -812,10 +838,10 @@ describe("auction", () => { terrans build m -4x2 `); - expect(() => new Engine(moves, {auction: true})).to.not.throw(); + expect(() => new Engine(moves, { auction: true })).to.not.throw(); }); - it ("should throw because players are bidding in the wrong order", () => { + it("should throw because players are bidding in the wrong order", () => { const moves = Engine.parseMoves(` init 4 djfjjv4k p1 faction geodens @@ -829,11 +855,10 @@ describe("auction", () => { p2 bid terrans 3 `); - expect(() => new Engine(moves, {auction: true})).to.throw(); + expect(() => new Engine(moves, { auction: true })).to.throw(); }); - - it ("should allow auction, 4 players, right turn order", () => { + it("should allow auction, 4 players, right turn order", () => { const moves = Engine.parseMoves(` init 4 djfjjv4k p1 faction geodens @@ -849,16 +874,15 @@ describe("auction", () => { p4 bid taklons 1 `); - const engine = new Engine(moves, {auction: true}); + const engine = new Engine(moves, { auction: true }); expect(engine.players[0].faction).to.equal(Faction.Geodens); expect(engine.players[1].faction).to.equal(Faction.Terrans); expect(engine.players[2].faction).to.equal(Faction.Itars); expect(engine.players[3].faction).to.equal(Faction.Taklons); - }); - it ("should throw , wrong leech order based on auction setup", () => { + it("should throw , wrong leech order based on auction setup", () => { const moves = Engine.parseMoves(` init 3 randomSeed p1 faction terrans @@ -880,8 +904,7 @@ describe("auction", () => { ambas charge 1pw `); - expect(() => new Engine(moves, {auction: true})).to.throw(); - + expect(() => new Engine(moves, { auction: true })).to.throw(); }); }); diff --git a/src/engine.ts b/src/engine.ts index 3872d597..79cb4e8e 100644 --- a/src/engine.ts +++ b/src/engine.ts @@ -1,7 +1,7 @@ -import SpaceMap, {MapConfiguration} from './map'; -import assert from 'assert'; -import { sortBy, uniq, sum, set } from 'lodash'; -import Player from './player'; +import SpaceMap, { MapConfiguration } from "./map"; +import assert from "assert"; +import { sortBy, uniq, sum, set } from "lodash"; +import Player from "./player"; import shuffleSeed from "shuffle-seed"; import { Faction, @@ -24,18 +24,18 @@ import { FinalTile, Phase, SubPhase, - Expansion -} from './enums'; -import Event, {EventSource, RoundScoring} from './events'; -import federations from './tiles/federations'; -import {roundScorings, finalScorings} from './tiles/scoring'; -import * as researchTracks from './research-tracks'; -import AvailableCommand, {generate as generateAvailableCommands,} from './available-command'; -import Reward from './reward'; -import {boardActions} from './actions'; -import {stdBuildingValue} from './buildings'; -import {isAdvanced} from './tiles/techs'; -import { range, isEqual } from 'lodash'; + Expansion, +} from "./enums"; +import Event, { EventSource, RoundScoring } from "./events"; +import federations from "./tiles/federations"; +import { roundScorings, finalScorings } from "./tiles/scoring"; +import * as researchTracks from "./research-tracks"; +import AvailableCommand, { generate as generateAvailableCommands } from "./available-command"; +import Reward from "./reward"; +import { boardActions } from "./actions"; +import { stdBuildingValue } from "./buildings"; +import { isAdvanced } from "./tiles/techs"; +import { range, isEqual } from "lodash"; // const ISOLATED_DISTANCE = 3; const LEECHING_DISTANCE = 2; @@ -54,7 +54,7 @@ export interface EngineOptions { /** auction */ auction?: boolean; /** Layout */ - layout?: 'standard' | 'balanced' | 'xshape'; + layout?: "standard" | "balanced" | "xshape"; } /** @@ -73,7 +73,7 @@ export interface LogEntry { move?: number; player?: PlayerEnum; changes?: { - [source in EventSource]?: {[resource in Resource]?: number} + [source in EventSource]?: { [resource in Resource]?: number }; }; // For round changes round?: number; @@ -88,21 +88,29 @@ export default class Engine { options: EngineOptions = {}; tiles: { boosters: { - [key in Booster]?: boolean + [key in Booster]?: boolean; }; techs: { - [key in TechTilePos | AdvTechTilePos]?: {tile: TechTile | AdvTechTile; count: number} + [key in TechTilePos | AdvTechTilePos]?: { + tile: TechTile | AdvTechTile; + count: number; + }; }; scorings: { round: ScoringTile[]; final: FinalTile[]; }; federations: { - [key in Federation]?: number + [key in Federation]?: number; }; - } = {boosters: {}, techs: {}, scorings: {round: null, final: null}, federations: {}}; + } = { + boosters: {}, + techs: {}, + scorings: { round: null, final: null }, + federations: {}, + }; boardActions: { - [key in BoardAction]?: boolean + [key in BoardAction]?: boolean; } = {}; terraformingFederation: Federation; @@ -131,9 +139,17 @@ export default class Engine { // used to transit between phases tempTurnOrder: PlayerEnum[] = []; tempCurrentPlayer: PlayerEnum; - leechSources: Array<{player: PlayerEnum; coordinates: string; tradeDelivery?: PlayerEnum}> = []; + leechSources: Array<{ + player: PlayerEnum; + coordinates: string; + tradeDelivery?: PlayerEnum; + }> = []; // When ongoing leech, remember the source in case - lastLeechSource: {player: PlayerEnum; coordinates: string; tradeDelivery?: PlayerEnum}; + lastLeechSource: { + player: PlayerEnum; + coordinates: string; + tradeDelivery?: PlayerEnum; + }; // All moves moveHistory: string[] = []; @@ -182,7 +198,7 @@ export default class Engine { this.newTurn = false; } - assert(this.turnMoves.length === 0, "Unnecessary commands at the end of the turn: " + this.turnMoves.join('. ')); + assert(this.turnMoves.length === 0, "Unnecessary commands at the end of the turn: " + this.turnMoves.join(". ")); this.moveHistory.push(move); } @@ -220,9 +236,11 @@ export default class Engine { this.advancedLog.push({ player, move, - changes: amount ? { - [source]: {[resource]: amount} - } : undefined + changes: amount + ? { + [source]: { [resource]: amount }, + } + : undefined, }); } } @@ -232,22 +250,20 @@ export default class Engine { } generateAvailableCommands(subphase: SubPhase = null, data?: any): AvailableCommand[] { - return this.availableCommands = generateAvailableCommands(this, subphase, data); + return (this.availableCommands = generateAvailableCommands(this, subphase, data)); } findAvailableCommand(player: PlayerEnum, command: Command) { this.availableCommands = this.availableCommands || this.generateAvailableCommands(); - return this.availableCommands.find( - availableCommand => { - if (availableCommand.name !== command) { - return false; - } - if (availableCommand.player === undefined) { - return false; - } - return availableCommand.player === player; + return this.availableCommands.find((availableCommand) => { + if (availableCommand.name !== command) { + return false; } - ); + if (availableCommand.player === undefined) { + return false; + } + return availableCommand.player === player; + }); } clearAvailableCommands() { @@ -270,7 +286,10 @@ export default class Engine { player.data.on(`gain-${Resource.TemporaryStep}`, () => this.processNextMove(SubPhase.BuildMine)); player.data.on(`gain-${Resource.TemporaryRange}`, (count: number) => { if (this.findAvailableCommand(player.player, Command.MoveShip)) { - assert(player.data.qicUsedToBoostShip === 0 && count === 2, "Impossible to gain range more than once during move ship phase"); + assert( + player.data.qicUsedToBoostShip === 0 && count === 2, + "Impossible to gain range more than once during move ship phase" + ); player.data.qicUsedToBoostShip += 1; this.processNextMove(SubPhase.MoveShip); } else { @@ -280,11 +299,16 @@ export default class Engine { player.data.on(`gain-${Resource.RescoreFederation}`, () => this.processNextMove(SubPhase.RescoreFederationTile)); player.data.on(`gain-${Resource.PISwap}`, () => this.processNextMove(SubPhase.PISwap)); player.data.on(`gain-${Resource.SpaceStation}`, () => this.processNextMove(SubPhase.SpaceStation)); - player.data.on(`gain-${Resource.DowngradeLab}`, () => {this.processNextMove(SubPhase.DowngradeLab); this.processNextMove(SubPhase.UpgradeResearch); }); - player.data.on(`gain-${Resource.UpgradeLowest}`, () => this.processNextMove(SubPhase.UpgradeResearch, {bescods: true})); + player.data.on(`gain-${Resource.DowngradeLab}`, () => { + this.processNextMove(SubPhase.DowngradeLab); + this.processNextMove(SubPhase.UpgradeResearch); + }); + player.data.on(`gain-${Resource.UpgradeLowest}`, () => + this.processNextMove(SubPhase.UpgradeResearch, { bescods: true }) + ); player.data.on(`gain-${Resource.UpgradeZero}`, (count: number) => { for (let i = 0; i < count; i++) { - this.processNextMove(SubPhase.UpgradeResearch, {zero: true}); + this.processNextMove(SubPhase.UpgradeResearch, { zero: true }); } }); player.data.on(`gain-${Resource.MoveShips}`, () => { @@ -305,23 +329,38 @@ export default class Engine { player.resetTemporaryVariables(); this.processNextMove(SubPhase.MoveShip); }); - player.data.on('brainstone', areas => this.processNextMove(SubPhase.BrainStone, areas)); + player.data.on("brainstone", (areas) => this.processNextMove(SubPhase.BrainStone, areas)); // Test before upgrading research that it's actually possible. Needed when getting up-int or up-nav in // the spaceship expansion - player.data.on('beforeResearchUpgrade', field => { + player.data.on("beforeResearchUpgrade", (field) => { const destTile = player.data.research[field] + 1; if (!player.canUpgradeResearch(field)) { player.data.canUpgradeResearch = false; - } else if (destTile === researchTracks.lastTile(field) && this.players.some(pl => pl.data.research[field] === destTile)) { + } else if ( + destTile === researchTracks.lastTile(field) && + this.players.some((pl) => pl.data.research[field] === destTile) + ) { player.data.canUpgradeResearch = false; } }); - player.on('pick-rewards', () => this.processNextMove(SubPhase.PickRewards)); + player.on("pick-rewards", () => this.processNextMove(SubPhase.PickRewards)); /* For advanced log */ - for (const resource of [Resource.VictoryPoint, Resource.ChargePower, Resource.Credit, Resource.Qic, Resource.Knowledge, Resource.Ore, Resource.GainToken]) { - player.data.on(`gain-${resource}`, (amount: number, source: EventSource) => this.log(player.player, resource, amount, source)); - player.data.on(`pay-${resource}`, (amount: number, source: EventSource) => this.log(player.player, resource, -amount, source)); + for (const resource of [ + Resource.VictoryPoint, + Resource.ChargePower, + Resource.Credit, + Resource.Qic, + Resource.Knowledge, + Resource.Ore, + Resource.GainToken, + ]) { + player.data.on(`gain-${resource}`, (amount: number, source: EventSource) => + this.log(player.player, resource, amount, source) + ); + player.data.on(`pay-${resource}`, (amount: number, source: EventSource) => + this.log(player.player, resource, -amount, source) + ); } } @@ -330,7 +369,7 @@ export default class Engine { } playersInOrder(): Player[] { - return this.turnOrder.map(i => this.players[i]); + return this.turnOrder.map((i) => this.players[i]); } /** @@ -338,14 +377,13 @@ export default class Engine { * @param player */ playersInTableOrderFrom(player: PlayerEnum): Player[] { - - const pos = this.turnOrderAfterSetupAuction.findIndex(pl => pl === player); - const turn= [...this.turnOrderAfterSetupAuction.slice(pos), ...this.turnOrderAfterSetupAuction.slice(0, pos)]; - return turn.map(pl => this.players[pl]); + const pos = this.turnOrderAfterSetupAuction.findIndex((pl) => pl === player); + const turn = [...this.turnOrderAfterSetupAuction.slice(pos), ...this.turnOrderAfterSetupAuction.slice(0, pos)]; + return turn.map((pl) => this.players[pl]); } get turnOrderAfterSetupAuction(): PlayerEnum[] { - return this.setup.map(faction => this.players.findIndex(pl => pl.faction == faction)); + return this.setup.map((faction) => this.players.findIndex((pl) => pl.faction == faction)); } get playerToMove(): PlayerEnum { @@ -357,14 +395,14 @@ export default class Engine { } numberOfPlayersWithFactions(): number { - return this.players.filter(pl => pl.faction).length; + return this.players.filter((pl) => pl.faction).length; } getNextPlayer(list: PlayerEnum[] = this.turnOrder) { return list[(list.indexOf(this.currentPlayer) + 1) % list.length]; } - moveToNextPlayer(list: PlayerEnum[], params: {loop?: boolean} = {loop: true}) { + moveToNextPlayer(list: PlayerEnum[], params: { loop?: boolean } = { loop: true }) { if (list.length === 0) { return false; } @@ -387,10 +425,10 @@ export default class Engine { const pl = this.player(toMove); const ps = pl.faction || `p${toMove + 1}`; - if (this.availableCommands.some(cmd => cmd.name === Command.Decline)) { + if (this.availableCommands.some((cmd) => cmd.name === Command.Decline)) { const cmd = this.findAvailableCommand(this.playerToMove, Command.Decline); this.move(`${ps} ${Command.Decline} ${cmd.data.offer}`, false); - } else if (this.availableCommands.some(cmd => cmd.name === Command.Pass)) { + } else if (this.availableCommands.some((cmd) => cmd.name === Command.Pass)) { const cmd = this.findAvailableCommand(this.playerToMove, Command.Pass); const boosters = cmd.data.boosters; @@ -399,20 +437,32 @@ export default class Engine { } else { this.move(`${ps} ${Command.Pass}`, false); } - } else if (this.availableCommands.some(cmd => cmd.name === Command.ChooseIncome)) { + } else if (this.availableCommands.some((cmd) => cmd.name === Command.ChooseIncome)) { const cmd = this.findAvailableCommand(this.playerToMove, Command.ChooseIncome); this.move(`${ps} ${Command.ChooseIncome} ${cmd.data}`); - } else if (this.availableCommands.some(cmd => cmd.name === Command.BrainStone)) { + } else if (this.availableCommands.some((cmd) => cmd.name === Command.BrainStone)) { const cmd = this.findAvailableCommand(this.playerToMove, Command.BrainStone); this.move(`${ps} ${Command.BrainStone} ${cmd.data[0]}`); - } else if (this.availableCommands.some(cmd => cmd.name === Command.PlaceShip)) { + } else if (this.availableCommands.some((cmd) => cmd.name === Command.PlaceShip)) { const cmd = this.findAvailableCommand(this.playerToMove, Command.PlaceShip); this.move(`${ps} ${Command.PlaceShip} ${cmd.data.locations[0].coordinates}`); - } else if (this.availableCommands.some(cmd => cmd.name === Command.Spend && cmd.data.acts[0].cost.includes(Resource.GainTokenGaiaArea))) { + } else if ( + this.availableCommands.some( + (cmd) => cmd.name === Command.Spend && cmd.data.acts[0].cost.includes(Resource.GainTokenGaiaArea) + ) + ) { // Terrans spending power in gaia phase to create resources - this.move(`${ps} ${Command.Spend} ${pl.data.power.gaia}${Resource.GainTokenGaiaArea} for ${pl.data.power.gaia}${Resource.Credit}`); + this.move( + `${ps} ${Command.Spend} ${pl.data.power.gaia}${Resource.GainTokenGaiaArea} for ${pl.data.power.gaia}${Resource.Credit}` + ); } else { - assert(false, "Can't automove for player " + (this.playerToMove + 1) + ", available command: " + this.availableCommands[0].name); + assert( + false, + "Can't automove for player " + + (this.playerToMove + 1) + + ", available command: " + + this.availableCommands[0].name + ); } // Again @@ -447,14 +497,14 @@ export default class Engine { // cost associated with it. // If this not true, please add an example (or link to) in the comments if (this.isLastRound && this.passedPlayers.includes(pl.player)) { - if (!offers.some(offer => offer.cost === '~')) { + if (!offers.some((offer) => offer.cost === "~")) { this.move(`${pl.faction} ${Command.Decline} ${offer}`, false); return true; } } // Only leech when only one option and cost is nothing - if (offers.length > 1 || power > (pl.data.autoChargePower ?? 1) ) { + if (offers.length > 1 || power > (pl.data.autoChargePower ?? 1)) { return false; } @@ -527,9 +577,9 @@ export default class Engine { const jsonObj: any = Object.assign({}, this); Object.entries(Object.getOwnPropertyDescriptors(proto)) - .filter(([key, descriptor]) => typeof descriptor.get === 'function') + .filter(([key, descriptor]) => typeof descriptor.get === "function") .map(([key, descriptor]) => { - if (descriptor && key[0] !== '_') { + if (descriptor && key[0] !== "_") { try { const val = (this as any)[key]; jsonObj[key] = val; @@ -558,7 +608,10 @@ export default class Engine { } static parseMoves(moves: string) { - return moves.trim().split("\n").map(move => move.trim()); + return moves + .trim() + .split("\n") + .map((move) => move.trim()); } /** @@ -567,38 +620,53 @@ export default class Engine { * @param move The move string to process. Can contain multiple moves separated by a dot * @param params params.processFirst indicates to process the first move. params.split is set to true if leftover commands are allowed */ - loadTurnMoves(move: string, params: {split?: boolean; processFirst?: boolean} = {split: true, processFirst: false}) { + loadTurnMoves( + move: string, + params: { split?: boolean; processFirst?: boolean } = { + split: true, + processFirst: false, + } + ) { this.oldPhase = this.phase; - const playerS = move.substr(0, move.indexOf(' ')); + const playerS = move.substr(0, move.indexOf(" ")); let player: number; if (/^p[1-7]$/.test(playerS)) { player = +playerS[1] - 1; } else { - const pl = this.players.find(_pl => _pl.faction === playerS); + const pl = this.players.find((_pl) => _pl.faction === playerS); if (pl) { player = pl.player; } } - assert(this.playerToMove === (player as PlayerEnum), "Wrong turn order in move " + move + ", expected player " + (this.playerToMove + 1)); + assert( + this.playerToMove === (player as PlayerEnum), + "Wrong turn order in move " + move + ", expected player " + (this.playerToMove + 1) + ); this.processedPlayer = player; - const split = params.split ?? true ; + const split = params.split ?? true; const processFirst = params.processFirst ?? true; if (!split) { assert(processFirst); } - this.turnMoves = move.substr(playerS.length).split('.').map(x => x.trim()); + this.turnMoves = move + .substr(playerS.length) + .split(".") + .map((x) => x.trim()); if (processFirst) { this.processNextMove(); - assert(split || this.turnMoves.length === 0, "There is an extra command at the end of the turn: " + this.turnMoves.join('. ')); + assert( + split || this.turnMoves.length === 0, + "There is an extra command at the end of the turn: " + this.turnMoves.join(". ") + ); } } @@ -608,7 +676,7 @@ export default class Engine { */ executeMove(move: string) { try { - (this[this.phase])(move); + this[this.phase](move); this.clearAvailableCommands(); } catch (err) { if (err.availableCommands) { @@ -623,10 +691,10 @@ export default class Engine { } parseMove(move: string) { - const split = move.split(' '); + const split = move.split(" "); return { command: (split[0] || Command.EndTurn) as Command, - args: split.slice(1) + args: split.slice(1), }; } @@ -638,7 +706,9 @@ export default class Engine { } } if (this.turnMoves.length === 0) { - throw Object.assign(new Error('Missing command to end turn'), {availableCommands: this.availableCommands}); + throw Object.assign(new Error("Missing command to end turn"), { + availableCommands: this.availableCommands, + }); } const move = this.parseMove(this.turnMoves.shift()); @@ -653,7 +723,10 @@ export default class Engine { } checkCommand(command: Command) { - assert(this.availableCommand = this.findAvailableCommand(this.playerToMove, command), `Command ${command} is not in the list of available commands: ${this.availableCommands.map(cmd => cmd.name)}`); + assert( + (this.availableCommand = this.findAvailableCommand(this.playerToMove, command)), + `Command ${command} is not in the list of available commands: ${this.availableCommands.map((cmd) => cmd.name)}` + ); } doFreeActions(subPhase: SubPhase) { @@ -695,7 +768,7 @@ export default class Engine { this.player(this.currentPlayer).receiveIncome(); - if (!this.moveToNextPlayer(this.tempTurnOrder, {loop: false})) { + if (!this.moveToNextPlayer(this.tempTurnOrder, { loop: false })) { this.endIncomePhase(); } else { this.handleNextIncome(); @@ -718,7 +791,7 @@ export default class Engine { player.gaiaPhase(); - if (!this.moveToNextPlayer(this.tempTurnOrder, {loop: false})) { + if (!this.moveToNextPlayer(this.tempTurnOrder, { loop: false })) { this.endGaiaPhase(); } else { this.handleNextGaia(); @@ -748,19 +821,19 @@ export default class Engine { beginSetupFactionPhase() { this.changePhase(Phase.SetupFaction); - this.turnOrder = this.players.map(pl => pl.player as PlayerEnum); - this.moveToNextPlayer(this.turnOrder, {loop: false}); + this.turnOrder = this.players.map((pl) => pl.player as PlayerEnum); + this.moveToNextPlayer(this.turnOrder, { loop: false }); } beginSetupAuctionPhase() { this.changePhase(Phase.SetupAuction); - this.turnOrder = this.players.map(pl => pl.player as PlayerEnum); + this.turnOrder = this.players.map((pl) => pl.player as PlayerEnum); - this.moveToNextPlayer(this.turnOrder, {loop: false}); + this.moveToNextPlayer(this.turnOrder, { loop: false }); } endSetupAuctionPhase() { - for ( const pl of this.players ){ + for (const pl of this.players) { if (pl.faction) { pl.loadFaction(pl.faction, this.expansions); } else { @@ -774,18 +847,13 @@ export default class Engine { beginSetupBuildingPhase() { this.changePhase(Phase.SetupBuilding); - const posIvits = this.players.findIndex( - player => player.faction === Faction.Ivits - ); + const posIvits = this.players.findIndex((player) => player.faction === Faction.Ivits); - const setupTurnOrder = this.turnOrderAfterSetupAuction - .filter(i => i !== posIvits); + const setupTurnOrder = this.turnOrderAfterSetupAuction.filter((i) => i !== posIvits); const reverseSetupTurnOrder = setupTurnOrder.slice().reverse(); this.turnOrder = setupTurnOrder.concat(reverseSetupTurnOrder); - const posXenos = this.players.findIndex( - player => player.faction === Faction.Xenos - ); + const posXenos = this.players.findIndex((player) => player.faction === Faction.Xenos); if (posXenos !== -1) { this.turnOrder.push(posXenos as PlayerEnum); @@ -795,24 +863,24 @@ export default class Engine { this.turnOrder.push(posIvits as PlayerEnum); } - this.moveToNextPlayer(this.turnOrder, {loop: false}); + this.moveToNextPlayer(this.turnOrder, { loop: false }); } beginSetupBoosterPhase() { this.changePhase(Phase.SetupBooster); this.turnOrder = this.turnOrderAfterSetupAuction.reverse(); - this.moveToNextPlayer(this.turnOrder, {loop: false}); + this.moveToNextPlayer(this.turnOrder, { loop: false }); } beginSetupShipPhase() { this.changePhase(Phase.SetupShip); this.turnOrder = this.turnOrderAfterSetupAuction; - this.moveToNextPlayer(this.turnOrder, {loop: false}); + this.moveToNextPlayer(this.turnOrder, { loop: false }); } beginRoundStartPhase() { this.round += 1; - this.advancedLog.push({round: this.round}); + this.advancedLog.push({ round: this.round }); this.turnOrder = this.passedPlayers || this.turnOrderAfterSetupAuction; this.passedPlayers = []; this.currentPlayer = this.turnOrder[0]; @@ -826,17 +894,17 @@ export default class Engine { beginIncomePhase() { this.changePhase(Phase.RoundIncome); - this.advancedLog.push({phase: Phase.RoundIncome}); + this.advancedLog.push({ phase: Phase.RoundIncome }); this.tempTurnOrder = [...this.turnOrder]; - this.moveToNextPlayer(this.tempTurnOrder, {loop: false}); + this.moveToNextPlayer(this.tempTurnOrder, { loop: false }); this.handleNextIncome(); } endIncomePhase() { // remove incomes from roundboosters for (const player of this.playersInOrder()) { - player.removeRoundBoosterEvents( Operator.Income ); + player.removeRoundBoosterEvents(Operator.Income); } this.beginGaiaPhase(); @@ -844,17 +912,21 @@ export default class Engine { beginGaiaPhase() { this.changePhase(Phase.RoundGaia); - this.advancedLog.push({phase: Phase.RoundGaia}); + this.advancedLog.push({ phase: Phase.RoundGaia }); this.tempTurnOrder = [...this.turnOrder]; // transform Transdim planets into Gaia if gaiaformed for (const hex of this.map.toJSON()) { - if (hex.data.planet === Planet.Transdim && hex.data.player !== undefined && hex.data.building === Building.GaiaFormer) { + if ( + hex.data.planet === Planet.Transdim && + hex.data.player !== undefined && + hex.data.building === Building.GaiaFormer + ) { hex.data.planet = Planet.Gaia; } } - this.moveToNextPlayer(this.tempTurnOrder, {loop: false}); + this.moveToNextPlayer(this.tempTurnOrder, { loop: false }); this.handleNextGaia(); } @@ -904,22 +976,25 @@ export default class Engine { finalScoringPhase() { this.changePhase(Phase.EndGame); - this.advancedLog.push({phase: Phase.EndGame}); + this.advancedLog.push({ phase: Phase.EndGame }); this.currentPlayer = this.tempCurrentPlayer = undefined; - const allRankings: Array> = []; + const allRankings: Array> = []; // finalScoring tiles for (const tile of this.tiles.scorings.final) { - const players = sortBy(this.players, player => player.finalCount(tile)).reverse(); + const players = sortBy(this.players, (player) => player.finalCount(tile)).reverse(); - const rankings = players.map(pl => ({ + const rankings = players.map((pl) => ({ player: pl, - count: pl.finalCount(tile) + count: pl.finalCount(tile), })); if (this.players.length === 2) { - rankings.push({ player: null, count: finalScorings[tile].neutralPlayer }); + rankings.push({ + player: null, + count: finalScorings[tile].neutralPlayer, + }); rankings.sort((pl1, pl2) => pl2.count - pl1.count); } @@ -930,20 +1005,23 @@ export default class Engine { for (const player of this.players) { // Gain points from final scoring allRankings.forEach((rankings, index) => { - const ranking = rankings.find(rnk => rnk.player === player); + const ranking = rankings.find((rnk) => rnk.player === player); const count = ranking.count; // index of the first player with that score - const first = rankings.findIndex(pl => pl.count === count); + const first = rankings.findIndex((pl) => pl.count === count); // number of other players with the same score - const ties = rankings.filter(pl => pl.count === count).length; + const ties = rankings.filter((pl) => pl.count === count).length; // only players that advaced are getting VPs // see https://boardgamegeek.com/thread/1929227/0-end-score-0-vp if (ranking.player && count > 0) { const VPs = [18, 12, 6, 0, 0, 0]; - ranking.player.gainRewards([new Reward(Math.floor(sum(VPs.slice(first, first + ties)) / ties), Resource.VictoryPoint)], `final${index + 1}` as 'final1' | 'final2'); + ranking.player.gainRewards( + [new Reward(Math.floor(sum(VPs.slice(first, first + ties)) / ties), Resource.VictoryPoint)], + `final${index + 1}` as "final1" | "final2" + ); } }); @@ -951,7 +1029,7 @@ export default class Engine { player.data.gainFinalVictoryPoints(); //remove bids - player.gainRewards([new Reward(Math.max(Math.floor(-1*player.data.bid )), Resource.VictoryPoint)], Command.Bid); + player.gainRewards([new Reward(Math.max(Math.floor(-1 * player.data.bid)), Resource.VictoryPoint)], Command.Bid); } } @@ -999,14 +1077,14 @@ export default class Engine { if (canLeechPlayers.length > 0) { this.changePhase(Phase.RoundLeech); - this.tempTurnOrder = canLeechPlayers.map(pl => pl.player); + this.tempTurnOrder = canLeechPlayers.map((pl) => pl.player); this.tempCurrentPlayer = this.tempTurnOrder.shift(); } else { return this.beginLeechingPhase(); } } - advanceResearchAreaPhase(player: PlayerEnum, cost: string, field: ResearchField ) { + advanceResearchAreaPhase(player: PlayerEnum, cost: string, field: ResearchField) { const pl = this.player(player); if (!pl.canUpgradeResearch(field)) { @@ -1017,7 +1095,7 @@ export default class Engine { // If someone is already on last tile if (destTile === researchTracks.lastTile(field)) { - if (this.players.some(pl2 => pl2.data.research[field] === destTile)) { + if (this.players.some((pl2) => pl2.data.research[field] === destTile)) { return; } } @@ -1045,7 +1123,7 @@ export default class Engine { // ******** PHASE COMMAND HANDLING ******** // **************************************** [Phase.SetupInit](move: string) { - const split = move.split(' '); + const split = move.split(" "); const command = split[0] as Command; assert(command === Command.Init, "The first command of a game needs to be the initialization command"); @@ -1056,15 +1134,15 @@ export default class Engine { } [Phase.SetupBoard](move: string) { - this.loadTurnMoves(move, {split: false, processFirst: true}); + this.loadTurnMoves(move, { split: false, processFirst: true }); this.beginSetupFactionPhase(); } [Phase.SetupFaction](move: string) { - this.loadTurnMoves(move, {split: false, processFirst: true}); + this.loadTurnMoves(move, { split: false, processFirst: true }); - if (!this.moveToNextPlayer(this.turnOrder, {loop: false})) { + if (!this.moveToNextPlayer(this.turnOrder, { loop: false })) { if (this.options.auction) { this.beginSetupAuctionPhase(); } else { @@ -1075,21 +1153,23 @@ export default class Engine { } [Phase.SetupAuction](move: string) { - this.loadTurnMoves(move, {processFirst: true}); + this.loadTurnMoves(move, { processFirst: true }); - const player = [...range(this.currentPlayer + 1, this.players.length), ...range(0, this.currentPlayer)].find(player => !this.players.some(pl => pl.player === player && pl.faction)); + const player = [...range(this.currentPlayer + 1, this.players.length), ...range(0, this.currentPlayer)].find( + (player) => !this.players.some((pl) => pl.player === player && pl.faction) + ); if (player !== undefined) { - this.currentPlayer = player; + this.currentPlayer = player; } else { - this.endSetupAuctionPhase(); + this.endSetupAuctionPhase(); } } [Phase.SetupBuilding](move: string) { - this.loadTurnMoves(move, {split: false, processFirst: true}); + this.loadTurnMoves(move, { split: false, processFirst: true }); - if (!this.moveToNextPlayer(this.turnOrder, {loop: false})) { + if (!this.moveToNextPlayer(this.turnOrder, { loop: false })) { if (this.expansions & Expansion.Spaceships) { this.beginSetupShipPhase(); } else { @@ -1099,23 +1179,23 @@ export default class Engine { } [Phase.SetupShip](move: string) { - this.loadTurnMoves(move, {split: false, processFirst: true}); + this.loadTurnMoves(move, { split: false, processFirst: true }); - if (!this.moveToNextPlayer(this.turnOrder, {loop: false})) { + if (!this.moveToNextPlayer(this.turnOrder, { loop: false })) { this.beginSetupBoosterPhase(); } } [Phase.SetupBooster](move: string) { - this.loadTurnMoves(move, {split: false, processFirst: true}); + this.loadTurnMoves(move, { split: false, processFirst: true }); - if (!this.moveToNextPlayer(this.turnOrder, {loop: false})) { + if (!this.moveToNextPlayer(this.turnOrder, { loop: false })) { this.beginRoundStartPhase(); } } [Phase.RoundIncome](move: string) { - this.loadTurnMoves(move, {processFirst: true}); + this.loadTurnMoves(move, { processFirst: true }); while (!this.handleNextIncome()) { this.generateAvailableCommands(); @@ -1124,7 +1204,7 @@ export default class Engine { } [Phase.RoundGaia](move: string) { - this.loadTurnMoves(move, {processFirst: true}); + this.loadTurnMoves(move, { processFirst: true }); while (!this.handleNextGaia(true)) { this.generateAvailableCommands(); @@ -1177,7 +1257,7 @@ export default class Engine { } [Phase.RoundLeech](move: string) { - this.loadTurnMoves(move, {split: false, processFirst: true}); + this.loadTurnMoves(move, { split: false, processFirst: true }); this.tempCurrentPlayer = this.tempTurnOrder.shift(); // Current leech round ended @@ -1192,7 +1272,7 @@ export default class Engine { // **************************************** [Command.Init](players: string, seed: string) { const nbPlayers = +players || 2; - seed = seed || 'defaultSeed'; + seed = seed || "defaultSeed"; assert(nbPlayers >= 2 && nbPlayers <= 5, "Invalid number of players"); @@ -1211,19 +1291,22 @@ export default class Engine { // Shuffle tech tiles const techtiles = shuffleSeed.shuffle(TechTile.values(this.expansions), this.map.rng()); - TechTilePos.values(this.expansions).forEach( (pos, i) => { - this.tiles.techs[pos] = {tile: techtiles[i], count: 4}; + TechTilePos.values(this.expansions).forEach((pos, i) => { + this.tiles.techs[pos] = { tile: techtiles[i], count: 4 }; }); - this.tiles.techs[TechTilePos.BasicShip] = {tile: TechTile.Ship0, count: 0}; + this.tiles.techs[TechTilePos.BasicShip] = { + tile: TechTile.Ship0, + count: 0, + }; // Choose adv tech tiles as part of the pool const advtechtiles = shuffleSeed.shuffle(AdvTechTile.values(this.expansions), this.map.rng()); - AdvTechTilePos.values(this.expansions).forEach( (pos, i) => { - this.tiles.techs[pos] = {tile: advtechtiles[i], count: 1}; + AdvTechTilePos.values(this.expansions).forEach((pos, i) => { + this.tiles.techs[pos] = { tile: advtechtiles[i], count: 1 }; }); // powerActions - BoardAction.values(this.expansions).forEach( (pos: BoardAction) => { + BoardAction.values(this.expansions).forEach((pos: BoardAction) => { this.boardActions[pos] = true; }); @@ -1265,7 +1348,7 @@ export default class Engine { pairs.push([params[i], params[i + 1]]); } - assert(uniq(pairs.map(pair => pair[0])).length === params.length / 2, "Duplicate rotations are not allowed"); + assert(uniq(pairs.map((pair) => pair[0])).length === params.length / 2, "Duplicate rotations are not allowed"); for (const pair of pairs) { this.map.rotateSector(pair[0], +pair[1]); @@ -1276,16 +1359,16 @@ export default class Engine { [Command.ChooseFaction](player: PlayerEnum, faction: string) { assert(this.availableCommand.data.includes(faction), `${faction} is not in the available factions`); - this.setup.push( faction as Faction ); + this.setup.push(faction as Faction); } [Command.Bid](player: PlayerEnum, faction: string, bid: number) { - const bidsAC = this.availableCommand.data.bids; - const bidAC = bidsAC.find( b => b.faction === faction); - assert( bidAC.bid.includes(+bid), 'You have to bid the right amount'); - assert( bidAC, `${faction} is not in the available factions`); + const bidsAC = this.availableCommand.data.bids; + const bidAC = bidsAC.find((b) => b.faction === faction); + assert(bidAC.bid.includes(+bid), "You have to bid the right amount"); + assert(bidAC, `${faction} is not in the available factions`); - const previous = this.players.find(s => s.faction == faction); + const previous = this.players.find((s) => s.faction == faction); // remove faction from previous owner if (previous) { previous.faction = undefined; @@ -1295,7 +1378,11 @@ export default class Engine { this.players[player].data.bid = +bid; } - [Command.ChooseRoundBooster](player: PlayerEnum, booster: Booster, fromCommand: Command = Command.ChooseRoundBooster ) { + [Command.ChooseRoundBooster]( + player: PlayerEnum, + booster: Booster, + fromCommand: Command = Command.ChooseRoundBooster + ) { const { boosters } = this.availableCommand.data; assert(boosters.includes(booster), `${booster} is not in the available boosters`); @@ -1310,15 +1397,15 @@ export default class Engine { for (const elem of buildings) { if (elem.building === building && isEqual(this.map.parse(elem.coordinates), parsed)) { - const {q, r} = this.map.parse(location); - const hex = this.map.grid.get({q, r}); + const { q, r } = this.map.parse(location); + const hex = this.map.grid.get({ q, r }); const pl = this.player(player); pl.build(building, hex, Reward.parse(elem.cost), this.map, elem.steps); // will trigger a LeechPhase if (this.phase === Phase.RoundMove) { - this.leechSources.unshift({player, coordinates: location}); + this.leechSources.unshift({ player, coordinates: location }); } return; @@ -1330,7 +1417,7 @@ export default class Engine { [Command.UpgradeResearch](player: PlayerEnum, field: ResearchField) { const { tracks } = this.availableCommand.data; - const track = tracks.find(tr => tr.field === field); + const track = tracks.find((tr) => tr.field === field); assert(track, `Impossible to upgrade research for ${field}`); @@ -1356,12 +1443,15 @@ export default class Engine { // Handles legacy stuff. To remove when all games with old engine have ended if (!leechCommand.offers) { - leechCommand.offers = [{offer: leechCommand.offer, cost: leechCommand.cost}]; + leechCommand.offers = [{ offer: leechCommand.offer, cost: leechCommand.cost }]; } - const offer = leechCommand.offers.find(ofr => ofr.offer === income); + const offer = leechCommand.offers.find((ofr) => ofr.offer === income); - assert(offer, `Cannot leech ${income}. Possible leeches: ${leechCommand.offers.map(ofr => ofr.offer).join(' - ')}`); + assert( + offer, + `Cannot leech ${income}. Possible leeches: ${leechCommand.offers.map((ofr) => ofr.offer).join(" - ")}` + ); this.player(player).gainRewards(leechRewards, Command.ChargePower); this.player(player).payCosts(Reward.parse(offer.cost), Command.ChargePower); @@ -1377,7 +1467,7 @@ export default class Engine { [Command.ChooseTechTile](player: PlayerEnum, pos: TechTilePos | AdvTechTilePos) { const { tiles } = this.availableCommand.data; - const tileAvailable = tiles.find(ta => ta.pos === pos); + const tileAvailable = tiles.find((ta) => ta.pos === pos); assert(tileAvailable !== undefined, `Impossible to get ${pos} tile`); @@ -1391,12 +1481,15 @@ export default class Engine { this.tiles.techs[pos].count -= 1; // AFTER gaining the tech tile (as green federation can be flipped and lock research tracks) - this.processNextMove(SubPhase.UpgradeResearch, ResearchField.values(Expansion.All).includes(pos as any as ResearchField) ? {pos} : undefined) ; + this.processNextMove( + SubPhase.UpgradeResearch, + ResearchField.values(Expansion.All).includes((pos as any) as ResearchField) ? { pos } : undefined + ); } [Command.ChooseCoverTechTile](player: PlayerEnum, tilePos: TechTilePos) { const { tiles } = this.availableCommand.data; - const tileAvailable = tiles.find(ta => ta.pos === tilePos); + const tileAvailable = tiles.find((ta) => ta.pos === tilePos); assert(tileAvailable !== undefined, `Impossible to cover ${tilePos} tile`); // remove tile @@ -1405,7 +1498,7 @@ export default class Engine { [Command.Special](player: PlayerEnum, income: string) { const { specialacts } = this.availableCommand.data; - const actAvailable = specialacts.find(sa => Reward.match(Reward.parse(sa.income), Reward.parse(income))); + const actAvailable = specialacts.find((sa) => Reward.match(Reward.parse(sa.income), Reward.parse(income))); assert(actAvailable !== undefined, `Special action ${income} is not available`); @@ -1431,7 +1524,7 @@ export default class Engine { const { spaces } = this.availableCommand.data; const parsed = this.map.parse(location); - const data = spaces.find(space => isEqual(this.map.parse(space.coordinates), parsed)); + const data = spaces.find((space) => isEqual(this.map.parse(space.coordinates), parsed)); assert(data, `Impossible to execute build command at ${location}`); @@ -1440,7 +1533,7 @@ export default class Engine { this.player(player).build(Building.Mine, hex, Reward.parse(data.cost), this.map, 0); - this.leechSources.unshift({player, coordinates: location}); + this.leechSources.unshift({ player, coordinates: location }); } [Command.PlaceShip](player: PlayerEnum, location: string) { @@ -1448,7 +1541,12 @@ export default class Engine { const { locations } = this.availableCommand.data; const parsed = this.map.parse(location); - assert(locations.find(loc => isEqual(this.map.parse(loc.coordinates), parsed), `Impossible to place ship at ${location}`)); + assert( + locations.find( + (loc) => isEqual(this.map.parse(loc.coordinates), parsed), + `Impossible to place ship at ${location}` + ) + ); const hex = this.map.grid.get(parsed); pl.placeShip(hex); @@ -1460,12 +1558,19 @@ export default class Engine { } [Command.DeliverTrade](player: PlayerEnum, location: string) { - assert(location === this.availableCommand.data.locations[0].coordinates, "Impossible to deliver trade at " + location); + assert( + location === this.availableCommand.data.locations[0].coordinates, + "Impossible to deliver trade at " + location + ); const destHex = this.map.getS(location); this.player(player).deliverTrade(destHex); // The main occupier of the planet can charge power - this.leechSources.push({player, coordinates: location, tradeDelivery: destHex.data.player}); + this.leechSources.push({ + player, + coordinates: location, + tradeDelivery: destHex.data.player, + }); } [`_${Command.MoveShip}`](player: PlayerEnum, ship: string, dest: string) { @@ -1474,11 +1579,13 @@ export default class Engine { const { ships, range, costs } = this.availableCommand.data; const parsedShip = this.map.parse(ship); - assert(ships.find(loc => isEqual(this.map.parse(loc.coordinates), parsedShip), `There is no movable ship at ${ship}`)); + assert( + ships.find((loc) => isEqual(this.map.parse(loc.coordinates), parsedShip), `There is no movable ship at ${ship}`) + ); const distance = this.map.distance(parsedShip, this.map.parse(dest)); - assert(range >= distance, 'The ship cannot move that far'); + assert(range >= distance, "The ship cannot move that far"); const moveCost = costs[distance] || "~"; pl.payCosts(Reward.parse(moveCost), Command.MoveShip); @@ -1488,37 +1595,54 @@ export default class Engine { const destHex = this.map.getS(dest); if (pl.data.availableWildTradeTokens() > 0) { - assert (!destHex.hasTradeToken(player) || !destHex.hasWildTradeToken(), `The destination planet already has a trade token for your faction`); + assert( + !destHex.hasTradeToken(player) || !destHex.hasWildTradeToken(), + `The destination planet already has a trade token for your faction` + ); } else { - assert (!destHex.hasTradeToken(player), `The destination planet already has a trade token for your faction`); + assert(!destHex.hasTradeToken(player), `The destination planet already has a trade token for your faction`); } pl.placeShip(destHex); if (destHex.hasPlanet()) { if (destHex.occupied()) { - assert(destHex.hasStructure(), `When moving a ship to an occupied planet, there needs to be a valid building on it`); + assert( + destHex.hasStructure(), + `When moving a ship to an occupied planet, there needs to be a valid building on it` + ); assert(!destHex.isMainOccupier(player), "You can't move a ship to a planet that is occupied by you."); const canPutTradeToken = pl.data.availableTradeTokens() > 0 && !destHex.hasTradeToken(player); const canPutWildTradeToken = pl.data.availableWildTradeTokens() > 0 && !destHex.hasWildTradeToken(); - assert(canPutTradeToken || canPutWildTradeToken, "Impossible to put a trade token on the planet, either you already have a token there or all your tokens are used"); + assert( + canPutTradeToken || canPutWildTradeToken, + "Impossible to put a trade token on the planet, either you already have a token there or all your tokens are used" + ); - this.processNextMove(SubPhase.DeliverTrade, {locations: [{coordinates: dest}], automatic: true}); + this.processNextMove(SubPhase.DeliverTrade, { + locations: [{ coordinates: dest }], + automatic: true, + }); } else { const planet = destHex.data.planet; const building = planet === Planet.Transdim ? Building.GaiaFormer : Building.Mine; - const {possible, cost, steps} = pl.canBuild(planet, building); + const { possible, cost, steps } = pl.canBuild(planet, building); assert(possible, "Impossible to move ship to this empty planet as you cannot build there"); - this.processNextMove(SubPhase.BuildMineOrGaiaFormer, {buildings: [{ - building, - coordinates: dest, - cost: Reward.toString(cost), - steps - }], automatic: true}); + this.processNextMove(SubPhase.BuildMineOrGaiaFormer, { + buildings: [ + { + building, + coordinates: dest, + cost: Reward.toString(cost), + steps, + }, + ], + automatic: true, + }); } pl.removeShip(destHex); @@ -1535,7 +1659,7 @@ export default class Engine { [Command.PickReward](player: PlayerEnum, rewardString: string) { const pl = this.player(player); const reward = new Reward(rewardString); - const index = pl.data.toPick.rewards.findIndex(rw => rw.type === reward.type && rw.count === reward.count); + const index = pl.data.toPick.rewards.findIndex((rw) => rw.type === reward.type && rw.count === reward.count); assert(index !== -1, "Cannot pick " + rewardString); @@ -1556,9 +1680,9 @@ export default class Engine { const cost = Reward.merge(Reward.parse(costS)); const income = Reward.merge(Reward.parse(incomeS)); - assert(!cost.some(r => r.count <= 0) && !income.some(r => r.count <= 0), "Nice try!"); + assert(!cost.some((r) => r.count <= 0) && !income.some((r) => r.count <= 0), "Nice try!"); assert(pl.canPay(cost) && cost, `Impossible to pay ${costS}`); - assert(_for === 'for', "Expect second part of command to be 'for'"); + assert(_for === "for", "Expect second part of command to be 'for'"); // tslint:disable-next-line no-shadowed-variable const isPossible = (cost: Reward[], income: Reward[]) => { @@ -1570,8 +1694,8 @@ export default class Engine { let newIncome = Reward.merge(income, Reward.negative(Reward.parse(action.income))); // Convert unused income into cost - newCost.push(...Reward.negative(newIncome.filter(rew => rew.count < 0))); - newIncome = newIncome.filter(rew => rew.count > 0); + newCost.push(...Reward.negative(newIncome.filter((rew) => rew.count < 0))); + newIncome = newIncome.filter((rew) => rew.count > 0); if (newIncome.length === 0 && newCost.length === 0) { return true; @@ -1599,14 +1723,20 @@ export default class Engine { } [Command.BrainStone](player: PlayerEnum, dest: string) { - assert(this.availableCommand.data.includes(dest), "Possible brain stone areas: " + this.availableCommand.data.join(", ")); + assert( + this.availableCommand.data.includes(dest), + "Possible brain stone areas: " + this.availableCommand.data.join(", ") + ); this.players[player].data.brainstoneDest = dest as any; } [Command.Action](player: PlayerEnum, action: BoardAction) { - const { poweracts: acts} = this.availableCommand.data; + const { poweracts: acts } = this.availableCommand.data; - assert(acts.find(act => act.name === action), `${action} is not in the available power actions`); + assert( + acts.find((act) => act.name === action), + `${action} is not in the available power actions` + ); const pl = this.player(player); this.boardActions[action] = false; @@ -1617,11 +1747,11 @@ export default class Engine { [Command.ChooseIncome](player: PlayerEnum, income: string) { const incomes = this.availableCommand.data; - const incomeRewards = income.split(",") ; + const incomeRewards = income.split(","); const pl = this.player(player); for (const incR of incomeRewards) { - const eventIdx = incomes.findIndex(rw => Reward.match(Reward.parse(incR), [rw])); + const eventIdx = incomes.findIndex((rw) => Reward.match(Reward.parse(incR), [rw])); assert(eventIdx > -1, `${incR} is not in the available income`); incomes.splice(eventIdx, 1); } @@ -1644,18 +1774,18 @@ export default class Engine { const { buildings } = this.availableCommand.data; const pl = this.player(player); - const PIHex = pl.data.occupied.find( hex => hex.buildingOf(player) === Building.PlanetaryInstitute); + const PIHex = pl.data.occupied.find((hex) => hex.buildingOf(player) === Building.PlanetaryInstitute); const parsed = this.map.parse(location); for (const elem of buildings) { if (isEqual(this.map.parse(elem.coordinates), parsed)) { - const {q, r} = this.map.parse(location); - const hex = this.map.grid.get({q, r}); + const { q, r } = this.map.parse(location); + const hex = this.map.grid.get({ q, r }); - if ( hex.buildingOf(player) === Building.Mine ) { + if (hex.buildingOf(player) === Building.Mine) { hex.data.building = Building.PlanetaryInstitute; PIHex.data.building = Building.Mine; - pl.federationCache = null ; + pl.federationCache = null; return; } } diff --git a/src/enums.ts b/src/enums.ts index a9fb503e..d018c39a 100644 --- a/src/enums.ts +++ b/src/enums.ts @@ -9,7 +9,7 @@ export enum Planet { Ice = "i", Gaia = "g", Transdim = "m", - Lost = "l" + Lost = "l", } export enum ResearchField { @@ -25,12 +25,19 @@ export enum ResearchField { export enum Expansion { Spaceships = 1, - All = 1 + All = 1, } export namespace ResearchField { export function values(expansions = 0): ResearchField[] { - const ret = [ResearchField.Terraforming, ResearchField.Navigation, ResearchField.Intelligence, ResearchField.GaiaProject, ResearchField.Economy, ResearchField.Science]; + const ret = [ + ResearchField.Terraforming, + ResearchField.Navigation, + ResearchField.Intelligence, + ResearchField.GaiaProject, + ResearchField.Economy, + ResearchField.Science, + ]; if (expansions & Expansion.Spaceships) { ret.push(ResearchField.TradingBonus, ResearchField.TradingVolume); @@ -78,7 +85,7 @@ export enum Resource { TemporaryRange = "range", TokenArea3 = "t-a3", PISwap = "swap-PI", - Turn = "turn" + Turn = "turn", } export enum Operator { @@ -95,7 +102,7 @@ export enum Operator { /** reserved op for planetary institute and academies becoming 4pw structures */ Special = "PA->4pw", /** Special annoying adv tech */ - AdvShip4 = "2ship+4" + AdvShip4 = "2ship+4", } export enum Condition { @@ -127,17 +134,21 @@ export enum Condition { MineOnGaia = "mg", AdvanceResearch = "a", TerraformStep = "step", - GaiaFormer = "gf" + GaiaFormer = "gf", } export namespace Condition { export function matchesBuilding(condition: Condition, building: Building, planet: Planet): boolean { - if (condition as string === building as string) { + if ((condition as string) === (building as string)) { return true; } switch (condition) { - case Condition.MineOnGaia: return building === Building.Mine && planet === Planet.Gaia; - case Condition.PlanetaryInstituteOrAcademy: return building === Building.PlanetaryInstitute || building === Building.Academy1 || building === Building.Academy2; + case Condition.MineOnGaia: + return building === Building.Mine && planet === Planet.Gaia; + case Condition.PlanetaryInstituteOrAcademy: + return ( + building === Building.PlanetaryInstitute || building === Building.Academy1 || building === Building.Academy2 + ); } return false; } @@ -151,7 +162,7 @@ export enum Building { Academy1 = "ac1", Academy2 = "ac2", GaiaFormer = "gf", - SpaceStation = "sp" + SpaceStation = "sp", } export enum Faction { @@ -168,7 +179,7 @@ export enum Faction { Firaks = "firaks", Bescods = "bescods", Nevlas = "nevlas", - Itars = "itars" + Itars = "itars", } export enum Command { @@ -192,7 +203,7 @@ export enum Command { BrainStone = "brainstone", Action = "action", Special = "special", - PlaceLostPlanet = "lostPlanet", + PlaceLostPlanet = "lostPlanet", PlaceShip = "ship", MoveShip = "move", DeliverTrade = "trade", @@ -200,11 +211,11 @@ export enum Command { FormFederation = "federation", EndTurn = "endturn", EndTurnConfirmation = "endturnConfirmation", - PISwap = "swap-PI" + PISwap = "swap-PI", } export enum TradeToken { - Wild = "wild" + Wild = "wild", } export enum Player { @@ -212,18 +223,18 @@ export enum Player { Player2, Player3, Player4, - Player5 + Player5, } export enum Round { - None= 0, - Round1= 1, - Round2= 2, - Round3= 3, - Round4= 4, - Round5= 5, - Round6= 6, - LastRound = 6 + None = 0, + Round1 = 1, + Round2 = 2, + Round3 = 3, + Round4 = 4, + Round5 = 5, + Round6 = 6, + LastRound = 6, } export enum Booster { @@ -239,17 +250,19 @@ export enum Booster { Booster10 = "booster10", Ship1 = "booster-ship1", Ship2 = "booster-ship2", - Ship3 = "booster-ship3" + Ship3 = "booster-ship3", } export namespace Booster { export function values(expansions = 0): Booster[] { return (Object.values(Booster) as Booster[]).filter((val: Booster) => { - if (typeof val !== "string") {return; } + if (typeof val !== "string") { + return; + } if (/^booster[0-9]/.test(val)) { return true; } - if (expansions & Expansion.Spaceships && val.startsWith('booster-ship')) { + if (expansions & Expansion.Spaceships && val.startsWith("booster-ship")) { return true; } }) as Booster[]; @@ -270,17 +283,19 @@ export enum TechTile { Ship0 = "tech-ship0", Ship1 = "tech-ship1", Ship2 = "tech-ship2", - Ship3 = "tech-ship3" + Ship3 = "tech-ship3", } export namespace TechTile { export function values(expansions = 0): TechTile[] { return (Object.values(TechTile) as TechTile[]).filter((val: TechTile) => { - if (typeof val !== "string") {return; } + if (typeof val !== "string") { + return; + } if (/^tech[0-9]/.test(val)) { return true; } - if (expansions & Expansion.Spaceships && val.startsWith('tech-ship') && val !== TechTile.Ship0) { + if (expansions & Expansion.Spaceships && val.startsWith("tech-ship") && val !== TechTile.Ship0) { return true; } }) as TechTile[]; @@ -300,7 +315,7 @@ export enum TechTilePos { Free2 = "free2", Free3 = "free3", Free4 = "free4", - BasicShip = "move" + BasicShip = "move", } export namespace TechTilePos { @@ -316,37 +331,39 @@ export namespace TechTilePos { } export enum AdvTechTile { - AdvTech1= "advtech1", - AdvTech2= "advtech2", - AdvTech3= "advtech3", - AdvTech4= "advtech4", - AdvTech5= "advtech5", - AdvTech6= "advtech6", - AdvTech7= "advtech7", - AdvTech8= "advtech8", - AdvTech9= "advtech9", - AdvTech10= "advtech10", - AdvTech11= "advtech11", - AdvTech12= "advtech12", - AdvTech13= "advtech13", - AdvTech14= "advtech14", - AdvTech15= "advtech15", + AdvTech1 = "advtech1", + AdvTech2 = "advtech2", + AdvTech3 = "advtech3", + AdvTech4 = "advtech4", + AdvTech5 = "advtech5", + AdvTech6 = "advtech6", + AdvTech7 = "advtech7", + AdvTech8 = "advtech8", + AdvTech9 = "advtech9", + AdvTech10 = "advtech10", + AdvTech11 = "advtech11", + AdvTech12 = "advtech12", + AdvTech13 = "advtech13", + AdvTech14 = "advtech14", + AdvTech15 = "advtech15", Ship1 = "advship1", Ship2 = "advship2", Ship3 = "advship3", Ship4 = "advship4", Ship5 = "advship5", - Ship6 = "advship6" + Ship6 = "advship6", } export namespace AdvTechTile { export function values(expansions = 0): AdvTechTile[] { return (Object.values(AdvTechTile) as AdvTechTile[]).filter((val: AdvTechTile) => { - if (typeof val !== "string") {return; } - if (val.startsWith('advtech')) { + if (typeof val !== "string") { + return; + } + if (val.startsWith("advtech")) { return true; } - if (expansions & Expansion.Spaceships && val.startsWith('advship')) { + if (expansions & Expansion.Spaceships && val.startsWith("advship")) { return true; } }) as AdvTechTile[]; @@ -361,7 +378,7 @@ export enum AdvTechTilePos { Economy = "adv-eco", Science = "adv-sci", TradingBonus = "adv-trade", - TradingVolume = "adv-ship" + TradingVolume = "adv-ship", } export namespace AdvTechTilePos { @@ -384,7 +401,7 @@ export enum Federation { Fed5 = "fed5", Fed6 = "fed6", Gleens = "gleens", - Ship = "ship" + Ship = "ship", } export namespace Federation { @@ -394,26 +411,28 @@ export namespace Federation { } export enum BoardAction { - Power1= "power1", - Power2= "power2", - Power3= "power3", - Power4= "power4", - Power5= "power5", - Power6= "power6", - Power7= "power7", + Power1 = "power1", + Power2 = "power2", + Power3 = "power3", + Power4 = "power4", + Power5 = "power5", + Power6 = "power6", + Power7 = "power7", Qic1 = "qic1", Qic2 = "qic2", Qic3 = "qic3", ShipPower1 = "power-ship1", ShipPower2 = "power-ship2", ShipPower3 = "power-ship3", - ShipQic1 = "qic-ship1" + ShipQic1 = "qic-ship1", } export namespace BoardAction { - export function values(expansions= 0): BoardAction[] { + export function values(expansions = 0): BoardAction[] { return Object.values(BoardAction).filter((val: BoardAction) => { - if (typeof val !== "string") {return; } + if (typeof val !== "string") { + return; + } if (/^qic[0-9]/.test(val) || /^power[0-9]/.test(val)) { return true; } @@ -426,28 +445,30 @@ export namespace BoardAction { } export enum ScoringTile { - Score1= "score1", - Score2= "score2", - Score3= "score3", - Score4= "score4", - Score5= "score5", - Score6= "score6", - Score7= "score7", - Score8= "score8", - Score9= "score9", - Score10= "score10", + Score1 = "score1", + Score2 = "score2", + Score3 = "score3", + Score4 = "score4", + Score5 = "score5", + Score6 = "score6", + Score7 = "score7", + Score8 = "score8", + Score9 = "score9", + Score10 = "score10", Ship1 = "score-ship1", - Ship2 = "score-ship2" + Ship2 = "score-ship2", } export namespace ScoringTile { export function values(expansions = 0): ScoringTile[] { return (Object.values(ScoringTile) as ScoringTile[]).filter((val: ScoringTile) => { - if (typeof val !== "string") {return; } + if (typeof val !== "string") { + return; + } if (/^score[0-9]/.test(val)) { return true; } - if (expansions & Expansion.Spaceships && val.startsWith('score-ship')) { + if (expansions & Expansion.Spaceships && val.startsWith("score-ship")) { return true; } }) as ScoringTile[]; @@ -455,19 +476,26 @@ export namespace ScoringTile { } export enum FinalTile { - Structure= "structure", - StructureFed= "structureFed", - PlanetType= "planetType", - Gaia= "gaia", - Sector= "sector", - Satellite= "satellite", + Structure = "structure", + StructureFed = "structureFed", + PlanetType = "planetType", + Gaia = "gaia", + Sector = "sector", + Satellite = "satellite", TradeTokens = "trade", - Culture = "culture" + Culture = "culture", } export namespace FinalTile { export function values(expansions = 0): FinalTile[] { - const ret = [FinalTile.Structure, FinalTile.StructureFed, FinalTile.PlanetType, FinalTile.Gaia, FinalTile.Sector, FinalTile.Satellite]; + const ret = [ + FinalTile.Structure, + FinalTile.StructureFed, + FinalTile.PlanetType, + FinalTile.Gaia, + FinalTile.Sector, + FinalTile.Satellite, + ]; if (expansions & Expansion.Spaceships) { ret.push(FinalTile.TradeTokens, FinalTile.Culture); @@ -481,7 +509,7 @@ export enum BrainstoneArea { Area1 = "area1", Area2 = "area2", Area3 = "area3", - Gaia = "gaia" + Gaia = "gaia", } export enum Phase { @@ -499,7 +527,7 @@ export enum Phase { RoundMove = "roundMove", RoundLeech = "roundLeech", RoundFinish = "roundFinish", - EndGame = "endGame" + EndGame = "endGame", } export enum SubPhase { @@ -520,5 +548,5 @@ export enum SubPhase { PickRewards = "pickRewards", DeliverTrade = "deliverTrade", PISwap = "swap-PI", - DowngradeLab = "down-lab" + DowngradeLab = "down-lab", } diff --git a/src/events.spec.ts b/src/events.spec.ts index 840fcb6e..2c9ae32c 100644 --- a/src/events.spec.ts +++ b/src/events.spec.ts @@ -43,7 +43,8 @@ describe("Events", () => { expect(event.condition).to.equal(Condition.None); expect(event.operator).to.equal(Operator.Activate); // tslint:disable-next-line no-unused-expression - expect(Reward.match(event.rewards, [new Reward(-1, Resource.Knowledge), new Reward(1, Resource.TemporaryRange)])).to.be.true; + expect(Reward.match(event.rewards, [new Reward(-1, Resource.Knowledge), new Reward(1, Resource.TemporaryRange)])).to + .be.true; expect(event.action().rewards).to.equal("-k,range+1"); }); @@ -58,23 +59,23 @@ describe("Events", () => { }); it("should have no condition for o,q", () => { - const event = new Event('o,q'); + const event = new Event("o,q"); expect(event.condition).to.equal(Condition.None); }); describe("toString", () => { - it ("should render properly for a non-activated event", () => { + it("should render properly for a non-activated event", () => { expect(new Event("+t").toString()).to.equal("+t"); }); - it ("should render properly for an activated event", () => { + it("should render properly for an activated event", () => { const event = new Event("=> 3t"); event.activated = true; expect(event.toString()).to.equal("=> 3t!"); }); - it ("should render properly for a pick X event", () => { + it("should render properly for a pick X event", () => { const event = new Event("a 1>> o,k"); expect(event.toString()).to.equal("a 1>> o,k"); }); diff --git a/src/events.ts b/src/events.ts index 60a9bd5b..8f508846 100644 --- a/src/events.ts +++ b/src/events.ts @@ -1,4 +1,4 @@ -import { Condition, Operator, Booster, AdvTechTilePos, Command, ResearchField, BoardAction, Faction} from "./enums"; +import { Condition, Operator, Booster, AdvTechTilePos, Command, ResearchField, BoardAction, Faction } from "./enums"; import Reward from "./reward"; function findCondition(spec: string): [Condition, string] { @@ -45,15 +45,42 @@ function findOperator(spec: string): [Operator, string, number] { if (spec.split(" ").length === 2) { const [operator, remaining] = spec.split(" "); const toPick = parseInt(operator, 10); - return [operator.slice(('' + toPick).length) as Operator, remaining, toPick]; + return [operator.slice(("" + toPick).length) as Operator, remaining, toPick]; } return [Operator.Once, spec, 0]; } -export type RoundScoring = 'round1' | 'round2' | 'round3' | 'round4' | 'round5' | 'round6'; -export type TechPos = 'tech-gaia' | 'tech-nav' | 'tech-sci' | 'tech-eco' | 'tech-terra' | 'tech-int' | 'tech-free1' | 'tech-free2' | 'tech-free2'; -export type EventSource = Booster | TechPos | AdvTechTilePos | Command.ChargePower | Command.Spend | 'final1' | 'final2' | RoundScoring | ResearchField | BoardAction | Command.ChooseIncome | Command.Build | Command.ChooseFederationTile | Command.FormFederation | Command.UpgradeResearch | Faction | Command.MoveShip | Command.Bid; +export type RoundScoring = "round1" | "round2" | "round3" | "round4" | "round5" | "round6"; +export type TechPos = + | "tech-gaia" + | "tech-nav" + | "tech-sci" + | "tech-eco" + | "tech-terra" + | "tech-int" + | "tech-free1" + | "tech-free2" + | "tech-free2"; +export type EventSource = + | Booster + | TechPos + | AdvTechTilePos + | Command.ChargePower + | Command.Spend + | "final1" + | "final2" + | RoundScoring + | ResearchField + | BoardAction + | Command.ChooseIncome + | Command.Build + | Command.ChooseFederationTile + | Command.FormFederation + | Command.UpgradeResearch + | Faction + | Command.MoveShip + | Command.Bid; export default class Event { spec: string; @@ -65,7 +92,7 @@ export default class Event { toPick = 0; activated = false; - constructor(spec: string | {spec: string; source: EventSource}, source?: EventSource) { + constructor(spec: string | { spec: string; source: EventSource }, source?: EventSource) { if (typeof spec === "object") { this.spec = spec.spec; this.source = spec.source; @@ -101,12 +128,12 @@ export default class Event { } toJSON() { - return {spec: this.toString(), source: this.source}; + return { spec: this.toString(), source: this.source }; } - action(): {rewards: string; enabled: boolean} { - const idx = this.spec.indexOf('=>'); - const ret = {rewards: this.spec.slice(idx + 2).trim(), enabled: !this.activated}; + action(): { rewards: string; enabled: boolean } { + const idx = this.spec.indexOf("=>"); + const ret = { rewards: this.spec.slice(idx + 2).trim(), enabled: !this.activated }; if (idx > 0) { ret.rewards = "-" + this.spec.slice(0, idx).trim() + "," + ret.rewards; @@ -120,6 +147,6 @@ export default class Event { } static parse(events: string[], source: EventSource): Event[] { - return events.map(ev => new Event(ev, source)); + return events.map((ev) => new Event(ev, source)); } } diff --git a/src/faction-boards/ambas.spec.ts b/src/faction-boards/ambas.spec.ts index 83de68e0..3a97072d 100644 --- a/src/faction-boards/ambas.spec.ts +++ b/src/faction-boards/ambas.spec.ts @@ -1,6 +1,6 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player } from '../enums'; +import { Player } from "../enums"; const parseMoves = Engine.parseMoves; @@ -159,7 +159,5 @@ describe("Ambas", () => { `); expect(() => new Engine([...moves, "ambas federation 3x-3,4x-1,4x-2,4x-3,5x-1 fed4."])).to.not.throw(); - }); - }); diff --git a/src/faction-boards/ambas.ts b/src/faction-boards/ambas.ts index 899da03e..52481b29 100644 --- a/src/faction-boards/ambas.ts +++ b/src/faction-boards/ambas.ts @@ -5,10 +5,10 @@ const ambas: FactionBoardRaw = { faction: Faction.Ambas, buildings: { [Building.PlanetaryInstitute]: { - income: [["+4pw", "+2t", "=> swap-PI"]] - } + income: [["+4pw", "+2t", "=> swap-PI"]], + }, }, - income: ["3k,4o,15c,q,up-nav", "+2o,k"] + income: ["3k,4o,15c,q,up-nav", "+2o,k"], }; export default ambas; diff --git a/src/faction-boards/baltaks.spec.ts b/src/faction-boards/baltaks.spec.ts index 7ed36b8d..e1150d8e 100644 --- a/src/faction-boards/baltaks.spec.ts +++ b/src/faction-boards/baltaks.spec.ts @@ -1,11 +1,11 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player } from '../enums'; +import { Player } from "../enums"; const parseMoves = Engine.parseMoves; -describe('Baltaks', () => { - it('should test ability to upgrade navigation', () => { +describe("Baltaks", () => { + it("should test ability to upgrade navigation", () => { const moves = parseMoves(` init 2 randomSeed p1 faction terrans @@ -23,7 +23,7 @@ describe('Baltaks', () => { expect(() => new Engine(moves)).to.throw(); }); - it('should test ability to use freeaction and reset on new turn', () => { + it("should test ability to use freeaction and reset on new turn", () => { const moves = parseMoves(` init 2 randomSeed p1 faction terrans diff --git a/src/faction-boards/baltaks.ts b/src/faction-boards/baltaks.ts index f21dc689..71801ad8 100644 --- a/src/faction-boards/baltaks.ts +++ b/src/faction-boards/baltaks.ts @@ -8,16 +8,16 @@ const baltaks: FactionBoardRaw = { buildings: { [Building.Academy2]: { cost: "6c,6o", - income: [["=>4c", "tech"]] - } + income: [["=>4c", "tech"]], + }, }, income: ["3k,4o,15c,up-gaia", "+o,k"], power: { - area2: 2 + area2: 2, }, handlers: { - freeActionChoice: (player: Player, pool: any[]) => pool.push(...freeActionsBaltaks) - } + freeActionChoice: (player: Player, pool: any[]) => pool.push(...freeActionsBaltaks), + }, }; export default baltaks; diff --git a/src/faction-boards/bescods.spec.ts b/src/faction-boards/bescods.spec.ts index dd3187cb..f19977e6 100644 --- a/src/faction-boards/bescods.spec.ts +++ b/src/faction-boards/bescods.spec.ts @@ -1,6 +1,6 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player, Federation } from '../enums'; +import { Player, Federation } from "../enums"; const parseMoves = Engine.parseMoves; @@ -26,7 +26,5 @@ describe("Bescods", () => { const engine1 = new Engine(moves); expect(() => engine1.move("p2 special up-lowest. up nav")).to.not.throw(); - }); }); - diff --git a/src/faction-boards/bescods.ts b/src/faction-boards/bescods.ts index 3134d145..ddab1253 100644 --- a/src/faction-boards/bescods.ts +++ b/src/faction-boards/bescods.ts @@ -8,13 +8,17 @@ const bescods: FactionBoardRaw = { income: [["+k"], ["+k"], ["+k"], ["+k"]], }, [Building.ResearchLab]: { - income: [["+3c", "tech"], ["+4c", "tech"], ["+5c", "tech"]] + income: [ + ["+3c", "tech"], + ["+4c", "tech"], + ["+5c", "tech"], + ], }, [Building.PlanetaryInstitute]: { - income: [["+4pw", "+2t"]] - } + income: [["+4pw", "+2t"]], + }, }, - income: ["k,4o,15c,q", "+o", "=> up-lowest"] + income: ["k,4o,15c,q", "+o", "=> up-lowest"], }; export default bescods; diff --git a/src/faction-boards/firaks.spec.ts b/src/faction-boards/firaks.spec.ts index aa52a008..364fd64c 100644 --- a/src/faction-boards/firaks.spec.ts +++ b/src/faction-boards/firaks.spec.ts @@ -1,12 +1,13 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player, Federation } from '../enums'; +import { Player, Federation } from "../enums"; const parseMoves = Engine.parseMoves; describe("Firaks", () => { - it ("should allow firaks to downgrade a research lab to a ts and advance research after PI", () => { - const engine = new Engine(parseMoves(` + it("should allow firaks to downgrade a research lab to a ts and advance research after PI", () => { + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction firaks p2 faction nevlas @@ -34,9 +35,9 @@ describe("Firaks", () => { p2 burn 2. spend 4t-a3 for 4k. up sci. p1 spend 1pw for 1c. spend 1q for 1o. spend 1o for 1c. build lab 3x-2. tech terra. up terra. p2 pass booster4 - `)); + `) + ); expect(() => engine.move("p1 special down-lab. build ts 3x-2. up terra.")).to.not.throw(); }); }); - diff --git a/src/faction-boards/firaks.ts b/src/faction-boards/firaks.ts index 19612102..60e59527 100644 --- a/src/faction-boards/firaks.ts +++ b/src/faction-boards/firaks.ts @@ -5,10 +5,10 @@ const firaks: FactionBoardRaw = { faction: Faction.Firaks, buildings: { [Building.PlanetaryInstitute]: { - income: [["+4pw", "+t", "=> down-lab"]] - } + income: [["+4pw", "+t", "=> down-lab"]], + }, }, - income: ["2k,3o,15c,q", "+o,2k"] + income: ["2k,3o,15c,q", "+o,2k"], }; export default firaks; diff --git a/src/faction-boards/geodens.spec.ts b/src/faction-boards/geodens.spec.ts index b48b53c4..fed5e94e 100644 --- a/src/faction-boards/geodens.spec.ts +++ b/src/faction-boards/geodens.spec.ts @@ -1,12 +1,13 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player, Federation } from '../enums'; +import { Player, Federation } from "../enums"; const parseMoves = Engine.parseMoves; describe("Geodens", () => { - it ("should grant Geodens 3 knowledge after building mine on a new planet type with PI", () => { - const engine = new Engine(parseMoves(` + it("should grant Geodens 3 knowledge after building mine on a new planet type with PI", () => { + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction geodens p2 faction terrans @@ -23,7 +24,8 @@ describe("Geodens", () => { p2 charge 1pw p2 build ts -4x-1. p1 charge 3pw - `)); + `) + ); const k = engine.player(Player.Player1).data.knowledge; @@ -32,11 +34,13 @@ describe("Geodens", () => { // Increase knowledge after building a mine on new planet type expect(engine.player(Player.Player1).data.knowledge).to.equal(k + 3); - engine.loadMoves(parseMoves(` + engine.loadMoves( + parseMoves(` p2 charge 2pw p2 up gaia. p1 burn 2. action power6. build m -2x-4 - `)); + `) + ); // Do NOT increase knowledge after building a mine on same planet type expect(engine.player(Player.Player1).data.knowledge).to.equal(k + 3); diff --git a/src/faction-boards/geodens.ts b/src/faction-boards/geodens.ts index 4b256cec..eded7b7e 100644 --- a/src/faction-boards/geodens.ts +++ b/src/faction-boards/geodens.ts @@ -19,8 +19,8 @@ const geodens: FactionBoardRaw = { } player.gainRewards([new Reward("3k")], Faction.Geodens); - } - } + }, + }, }; export default geodens; diff --git a/src/faction-boards/gleens.spec.ts b/src/faction-boards/gleens.spec.ts index 3efca493..5c09a22d 100644 --- a/src/faction-boards/gleens.spec.ts +++ b/src/faction-boards/gleens.spec.ts @@ -1,12 +1,13 @@ import { expect } from "chai"; import Engine, { EngineOptions } from "../engine"; -import { Player, Federation } from '../enums'; +import { Player, Federation } from "../enums"; const parseMoves = Engine.parseMoves; describe("gleens", () => { - it ("should grant gleens an ore instead of qic when upgrading navigation without an academy", () => { - const engine = new Engine(parseMoves(` + it("should grant gleens an ore instead of qic when upgrading navigation without an academy", () => { + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction terrans p2 faction gleens @@ -17,7 +18,8 @@ describe("gleens", () => { p2 booster booster4 p1 booster booster5 p1 build m -5x0. - `)); + `) + ); const range = engine.player(Player.Player2).data.range; @@ -49,11 +51,12 @@ describe("gleens", () => { const data = engine.player(Player.Player2).data; // tslint:disable-next-line no-unused-expression - expect(data.tiles.federations.some(fed => fed.tile === Federation.Gleens)).to.be.true; + expect(data.tiles.federations.some((fed) => fed.tile === Federation.Gleens)).to.be.true; }); - it('should grant gleens two victory points when building a mine on a gaia planet', () => { - const engine = new Engine(parseMoves(` + it("should grant gleens two victory points when building a mine on a gaia planet", () => { + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction gleens p2 faction terrans @@ -68,10 +71,11 @@ describe("gleens", () => { p1 build gf -2x3. p1 pass booster3 p2 pass booster4 - `)); + `) + ); const vp = engine.player(Player.Player1).data.victoryPoints; - engine.move('p1 build m -2x3'); + engine.move("p1 build m -2x3"); expect(engine.player(Player.Player1).data.victoryPoints).to.equal(vp + 2); }); @@ -111,10 +115,18 @@ describe("gleens", () => { const options: EngineOptions = { map: { sectors: [ - {sector : "1", rotation : 3}, {sector : "7A", rotation : 1}, {sector : "3", rotation : 5}, {sector : "4", rotation : 1}, {sector : "8", rotation : 1}, - {sector : "9", rotation : 3}, {sector : "5A", rotation : 5}, {sector : "2", rotation : 3}, {sector : "6A", rotation : 3}, {sector : "10", rotation : 2} - ] - } + { sector: "1", rotation: 3 }, + { sector: "7A", rotation: 1 }, + { sector: "3", rotation: 5 }, + { sector: "4", rotation: 1 }, + { sector: "8", rotation: 1 }, + { sector: "9", rotation: 3 }, + { sector: "5A", rotation: 5 }, + { sector: "2", rotation: 3 }, + { sector: "6A", rotation: 3 }, + { sector: "10", rotation: 2 }, + ], + }, }; expect(Engine.slowMotion(moves.slice(0, -1), options).player(Player.Player3).data.victoryPoints).to.equal(9); diff --git a/src/faction-boards/gleens.ts b/src/faction-boards/gleens.ts index c8f12916..212706e2 100644 --- a/src/faction-boards/gleens.ts +++ b/src/faction-boards/gleens.ts @@ -8,8 +8,8 @@ const gleens: FactionBoardRaw = { faction: Faction.Gleens, buildings: { [Building.PlanetaryInstitute]: { - income: [["+4pw", "+o"]] - } + income: [["+4pw", "+o"]], + }, }, income: ["3k,4o,15c,up-nav", "+o,k"], handlers: { @@ -18,8 +18,8 @@ const gleens: FactionBoardRaw = { if (hex.data.planet === Planet.Gaia) { player.gainRewards([new Reward("2vp")], Faction.Gleens); } - } - } + }, + }, }; export default gleens; diff --git a/src/faction-boards/hadsch-hallas.spec.ts b/src/faction-boards/hadsch-hallas.spec.ts index 3cf873a0..9d61166c 100644 --- a/src/faction-boards/hadsch-hallas.spec.ts +++ b/src/faction-boards/hadsch-hallas.spec.ts @@ -3,7 +3,7 @@ import Engine from "../engine"; const parseMoves = Engine.parseMoves; -describe('Hadsch Hallas', () => { +describe("Hadsch Hallas", () => { it("should grant hadsch hallas new free actions after the PI is built", () => { const moves = parseMoves(` init 2 randomSeed diff --git a/src/faction-boards/hadsch-hallas.ts b/src/faction-boards/hadsch-hallas.ts index 174cb057..632e2a00 100644 --- a/src/faction-boards/hadsch-hallas.ts +++ b/src/faction-boards/hadsch-hallas.ts @@ -7,12 +7,12 @@ const hadschHallas: FactionBoardRaw = { faction: Faction.HadschHallas, income: ["3k,4o,15c,q,up-eco", "+o,k,3c"], handlers: { - freeActionChoice: (player: Player, pool: any[]) => { - if (player.data.hasPlanetaryInstitute()) { - pool.push(...freeActionsHadschHallas); - } - } - } + freeActionChoice: (player: Player, pool: any[]) => { + if (player.data.hasPlanetaryInstitute()) { + pool.push(...freeActionsHadschHallas); + } + }, + }, }; export default hadschHallas; diff --git a/src/faction-boards/index.ts b/src/faction-boards/index.ts index e273b9f6..0b760657 100644 --- a/src/faction-boards/index.ts +++ b/src/faction-boards/index.ts @@ -13,10 +13,10 @@ import Firaks from "./firaks"; import Bescods from "./bescods"; import Nevlas from "./nevlas"; import Itars from "./itars"; -import {FactionBoard, FactionBoardRaw} from "./types"; -export {FactionBoard, FactionBoardRaw} from "./types"; +import { FactionBoard, FactionBoardRaw } from "./types"; +export { FactionBoard, FactionBoardRaw } from "./types"; -const factionBoards: {[key in Faction]: FactionBoardRaw} = { +const factionBoards: { [key in Faction]: FactionBoardRaw } = { [Faction.Terrans]: Terrans, [Faction.Lantids]: Lantids, [Faction.Xenos]: Xenos, diff --git a/src/faction-boards/itars.spec.ts b/src/faction-boards/itars.spec.ts index 1dce9ea4..18598f53 100644 --- a/src/faction-boards/itars.spec.ts +++ b/src/faction-boards/itars.spec.ts @@ -1,11 +1,11 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player } from '../enums'; +import { Player } from "../enums"; const parseMoves = Engine.parseMoves; -describe('Itars', () => { - it ("should be able to gain a tech tile and decline another after PI is built", () => { +describe("Itars", () => { + it("should be able to gain a tech tile and decline another after PI is built", () => { const moves = parseMoves(` init 2 randomSeed p1 faction terrans @@ -34,7 +34,7 @@ describe('Itars', () => { p1 build m -3x4 `); - expect (() => new Engine(moves)).to.not.throw(); + expect(() => new Engine(moves)).to.not.throw(); }); it("should autocharge when no power tokens are going to be put in area3", () => { diff --git a/src/faction-boards/itars.ts b/src/faction-boards/itars.ts index 51cbd779..9e0967b2 100644 --- a/src/faction-boards/itars.ts +++ b/src/faction-boards/itars.ts @@ -5,16 +5,16 @@ const itars: FactionBoardRaw = { faction: Faction.Itars, buildings: { [Building.Academy1]: { - income: [["+3k", "tech"]] + income: [["+3k", "tech"]], }, }, income: ["3k,5o,15c,q", "+o,k,t"], power: { - area1: 4 + area1: 4, }, handlers: { - burn: (player, amount) => player.data.power.gaia += amount - } + burn: (player, amount) => (player.data.power.gaia += amount), + }, }; export default itars; diff --git a/src/faction-boards/ivits.spec.ts b/src/faction-boards/ivits.spec.ts index d1d803dc..5b4e2660 100644 --- a/src/faction-boards/ivits.spec.ts +++ b/src/faction-boards/ivits.spec.ts @@ -1,11 +1,11 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player, Command } from '../enums'; +import { Player, Command } from "../enums"; const parseMoves = Engine.parseMoves; -describe('Ivits', () => { - it ("should be able to place a space station and use it as a starting point to build a mine", () => { +describe("Ivits", () => { + it("should be able to place a space station and use it as a starting point to build a mine", () => { const moves = parseMoves(` init 2 randomSeed2 p1 faction ivits @@ -21,10 +21,10 @@ describe('Ivits', () => { p1 build m -1x-4 `); - expect (() => new Engine(moves)).to.not.throw(); + expect(() => new Engine(moves)).to.not.throw(); }); - it ("spacestation is not discounting upgrade cost for others", () => { + it("spacestation is not discounting upgrade cost for others", () => { const moves = parseMoves(` init 2 curious-stay-2150 p1 faction nevlas @@ -63,7 +63,7 @@ describe('Ivits', () => { expect(engine.player(Player.Player1).data.credits).to.equal(credits - 6); }); - it ("should be able to build a federation using a space station and qic", () => { + it("should be able to build a federation using a space station and qic", () => { const moves = parseMoves(` init 2 randomSeed2 p1 faction ivits @@ -101,7 +101,7 @@ describe('Ivits', () => { expect(engine.player(Player.Player1).data.qics).to.equal(qic - 1 + 1); }); - it ("should be able to build a federation using using PA->4pw", () => { + it("should be able to build a federation using using PA->4pw", () => { const moves = parseMoves(` init 2 waiting-fabs-1 p1 faction baltaks @@ -202,7 +202,7 @@ describe('Ivits', () => { }); it("should have 1q after forming this federation", () => { - const engine = new Engine(almostFullGame.slice(0, -1), {advancedRules: true, noFedCheck: true}); + const engine = new Engine(almostFullGame.slice(0, -1), { advancedRules: true, noFedCheck: true }); engine.options.noFedCheck = false; @@ -212,30 +212,35 @@ describe('Ivits', () => { }); it("should place PI last even with auction", () => { - const engine = new Engine([ - "init 3 Pink-visit-2792", - "p1 faction ivits", - "p2 faction terrans", - "p3 faction gleens", - "p1 bid ivits 8", - "p2 bid ivits 11", - "p3 bid terrans 2", - "p1 bid gleens 0" - ], {auction: true, map: { - sectors: [ - {sector: "9",rotation: 0}, - {sector: "6A", rotation: 4}, - {sector: "2", rotation: 5}, - {sector: "3", rotation: 3}, - {sector: "1", rotation: 5}, - {sector: "5A", rotation: 5}, - {sector: "8", rotation: 5}, - {sector: "4", rotation: 4}, - {sector: "7A", rotation: 2}, - {sector: "10", rotation: 4} - ] + const engine = new Engine( + [ + "init 3 Pink-visit-2792", + "p1 faction ivits", + "p2 faction terrans", + "p3 faction gleens", + "p1 bid ivits 8", + "p2 bid ivits 11", + "p3 bid terrans 2", + "p1 bid gleens 0", + ], + { + auction: true, + map: { + sectors: [ + { sector: "9", rotation: 0 }, + { sector: "6A", rotation: 4 }, + { sector: "2", rotation: 5 }, + { sector: "3", rotation: 3 }, + { sector: "1", rotation: 5 }, + { sector: "5A", rotation: 5 }, + { sector: "8", rotation: 5 }, + { sector: "4", rotation: 4 }, + { sector: "7A", rotation: 2 }, + { sector: "10", rotation: 4 }, + ], + }, } - }); + ); expect(() => engine.move("ivits build PI -6x3")).to.throw(); expect(() => engine.move("gleens build m -5x7")).to.throw(); diff --git a/src/faction-boards/ivits.ts b/src/faction-boards/ivits.ts index 45adfe84..d21344bf 100644 --- a/src/faction-boards/ivits.ts +++ b/src/faction-boards/ivits.ts @@ -6,10 +6,10 @@ const ivits: FactionBoardRaw = { buildings: { [Building.PlanetaryInstitute]: { cost: "~", - income: [["+4pw", "+t", "=> space-station"]] - } + income: [["+4pw", "+t", "=> space-station"]], + }, }, - income: ["3k,4o,15c,q", "+o,k,q"] + income: ["3k,4o,15c,q", "+o,k,q"], }; export default ivits; diff --git a/src/faction-boards/lantids.spec.ts b/src/faction-boards/lantids.spec.ts index 37a87b00..381ba232 100644 --- a/src/faction-boards/lantids.spec.ts +++ b/src/faction-boards/lantids.spec.ts @@ -1,13 +1,11 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player, Building, Command, Planet, Operator } from '../enums'; - - +import { Player, Building, Command, Planet, Operator } from "../enums"; const parseMoves = Engine.parseMoves; describe("Lantids", () => { - it ("should be able to build a mine on other players' planets", () => { + it("should be able to build a mine on other players' planets", () => { const moves = parseMoves(` init 2 randomSeed p1 faction lantids @@ -26,8 +24,9 @@ describe("Lantids", () => { expect(() => new Engine(moves)).to.not.throw(); }); - it ("should gain knowledge when having a PI and building on someone else's planet", () => { - const engine = new Engine(parseMoves(` + it("should gain knowledge when having a PI and building on someone else's planet", () => { + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction lantids p2 faction xenos @@ -38,7 +37,8 @@ describe("Lantids", () => { p2 build m 1x2 p2 booster booster3 p1 booster booster7 - `)); + `) + ); engine.player(Player.Player1).data.buildings[Building.PlanetaryInstitute] = 1; const k = engine.player(Player.Player1).data.knowledge; @@ -46,8 +46,9 @@ describe("Lantids", () => { expect(engine.player(Player.Player1).data.knowledge).to.equal(k + 2); }); - it ("should gain only 1 knowledge when getting pt | vp", () => { - const engine = new Engine(parseMoves(` + it("should gain only 1 knowledge when getting pt | vp", () => { + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction lantids p2 faction hadsch-hallas @@ -66,7 +67,8 @@ describe("Lantids", () => { hadsch-hallas pass booster3 lantids build ts -4x-1. hadsch-hallas decline - `)); + `) + ); const pl = engine.player(Player.Player1); const k = pl.data.knowledge; @@ -108,7 +110,7 @@ describe("Lantids", () => { const commands = engine.generateAvailableCommands(); // tslint:disable-next-line no-unused-expression - expect(commands.some(cmd => cmd.name === Command.FormFederation)).to.be.false; + expect(commands.some((cmd) => cmd.name === Command.FormFederation)).to.be.false; }); it("should not get token income from planetary institute", () => { @@ -134,13 +136,14 @@ describe("Lantids", () => { const income = engine.player(Player.Player1).income; // tslint:disable-next-line no-unused-expression - expect(income.includes('4pw')).to.be.true; + expect(income.includes("4pw")).to.be.true; // tslint:disable-next-line no-unused-expression - expect(income.includes('t')).to.be.false; + expect(income.includes("t")).to.be.false; }); - it ("should allow to place a mine in the Lost Planet", () => { - const engine = new Engine(parseMoves(` + it("should allow to place a mine in the Lost Planet", () => { + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction lantids p2 faction ivits @@ -152,16 +155,17 @@ describe("Lantids", () => { ivits income 1t lantids build m 6B4. ivits pass booster5 - `)); - + `) + ); + const hex = engine.map.getS("1B5"); hex.data.planet = Planet.Lost; hex.data.building = Building.Mine; hex.data.player = Player.Player2; - const mines = engine.player(Player.Player1).data.buildings[Building.Mine]; + const mines = engine.player(Player.Player1).data.buildings[Building.Mine]; const events = engine.player(Player.Player1).events[Operator.Income].length; engine.move("p1 build m 1B5."); - expect(engine.player(Player.Player1).data.buildings[Building.Mine]).to.equal( mines + 1); - expect(engine.player(Player.Player1).events[Operator.Income].length).to.equal( events + 1); + expect(engine.player(Player.Player1).data.buildings[Building.Mine]).to.equal(mines + 1); + expect(engine.player(Player.Player1).events[Operator.Income].length).to.equal(events + 1); }); }); diff --git a/src/faction-boards/lantids.ts b/src/faction-boards/lantids.ts index 3eec1a02..5f944d7b 100644 --- a/src/faction-boards/lantids.ts +++ b/src/faction-boards/lantids.ts @@ -5,14 +5,14 @@ const lantids: FactionBoardRaw = { faction: Faction.Lantids, buildings: { [Building.PlanetaryInstitute]: { - income: [["+4pw"]] - } + income: [["+4pw"]], + }, }, income: ["3k,4o,13c,q", "+o,k"], power: { area1: 4, - area2: 0 - } + area2: 0, + }, }; export default lantids; diff --git a/src/faction-boards/nevlas.spec.ts b/src/faction-boards/nevlas.spec.ts index bf8f2573..b8f5c6cd 100644 --- a/src/faction-boards/nevlas.spec.ts +++ b/src/faction-boards/nevlas.spec.ts @@ -1,12 +1,13 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player } from '../enums'; +import { Player } from "../enums"; const parseMoves = Engine.parseMoves; describe("Nevlas", () => { it("should allow Nevlas to use action power using empowered tokens and free actions", () => { - const engine = new Engine(parseMoves(` + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction nevlas p2 faction gleens @@ -28,13 +29,14 @@ describe("Nevlas", () => { p2 charge 2pw p2 build ts 1x2. p1 charge 2pw - `)); + `) + ); const a3 = engine.player(Player.Player1).data.power.area3; const gaia = engine.player(Player.Player1).data.power.gaia; const know = engine.player(Player.Player1).data.knowledge; // power7 is 3 power - engine.move('p1 action power7.'); + engine.move("p1 action power7."); expect(engine.player(Player.Player1).data.power.area3).to.equal(a3 - 2); engine.move("p2 pass booster5"); @@ -44,7 +46,8 @@ describe("Nevlas", () => { }); it("should move the correct number of tokens to area 1", () => { - const engine = new Engine(parseMoves(` + const engine = new Engine( + parseMoves(` init 2 randomSeed p1 faction firaks p2 faction nevlas @@ -63,7 +66,8 @@ describe("Nevlas", () => { p2 build PI -1x0. p1 charge 3pw p1 up terra. - `)); + `) + ); const area1 = engine.player(Player.Player2).data.power.area1; diff --git a/src/faction-boards/nevlas.ts b/src/faction-boards/nevlas.ts index 15098f5e..6d24c73b 100644 --- a/src/faction-boards/nevlas.ts +++ b/src/faction-boards/nevlas.ts @@ -10,19 +10,23 @@ const nevlas: FactionBoardRaw = { income: [["+3c"], ["+4c"], ["+4c"], ["+5c"]], }, [Building.ResearchLab]: { - income: [["+2pw", "tech"], ["+2pw", "tech"], ["+2pw", "tech"]] - } + income: [ + ["+2pw", "tech"], + ["+2pw", "tech"], + ["+2pw", "tech"], + ], + }, }, income: ["2k,4o,15c,q,up-sci", "+o,k"], handlers: { - [`build-${Building.PlanetaryInstitute}`]: (player: Player) => player.data.tokenModifier = 2, - freeActionChoice: (player: Player, pool: any[]) => { + [`build-${Building.PlanetaryInstitute}`]: (player: Player) => (player.data.tokenModifier = 2), + freeActionChoice: (player: Player, pool: any[]) => { pool.push(...freeActionsNevlas); if (player.data.hasPlanetaryInstitute()) { pool.push(...freeActionsNevlasPI); } - } - } + }, + }, }; export default nevlas; diff --git a/src/faction-boards/taklons.spec.ts b/src/faction-boards/taklons.spec.ts index 1eb7b9cd..1abcfddb 100644 --- a/src/faction-boards/taklons.spec.ts +++ b/src/faction-boards/taklons.spec.ts @@ -43,8 +43,12 @@ describe("Taklons", () => { p1 build ts -4x-1. `); - expect(new Engine([...moves, "p2 charge 1pw. brainstone area2"]).player(Player.Player2).data.brainstone).to.equal(BrainstoneArea.Area2); - expect(new Engine([...moves, "p2 charge 1pw. brainstone area1"]).player(Player.Player2).data.brainstone).to.equal(BrainstoneArea.Area1); + expect(new Engine([...moves, "p2 charge 1pw. brainstone area2"]).player(Player.Player2).data.brainstone).to.equal( + BrainstoneArea.Area2 + ); + expect(new Engine([...moves, "p2 charge 1pw. brainstone area1"]).player(Player.Player2).data.brainstone).to.equal( + BrainstoneArea.Area1 + ); expect(() => new Engine([...moves, "p2 charge 1pw. brainstone area3"])).to.throw(); }); diff --git a/src/faction-boards/taklons.ts b/src/faction-boards/taklons.ts index e495cc1e..453d2a07 100644 --- a/src/faction-boards/taklons.ts +++ b/src/faction-boards/taklons.ts @@ -1,6 +1,6 @@ -import { BrainstoneArea, Faction } from '../enums'; +import { BrainstoneArea, Faction } from "../enums"; export default { faction: Faction.Taklons, - brainstone: BrainstoneArea.Area1 + brainstone: BrainstoneArea.Area1, }; diff --git a/src/faction-boards/terrans.ts b/src/faction-boards/terrans.ts index f24c7756..e43cbd22 100644 --- a/src/faction-boards/terrans.ts +++ b/src/faction-boards/terrans.ts @@ -4,13 +4,13 @@ export default { faction: Faction.Terrans, income: ["3k,4o,15c,q,up-gaia", "+o,k"], power: { - area1: 4 + area1: 4, }, handlers: { - 'discardGaia': (player, amount) => player.data.power.area2 += amount, - 'gaiaPhase-beforeTokenMove': player => { + discardGaia: (player, amount) => (player.data.power.area2 += amount), + "gaiaPhase-beforeTokenMove": (player) => { player.data.power.area2 += player.data.power.gaia; player.data.power.gaia = 0; - } - } + }, + }, }; diff --git a/src/faction-boards/types.ts b/src/faction-boards/types.ts index d70a49a1..508e46ac 100644 --- a/src/faction-boards/types.ts +++ b/src/faction-boards/types.ts @@ -13,59 +13,63 @@ export interface FactionBoardRaw { cost?: string; isolatedCost?: string; income?: string[][]; - } + }; }; power?: { area1?: number; area2?: number; }; brainstone?: BrainstoneArea; - handlers?: {[event: string]: (player: Player, ...args: any[]) => any}; + handlers?: { [event: string]: (player: Player, ...args: any[]) => any }; } const defaultBoard: FactionBoardRaw = { buildings: { [Building.Mine]: { cost: "2c,o", - income: [["+o"], ["+o"], [], ["+o"], ["+o"], ["+o"], ["+o"], ["+o"]] + income: [["+o"], ["+o"], [], ["+o"], ["+o"], ["+o"], ["+o"], ["+o"]], }, [Building.TradingStation]: { cost: "3c,2o", isolatedCost: "6c,2o", - income: [["+3c"], ["+4c"], ["+4c"], ["+5c"]] + income: [["+3c"], ["+4c"], ["+4c"], ["+5c"]], }, [Building.ResearchLab]: { cost: "5c,3o", - income: [["+k", "tech"], ["+k", "tech"], ["+k", "tech"]] + income: [ + ["+k", "tech"], + ["+k", "tech"], + ["+k", "tech"], + ], }, [Building.Academy1]: { cost: "6c,6o", - income: [["+2k", "tech"]] + income: [["+2k", "tech"]], }, [Building.Academy2]: { cost: "6c,6o", - income: [["=>q", "tech"]] + income: [["=>q", "tech"]], }, [Building.PlanetaryInstitute]: { cost: "6c,4o", - income: [["+4pw", "+t"]] + income: [["+4pw", "+t"]], }, [Building.GaiaFormer]: { cost: "6t->tg", - income: [[], [], []] + income: [[], [], []], }, [Building.SpaceStation]: { cost: "~", - income: [[], [], [], [], [], []] - } + income: [[], [], [], [], [], []], + }, }, income: ["3k,4o,15c,q", "+o,k"], power: { area1: 2, - area2: 4 + area2: 4, }, brainstone: null, - handlers: {} + handlers: {}, }; export class FactionBoard { @@ -74,7 +78,7 @@ export class FactionBoard { cost: Reward[]; isolatedCost?: Reward[]; income: Event[][]; - } + }; }; income: Event[]; power: { @@ -82,26 +86,29 @@ export class FactionBoard { area2: number; }; brainstone: BrainstoneArea; - handlers?: {[event: string]: (player: Player, ...args: any[]) => any}; + handlers?: { [event: string]: (player: Player, ...args: any[]) => any }; constructor(input: FactionBoardRaw) { Object.assign(this, merge({}, defaultBoard, input)); const buildings = Object.values(Building); - const toRewards = [`${Building.TradingStation}.isolatedCost`].concat(buildings.map(bld => `${bld}.cost`)); - const toIncome = buildings.map(bld => `${bld}.income`); + const toRewards = [`${Building.TradingStation}.isolatedCost`].concat(buildings.map((bld) => `${bld}.cost`)); + const toIncome = buildings.map((bld) => `${bld}.income`); for (const toRew of toRewards) { set(this.buildings, toRew, Reward.parse(get(this.buildings, toRew))); } this.income = Event.parse(this.income as any, Command.ChooseIncome); for (const toInc of toIncome) { - set(this.buildings, toInc, get(this.buildings, toInc).map(events => Event.parse(events, Command.ChooseIncome))); + set( + this.buildings, + toInc, + get(this.buildings, toInc).map((events) => Event.parse(events, Command.ChooseIncome)) + ); } } cost(targetPlanet: Planet, building: Building, isolated = true): Reward[] { - if (building === Building.TradingStation && isolated) { return this.buildings[building].isolatedCost; } diff --git a/src/faction-boards/xenos.ts b/src/faction-boards/xenos.ts index 726a528f..55be236c 100644 --- a/src/faction-boards/xenos.ts +++ b/src/faction-boards/xenos.ts @@ -5,10 +5,10 @@ const xenos: FactionBoardRaw = { faction: Faction.Xenos, buildings: { [Building.PlanetaryInstitute]: { - income: [["+4pw", "+q"]] - } + income: [["+4pw", "+q"]], + }, }, - income: ["3k,4o,15c,q,up-int", "+o,k"] + income: ["3k,4o,15c,q,up-int", "+o,k"], }; export default xenos; diff --git a/src/factions.spec.ts b/src/factions.spec.ts index 15adf3a4..98215dc6 100644 --- a/src/factions.spec.ts +++ b/src/factions.spec.ts @@ -1,9 +1,9 @@ -import {expect} from "chai"; +import { expect } from "chai"; import factions from "./factions"; import { Faction } from "./enums"; describe("Factions", () => { - it ("lantids should be opposite terrans", () => { + it("lantids should be opposite terrans", () => { expect(factions.opposite(Faction.Terrans)).to.equal(Faction.Lantids); }); }); diff --git a/src/factions.ts b/src/factions.ts index 9de7692e..6a991798 100644 --- a/src/factions.ts +++ b/src/factions.ts @@ -1,76 +1,76 @@ -import { Faction, Planet } from './enums'; +import { Faction, Planet } from "./enums"; import Boards from "./faction-boards"; const factions = { [Faction.Terrans]: { name: "Terrans", planet: Planet.Terra, - board: Boards[Faction.Terrans] + board: Boards[Faction.Terrans], }, [Faction.Lantids]: { name: "Lantids", planet: Planet.Terra, - board: Boards[Faction.Lantids] + board: Boards[Faction.Lantids], }, [Faction.Xenos]: { name: "Xenos", planet: Planet.Desert, - board: Boards[Faction.Xenos] + board: Boards[Faction.Xenos], }, [Faction.Gleens]: { name: "Gleens", planet: Planet.Desert, - board: Boards[Faction.Gleens] + board: Boards[Faction.Gleens], }, [Faction.Taklons]: { name: "Taklons", planet: Planet.Swamp, - board: Boards[Faction.Taklons] + board: Boards[Faction.Taklons], }, [Faction.Ambas]: { name: "Ambas", planet: Planet.Swamp, - board: Boards[Faction.Ambas] + board: Boards[Faction.Ambas], }, [Faction.HadschHallas]: { name: "Hadsch Hallas", planet: Planet.Oxide, - board: Boards[Faction.HadschHallas] + board: Boards[Faction.HadschHallas], }, [Faction.Ivits]: { name: "Ivits", planet: Planet.Oxide, - board: Boards[Faction.Ivits] + board: Boards[Faction.Ivits], }, [Faction.Geodens]: { name: "Geoden", planet: Planet.Volcanic, - board: Boards[Faction.Geodens] + board: Boards[Faction.Geodens], }, [Faction.BalTaks]: { name: "Bal T'aks", planet: Planet.Volcanic, - board: Boards[Faction.BalTaks] + board: Boards[Faction.BalTaks], }, [Faction.Firaks]: { name: "Firaks", planet: Planet.Titanium, - board: Boards[Faction.Firaks] + board: Boards[Faction.Firaks], }, [Faction.Bescods]: { name: "Bescods", planet: Planet.Titanium, - board: Boards[Faction.Bescods] + board: Boards[Faction.Bescods], }, [Faction.Nevlas]: { name: "Nevlas", planet: Planet.Ice, - board: Boards[Faction.Nevlas] + board: Boards[Faction.Nevlas], }, [Faction.Itars]: { name: "Itars", planet: Planet.Ice, - board: Boards[Faction.Itars] + board: Boards[Faction.Itars], }, opposite(faction: Faction): Faction { @@ -92,7 +92,7 @@ const factions = { return fact.planet; } return Planet.Lost; - } + }, }; export default factions; diff --git a/src/federation.spec.ts b/src/federation.spec.ts index 209b0111..6bc30738 100644 --- a/src/federation.spec.ts +++ b/src/federation.spec.ts @@ -1,33 +1,37 @@ -import {expect} from "chai"; +import { expect } from "chai"; import Engine from "./engine"; import { Command } from "./enums"; describe("Federations", () => { - it("should show the 21 options with flexible federation rules", function() { + it("should show the 21 options with flexible federation rules", function () { this.timeout(10000); - const engine = new Engine(game(), {flexibleFederations: true}); + const engine = new Engine(game(), { flexibleFederations: true }); - expect(engine.findAvailableCommand(engine.playerToMove, Command.FormFederation).data.federations).to.have.length(21); + expect(engine.findAvailableCommand(engine.playerToMove, Command.FormFederation).data.federations).to.have.length( + 21 + ); }); - it("should show 9 options with regular federation rules", function() { + it("should show 9 options with regular federation rules", function () { this.timeout(30000); const engine = new Engine(game()); expect(engine.findAvailableCommand(engine.playerToMove, Command.FormFederation).data.federations).to.have.length(9); // This extra long federation should not work - expect(() => engine.move('gleens federation 0x1,0x0,0x-1,-1x-1,-1x-2,-1x-3,-2x-3,-3x-2,-3x-1,-3x0,-1x1,-2x2 fed6.')).to.throw(); + expect(() => + engine.move("gleens federation 0x1,0x0,0x-1,-1x-1,-1x-2,-1x-3,-2x-3,-3x-2,-3x-1,-3x0,-1x1,-2x2 fed6.") + ).to.throw(); }); - it("should not allow unnecessary mines if there's a PI and AC with 4pw each", function() { + it("should not allow unnecessary mines if there's a PI and AC with 4pw each", function () { this.timeout(10000); const engine = new Engine(game2.moveHistory, game2.options); - expect(() => engine.move('ambas federation -2x3,-2x2,-1x1,0x0 fed3.')).to.throw(); + expect(() => engine.move("ambas federation -2x3,-2x2,-1x1,0x0 fed3.")).to.throw(); }); - it("should force to add a mine to the federation if it means less satellites", function() { + it("should force to add a mine to the federation if it means less satellites", function () { this.timeout(10000); const engine = new Engine(game3.moveHistory, game3.options); @@ -35,18 +39,19 @@ describe("Federations", () => { expect(() => engine.move("xenos federation 5B3,5C,5A11,3A5,3B2,3B1 fed1.")).to.not.throw(); }); - it("should show a federation with only 6 satellites", function() { + it("should show a federation with only 6 satellites", function () { this.timeout(10000); - const engine = new Engine(game4.moveHistory, {advancedRules: true, auction: true}); + const engine = new Engine(game4.moveHistory, { advancedRules: true, auction: true }); engine.generateAvailableCommandsIfNeeded(); - expect(engine.availableCommands.some(command => command.name === Command.FormFederation)).to.be.true; + expect(engine.availableCommands.some((command) => command.name === Command.FormFederation)).to.be.true; }); }); -const game = () => Engine.parseMoves(` +const game = () => + Engine.parseMoves(` init 4 GaiaRocks p1 faction nevlas p2 faction hadsch-hallas @@ -323,8 +328,8 @@ const game2 = { center: { q: 0, r: 0, - s: 0 - } + s: 0, + }, }, { sector: "6B", @@ -332,8 +337,8 @@ const game2 = { center: { q: 5, r: -2, - s: -3 - } + s: -3, + }, }, { sector: "2", @@ -341,8 +346,8 @@ const game2 = { center: { q: 2, r: 3, - s: -5 - } + s: -5, + }, }, { sector: "7B", @@ -350,8 +355,8 @@ const game2 = { center: { q: -3, r: 5, - s: -2 - } + s: -2, + }, }, { sector: "4", @@ -359,8 +364,8 @@ const game2 = { center: { q: -5, r: 2, - s: 3 - } + s: 3, + }, }, { sector: "3", @@ -368,8 +373,8 @@ const game2 = { center: { q: -2, r: -3, - s: 5 - } + s: 5, + }, }, { sector: "1", @@ -377,11 +382,11 @@ const game2 = { center: { q: 3, r: -5, - s: 2 - } - } + s: 2, + }, + }, ], - } + }, }, moveHistory: [ @@ -472,8 +477,8 @@ const game2 = { "ivits federation -1x2,-2x2,-3x1,-3x2,-4x1,-5x1,-5x2,-6x3,0x2,1x2 fed5.", "ambas build ac1 -3x4. tech int. up int.", "ivits charge 2pw", - "ivits spend 1pw for 1c. special 3o." - ] + "ivits spend 1pw for 1c. special 3o.", + ], }; const game3 = { @@ -591,54 +596,54 @@ const game3 = { "baltaks up eco.", "ambas up sci.", "itars build m 5A0.", - "xenos charge 1pw" + "xenos charge 1pw", ], options: { - "map" : { - "sectors" : [ + map: { + sectors: [ { - "sector" : "1", - "rotation" : 4 + sector: "1", + rotation: 4, }, { - "sector" : "3", - "rotation" : 4 + sector: "3", + rotation: 4, }, { - "sector" : "10", - "rotation" : 5 + sector: "10", + rotation: 5, }, { - "sector" : "2", - "rotation" : 0 + sector: "2", + rotation: 0, }, { - "sector" : "7A", - "rotation" : 0 + sector: "7A", + rotation: 0, }, { - "sector" : "5A", - "rotation" : 0 + sector: "5A", + rotation: 0, }, { - "sector" : "6A", - "rotation" : 0 + sector: "6A", + rotation: 0, }, { - "sector" : "9", - "rotation" : 5 + sector: "9", + rotation: 5, }, { - "sector" : "4", - "rotation" : 4 + sector: "4", + rotation: 4, }, { - "sector" : "8", - "rotation" : 3 - } - ] - } - } + sector: "8", + rotation: 3, + }, + ], + }, + }, }; const game4 = { @@ -977,5 +982,5 @@ gleens charge 1pw itars spend 2q for 2o. build m 6A1. spend 1o for 1t. ivits pass firaks spend 4pw for 1k. federation 1A4,1B2,2A0,2A2,2B0,2B1,2B2,2B5 fed6. - `) -}; \ No newline at end of file + `), +}; diff --git a/src/federation.ts b/src/federation.ts index 63eb4ce1..a0315345 100644 --- a/src/federation.ts +++ b/src/federation.ts @@ -32,11 +32,15 @@ export function isOutclassedBy(fed: FederationInfo, comparison: FederationInfo) // We check if the federations share the same planets. // If so, and fed has more satellites, then fed is invalid // because it can be built with less satellites - const fedPlanets = fed.hexes.filter(hex => hex.hasPlanet()); - const compPlanets = comparison.hexes.filter(hex => hex.hasPlanet()); + const fedPlanets = fed.hexes.filter((hex) => hex.hasPlanet()); + const compPlanets = comparison.hexes.filter((hex) => hex.hasPlanet()); // Comp buildings included in fed buildings, & one more planet & one more satellite - if (fed.planets > comparison.planets && fed.satellites > comparison.satellites && difference(compPlanets, fedPlanets).length === 0) { + if ( + fed.planets > comparison.planets && + fed.satellites > comparison.satellites && + difference(compPlanets, fedPlanets).length === 0 + ) { return true; } diff --git a/src/gaia-hex.ts b/src/gaia-hex.ts index 43c3f7f6..4225a6ec 100644 --- a/src/gaia-hex.ts +++ b/src/gaia-hex.ts @@ -39,7 +39,7 @@ export class GaiaHex extends Hex { // into federations return []; } - return [this.data.player, this.data.additionalMine].filter(x => x !== undefined); + return [this.data.player, this.data.additionalMine].filter((x) => x !== undefined); } // Space stations do not count as colonized, gaia-formers do not count as colonized @@ -130,14 +130,14 @@ export class GaiaHex extends Hex { // Can probably math this better get relativeCoordinates() { - const horizontal = {q: -3, r: 5}; - const vertical = {q: 2, r: 3}; - const diagonal = {q: 5, r: -2}; + const horizontal = { q: -3, r: 5 }; + const vertical = { q: 2, r: 3 }; + const diagonal = { q: 5, r: -2 }; - const current = {q: this.q, r: this.r}; + const current = { q: this.q, r: this.r }; let counter = 0; - while(counter++ < 10 && magnitude(current.q, current.r) > 2) { + while (counter++ < 10 && magnitude(current.q, current.r) > 2) { for (const direction of [horizontal, vertical, diagonal]) { while (magnitude(current.q - direction.q, current.r - direction.r) < magnitude(current.q, current.r)) { current.q -= direction.q; @@ -158,7 +158,7 @@ export class GaiaHex extends Hex { const suffix = suffixes[`${relative.q}x${relative.r}`]; assert(suffix, `Can't find suffix for ${this.q}x${this.r} ${relative.q}x${relative.r}`); - return [this.data.sector.replace(/[AB]$/, ''), suffixes[`${relative.q}x${relative.r}`]].join(''); + return [this.data.sector.replace(/[AB]$/, ""), suffixes[`${relative.q}x${relative.r}`]].join(""); } } @@ -181,13 +181,13 @@ const suffixes = { "-1x0": "B3", "0x-1": "B4", "1x-1": "B5", - "0x0": "C" + "0x0": "C", }; -const reverseSuffixes = Object.keys(suffixes).reduce((acc, key) => ({...acc, [suffixes[key]]: key}), {}); +const reverseSuffixes = Object.keys(suffixes).reduce((acc, key) => ({ ...acc, [suffixes[key]]: key }), {}); export { reverseSuffixes }; -function magnitude (q: number, r: number) { - return Math.max(Math.abs(q), Math.abs(r), Math.abs(-q-r)); -} \ No newline at end of file +function magnitude(q: number, r: number) { + return Math.max(Math.abs(q), Math.abs(r), Math.abs(-q - r)); +} diff --git a/src/map.spec.ts b/src/map.spec.ts index a64134bb..43397c26 100644 --- a/src/map.spec.ts +++ b/src/map.spec.ts @@ -1,5 +1,5 @@ import SpaceMap, { MapConfiguration } from "./map"; -import Engine from './engine'; +import Engine from "./engine"; import { Hex } from "hexagrid"; import { expect } from "chai"; import { Planet } from "./enums"; @@ -14,82 +14,82 @@ describe("Map", () => { }); describe("rotateSectors", () => { - it ("should throw when rotating sectors and creating an invalid map", () => { + it("should throw when rotating sectors and creating an invalid map", () => { const moves = Engine.parseMoves(` init 2 randomSeed p2 rotate 0x0 2 `); - expect(() => new Engine(moves, {advancedRules: true})).to.throw(); + expect(() => new Engine(moves, { advancedRules: true })).to.throw(); }); - it ("should not throw when rotating sectors and creating a valid map", () => { + it("should not throw when rotating sectors and creating a valid map", () => { const moves = Engine.parseMoves(` init 2 randomSeed p2 rotate 0x0 1 `); - expect(() => new Engine(moves, {advancedRules: true})).to.not.throw(); + expect(() => new Engine(moves, { advancedRules: true })).to.not.throw(); }); }); it("should load from a configuration", () => { const conf: MapConfiguration = { sectors: [ - { sector: '3', rotation: 5 }, - { sector: '7B', rotation: 0 }, - { sector: '2', rotation: 3 }, - { sector: '5B', rotation: 2 }, - { sector: '4', rotation: 4 }, - { sector: '1', rotation: 0 }, - { sector: '6B', rotation: 5 } - ] + { sector: "3", rotation: 5 }, + { sector: "7B", rotation: 0 }, + { sector: "2", rotation: 3 }, + { sector: "5B", rotation: 2 }, + { sector: "4", rotation: 4 }, + { sector: "1", rotation: 0 }, + { sector: "6B", rotation: 5 }, + ], }; const map = new SpaceMap(); map.load(conf); - expect(map.grid.get({q: -2, r: 0}).data.sector).to.equal("5B"); - expect(map.grid.get({q: -2, r: 0}).data.planet).to.equal(Planet.Transdim); - expect(map.grid.get({q: -3, r: 1}).data.sector).to.equal("6B"); - expect(map.grid.get({q: -3, r: 1}).data.planet).to.equal(Planet.Transdim); - expect(map.grid.get({q: -4, r: 2}).data.planet).to.equal(Planet.Terra); + expect(map.grid.get({ q: -2, r: 0 }).data.sector).to.equal("5B"); + expect(map.grid.get({ q: -2, r: 0 }).data.planet).to.equal(Planet.Transdim); + expect(map.grid.get({ q: -3, r: 1 }).data.sector).to.equal("6B"); + expect(map.grid.get({ q: -3, r: 1 }).data.planet).to.equal(Planet.Transdim); + expect(map.grid.get({ q: -4, r: 2 }).data.planet).to.equal(Planet.Terra); }); it("should load from a configuration in reverse", () => { const conf: MapConfiguration = { sectors: [ - {sector: "4", rotation: 3}, - {sector: "3", rotation: 5}, - {sector: "7B", rotation: 3}, - {sector: "5B", rotation: 3}, - {sector: "6B", rotation: 4}, - {sector: "1", rotation: 0}, - {sector: "2", rotation: 3} + { sector: "4", rotation: 3 }, + { sector: "3", rotation: 5 }, + { sector: "7B", rotation: 3 }, + { sector: "5B", rotation: 3 }, + { sector: "6B", rotation: 4 }, + { sector: "1", rotation: 0 }, + { sector: "2", rotation: 3 }, ], - mirror: true + mirror: true, }; const map = new SpaceMap(); map.load(conf); - expect(map.grid.get({q: 2, r: 2}).data.planet).to.equal(Planet.Empty, "2x2 != empty"); - expect(map.grid.get({q: 3, r: 2}).data.planet).to.equal(Planet.Empty, "3x2 != empty"); - expect(map.grid.get({q: 1, r: 3}).data.planet).to.equal(Planet.Ice, "1x3 != ice"); - expect(map.grid.get({q: 3, r: 3}).data.planet).to.equal(Planet.Gaia, "3x3 != gaia"); - expect(map.grid.get({q: 3, r: 1}).data.planet).to.equal(Planet.Empty, "3x1 != empty"); - expect(map.grid.get({q: 1, r: 5}).data.planet).to.equal(Planet.Terra, "1x5 != terra"); + expect(map.grid.get({ q: 2, r: 2 }).data.planet).to.equal(Planet.Empty, "2x2 != empty"); + expect(map.grid.get({ q: 3, r: 2 }).data.planet).to.equal(Planet.Empty, "3x2 != empty"); + expect(map.grid.get({ q: 1, r: 3 }).data.planet).to.equal(Planet.Ice, "1x3 != ice"); + expect(map.grid.get({ q: 3, r: 3 }).data.planet).to.equal(Planet.Gaia, "3x3 != gaia"); + expect(map.grid.get({ q: 3, r: 1 }).data.planet).to.equal(Planet.Empty, "3x1 != empty"); + expect(map.grid.get({ q: 1, r: 5 }).data.planet).to.equal(Planet.Terra, "1x5 != terra"); }); it("withinDistance should work", () => { const map = new SpaceMap(2); - expect(map.withinDistance({q: 0, r: 0, s: 0}, 2)).to.have.length(19); + expect(map.withinDistance({ q: 0, r: 0, s: 0 }, 2)).to.have.length(19); }); - it ("should be fine with new coordinate system", () => { + it("should be fine with new coordinate system", () => { const map = new SpaceMap(4, "big"); // expect(map.grid) diff --git a/src/map.ts b/src/map.ts index f012bcd6..b523f4c8 100644 --- a/src/map.ts +++ b/src/map.ts @@ -1,39 +1,52 @@ -import {Grid, Hex, CubeCoordinates} from "hexagrid"; +import { Grid, Hex, CubeCoordinates } from "hexagrid"; import seedrandom from "seedrandom"; import shuffleSeed from "shuffle-seed"; -import assert from 'assert'; -import { keyBy } from 'lodash'; +import assert from "assert"; +import { keyBy } from "lodash"; import Sector from "./sector"; import { Player, Planet, Faction } from "./enums"; import { GaiaHex, reverseSuffixes } from "./gaia-hex"; import { EngineOptions } from "./engine"; // Data: from outer ring to inside ring, starting from top -const s1 = {name: "1", map: "eeemevoeedee,ereees,e".replace(/,/g, "")}; -const s2 = {name: "2", map: "teedemeoeeev,eieese,e".replace(/,/g, "")}; -const s3 = {name: "3", map: "meeteedreeee,eeieeg,e".replace(/,/g, "")}; -const s4 = {name: "4", map: "teeereeeeiee,oeseve,e".replace(/,/g, "")}; -const s5 = {name: "5A", map: "iemoeedveeee,eeeeeg,e".replace(/,/g, "")}; -const s5b = {name: "5B", map: "iemoeeeveeee,eeeeeg,e".replace(/,/g, "")}; -const s6 = {name: "6A", map: "emeedmeeeeee,ereges,e".replace(/,/g, "")}; -const s6b = {name: "6B", map: "emeedmeeeeee,eregee,e".replace(/,/g, "")}; -const s7 = {name: "7A", map: "eseeeeteeeme,oegege,e".replace(/,/g, "")}; -const s7b = {name: "7B", map: "eeeeeeteeeme,gesege,e".replace(/,/g, "")}; -const s8 = {name: "8", map: "remeeeemeeee,ieteve,e".replace(/,/g, "")}; -const s9 = {name: "9", map: "emieeeeeseev,eegete,e".replace(/,/g, "")}; -const s10 = {name: "10", map: "emmeeeeoreee,eegeed,e".replace(/,/g, "")}; +const s1 = { name: "1", map: "eeemevoeedee,ereees,e".replace(/,/g, "") }; +const s2 = { name: "2", map: "teedemeoeeev,eieese,e".replace(/,/g, "") }; +const s3 = { name: "3", map: "meeteedreeee,eeieeg,e".replace(/,/g, "") }; +const s4 = { name: "4", map: "teeereeeeiee,oeseve,e".replace(/,/g, "") }; +const s5 = { name: "5A", map: "iemoeedveeee,eeeeeg,e".replace(/,/g, "") }; +const s5b = { name: "5B", map: "iemoeeeveeee,eeeeeg,e".replace(/,/g, "") }; +const s6 = { name: "6A", map: "emeedmeeeeee,ereges,e".replace(/,/g, "") }; +const s6b = { name: "6B", map: "emeedmeeeeee,eregee,e".replace(/,/g, "") }; +const s7 = { name: "7A", map: "eseeeeteeeme,oegege,e".replace(/,/g, "") }; +const s7b = { name: "7B", map: "eeeeeeteeeme,gesege,e".replace(/,/g, "") }; +const s8 = { name: "8", map: "remeeeemeeee,ieteve,e".replace(/,/g, "") }; +const s9 = { name: "9", map: "emieeeeeseev,eegete,e".replace(/,/g, "") }; +const s10 = { name: "10", map: "emmeeeeoreee,eegeed,e".replace(/,/g, "") }; const sectors = keyBy([s1, s2, s3, s4, s5, s5b, s6, s6b, s7, s7b, s8, s9, s10], "name"); // Due to legacy issues const reverseSide = (side: string) => { - return side[0] + side.slice(1, 12).split("").reverse().join("") + side[12] + side.slice(13, 18).split("").reverse().join("") + side[18]; + return ( + side[0] + + side.slice(1, 12).split("").reverse().join("") + + side[12] + + side.slice(13, 18).split("").reverse().join("") + + side[18] + ); }; -const rSectors = keyBy([s1, s2, s3, s4, s5, s5b, s6, s6b, s7, s7b, s8, s9, s10].map(s => ({name: s.name, map: reverseSide(s.map)})), "name"); +const rSectors = keyBy( + [s1, s2, s3, s4, s5, s5b, s6, s6b, s7, s7b, s8, s9, s10].map((s) => ({ name: s.name, map: reverseSide(s.map) })), + "name" +); -const smallCenters = ["5x-2", "2x3", "3x-5", "0x0", "-3x5", "-2x-3", "-5x2"].map(coord => CubeCoordinates.parse(coord)); -const bigCenters = ["5x-2", "2x3", "-1x8", "3x-5", "0x0", "-3x5", "-6x10", "-2x-3", "-5x2", "-8x7"].map(coord => CubeCoordinates.parse(coord)); +const smallCenters = ["5x-2", "2x3", "3x-5", "0x0", "-3x5", "-2x-3", "-5x2"].map((coord) => + CubeCoordinates.parse(coord) +); +const bigCenters = ["5x-2", "2x3", "-1x8", "3x-5", "0x0", "-3x5", "-6x10", "-2x-3", "-5x2", "-8x7"].map((coord) => + CubeCoordinates.parse(coord) +); export interface SectorInMapConfiguration { sector: string; @@ -50,19 +63,19 @@ export interface MapConfiguration { const smallConfiguration = { sectors: [s1, s2, s3, s4, s5b, s6b, s7b], nbSectors: 7, - centers: [{q: 0, r: 0, s: 0}] + centers: [{ q: 0, r: 0, s: 0 }], }; const bigConfiguration = { sectors: [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10], nbSectors: 10, - centers: [{q: 0, r: 0, s: 0}] + centers: [{ q: 0, r: 0, s: 0 }], }; const xConfiguration = { sectors: [s1, s2, s3, s4, s5, s6, s7, s8], nbSectors: 8, - centers: [{q: 0, r: 0, s: 0}] + centers: [{ q: 0, r: 0, s: 0 }], }; // Centers of the small configuration @@ -81,7 +94,7 @@ xConfiguration.centers.splice(xConfiguration.centers.length - 1); // Big configuration: add 3 more for (let i = -1; i <= 1; i++) { const hex = new Hex(-6, 10); - hex.rotateRight(i, {q: -3, r: 5, s: -2}); + hex.rotateRight(i, { q: -3, r: 5, s: -2 }); bigConfiguration.centers.push(hex); if (i !== 0) { @@ -93,16 +106,16 @@ export default class SpaceMap { rng: seedrandom.prng; nbPlayers: number; seed: string; - layout: EngineOptions['layout']; + layout: EngineOptions["layout"]; /** * Simple array listing sectors and how they are placed. Allows to reconstruct the map with little data */ placement?: MapConfiguration; grid: Grid; // hexagrid - distanceCache: {[coord: string]: {[coord: string]: number}} = {}; + distanceCache: { [coord: string]: { [coord: string]: number } } = {}; - constructor(nbPlayers?: number, seed?: string, mirror?: boolean, layout: EngineOptions['layout'] = 'standard') { + constructor(nbPlayers?: number, seed?: string, mirror?: boolean, layout: EngineOptions["layout"] = "standard") { if (nbPlayers === undefined) { return; } @@ -113,7 +126,15 @@ export default class SpaceMap { this.layout = layout; // Keep tests valid even under new map generation rules - const germanRules = !["Gianluigi-Buffon", "randomSeed", "12", "9876", "yellow-paint-8951", "green-jeans-8458", "Fastgame01"].includes(seed); + const germanRules = ![ + "Gianluigi-Buffon", + "randomSeed", + "12", + "9876", + "yellow-paint-8951", + "green-jeans-8458", + "Fastgame01", + ].includes(seed); do { this.generate(mirror); } while (!this.isValid(germanRules)); @@ -123,10 +144,32 @@ export default class SpaceMap { const centers = conf.sectors.length === 7 ? smallCenters : bigCenters; // Legacy map generation, to keep old tests valid - const oldGen = ["Gianluigi-Buffon", "randomSeed", "12", "9876", "yellow-paint-8951", "green-jeans-8458", "Fastgame01", "zadbd", "bosco-marcuzzo3", "Alex-Del-Pieroooooo", "SGAMBATA", "djfjjv4k", "randomSeed2", "randomseed", "polite-food-8474", "green-jeans-8458", "waiting-fabs-1", "curious-stay-2150", "Three", "GaiaRocks", "SalmurOnTheBoard"].includes(this.seed); + const oldGen = [ + "Gianluigi-Buffon", + "randomSeed", + "12", + "9876", + "yellow-paint-8951", + "green-jeans-8458", + "Fastgame01", + "zadbd", + "bosco-marcuzzo3", + "Alex-Del-Pieroooooo", + "SGAMBATA", + "djfjjv4k", + "randomSeed2", + "randomseed", + "polite-food-8474", + "green-jeans-8458", + "waiting-fabs-1", + "curious-stay-2150", + "Three", + "GaiaRocks", + "SalmurOnTheBoard", + ].includes(this.seed); const [hexagon, ...hexagons] = conf.sectors.map((val: SectorInMapConfiguration, i) => { - const def = ((conf.mirror || oldGen) ? rSectors : sectors)[val.sector].map; + const def = (conf.mirror || oldGen ? rSectors : sectors)[val.sector].map; if (!val.center) { val.center = centers[i]; } @@ -147,13 +190,22 @@ export default class SpaceMap { for (const nb of this.grid.neighbours(hex)) { if (germanRules) { // German rules only forbid HOME planets from being next to each other, so gaia / transdim planets are ok - if (hex.data.planet !== Planet.Transdim && hex.data.planet !== Planet.Empty && hex.data.planet !== Planet.Gaia && hex.data.planet === nb.data.planet) { + if ( + hex.data.planet !== Planet.Transdim && + hex.data.planet !== Planet.Empty && + hex.data.planet !== Planet.Gaia && + hex.data.planet === nb.data.planet + ) { return false; } } else { // English rules are kept for backwards compatibility as most of the tests are based on them // English rules do not allow transdim/gaia planets next to each other, German rules do - if (hex.data.sector !== nb.data.sector && hex.data.planet !== Planet.Empty && hex.data.planet === nb.data.planet) { + if ( + hex.data.sector !== nb.data.sector && + hex.data.planet !== Planet.Empty && + hex.data.planet === nb.data.planet + ) { return false; } } @@ -169,24 +221,34 @@ export default class SpaceMap { const definitions = this.chooseSides(); const centers = this.configuration().centers; - this.placement = {sectors: definitions.map((side, i) => ({sector: side.name, rotation: Math.floor(this.rng() * 6), center: centers[i]})), mirror}; + this.placement = { + sectors: definitions.map((side, i) => ({ + sector: side.name, + rotation: Math.floor(this.rng() * 6), + center: centers[i], + })), + mirror, + }; this.load(this.placement); } rotateSector(center: string, times: number) { const coords = this.parse(center); - assert(this.configuration().centers.some(pt => pt.q === coords.q && pt.r === coords.r), `${center} is not the center of a sector`); + assert( + this.configuration().centers.some((pt) => pt.q === coords.q && pt.r === coords.r), + `${center} is not the center of a sector` + ); // Easy way to get coordinates of hexes in a sector - const sectorHexes = Hex.hexagon(2, {center: coords}); + const sectorHexes = Hex.hexagon(2, { center: coords }); for (const hex of sectorHexes) { this.grid.get(hex).rotateRight(times, coords); } } - chooseSides(): Array<{map: string; name: string}> { + chooseSides(): Array<{ map: string; name: string }> { const definitions = this.configuration().sectors; // Random sort of the chosen sectors, sliced return shuffleSeed.shuffle(definitions, this.rng()).slice(0, this.configuration().nbSectors); @@ -199,13 +261,13 @@ export default class SpaceMap { static fromData(data: any) { const map = new SpaceMap(); - map.grid = new Grid(...data.map(hex => new GaiaHex(hex.q, hex.r, hex.data))); + map.grid = new Grid(...data.map((hex) => new GaiaHex(hex.q, hex.r, hex.data))); return map; } configuration() { - if (this.layout === 'xshape') { + if (this.layout === "xshape") { return xConfiguration; } return SpaceMap.configuration(this.nbPlayers); @@ -231,7 +293,7 @@ export default class SpaceMap { } withinDistance(center: CubeCoordinates, distance: number): GaiaHex[] { - const group = GaiaHex.hexagon(distance, {center}); + const group = GaiaHex.hexagon(distance, { center }); const ret: GaiaHex[] = []; for (const hex of group) { @@ -289,17 +351,17 @@ export default class SpaceMap { const relative = CubeCoordinates.parse(reverseSuffixes[suffix]); - let center = this.placement!.sectors!.find(conf => conf.sector.replace(/[AB]/, '') === sector).center!; + let center = this.placement!.sectors!.find((conf) => conf.sector.replace(/[AB]/, "") === sector).center!; if (!center) { - const index = this.placement!.sectors!.findIndex(conf => conf.sector.replace(/[AB]/, '') === sector); + const index = this.placement!.sectors!.findIndex((conf) => conf.sector.replace(/[AB]/, "") === sector); center = (this.placement.sectors.length === 7 ? smallCenters : bigCenters)[index]; } return { q: center.q + relative.q, r: center.r + relative.r, - s: center.s + relative.s + s: center.s + relative.s, }; } @@ -308,4 +370,4 @@ export default class SpaceMap { } } -export {smallConfiguration, bigConfiguration}; +export { smallConfiguration, bigConfiguration }; diff --git a/src/planets.ts b/src/planets.ts index 23b40ba3..d84022f4 100644 --- a/src/planets.ts +++ b/src/planets.ts @@ -1,13 +1,21 @@ import { Planet } from "./enums"; export function terraformingStepsRequired(factionPlanet: Planet, targetPlanet: Planet): number { - const planetCycle = [ Planet.Terra, Planet.Oxide, Planet.Volcanic, Planet.Desert, Planet.Swamp, Planet.Titanium, Planet.Ice]; + const planetCycle = [ + Planet.Terra, + Planet.Oxide, + Planet.Volcanic, + Planet.Desert, + Planet.Swamp, + Planet.Titanium, + Planet.Ice, + ]; - if ( targetPlanet === Planet.Gaia || targetPlanet === Planet.Transdim) { + if (targetPlanet === Planet.Gaia || targetPlanet === Planet.Transdim) { return 0; } - let dist = planetCycle.findIndex(pc => pc === targetPlanet) - planetCycle.findIndex(pc => pc === factionPlanet); + let dist = planetCycle.findIndex((pc) => pc === targetPlanet) - planetCycle.findIndex((pc) => pc === factionPlanet); if (dist > 3) { dist -= 7; } else if (dist < -3) { @@ -28,5 +36,5 @@ export const planetNames = { [Planet.Terra]: "terra", [Planet.Titanium]: "titanium", [Planet.Transdim]: "transdim", - [Planet.Volcanic]: "volcanic" + [Planet.Volcanic]: "volcanic", }; diff --git a/src/player-data.spec.ts b/src/player-data.spec.ts index f62c550e..e33cd42c 100644 --- a/src/player-data.spec.ts +++ b/src/player-data.spec.ts @@ -1,17 +1,17 @@ -import {expect} from "chai"; -import 'mocha'; +import { expect } from "chai"; +import "mocha"; import PlayerData from "./player-data"; import { Resource, BrainstoneArea } from "./enums"; describe("PlayerData", () => { - it('should export to JSON', () => { + it("should export to JSON", () => { const data = new PlayerData(); expect(data.toJSON()).to.be.an.instanceof(Object); }); describe("discardPower", () => { - it ("should remove power tokens from power areas", () => { + it("should remove power tokens from power areas", () => { const data = new PlayerData(); data.power.area1 = 4; data.power.area2 = 4; @@ -26,7 +26,7 @@ describe("PlayerData", () => { }); describe("discardPower with brainstone in play", () => { - it ("should remove power tokens from power areas and brainstone", () => { + it("should remove power tokens from power areas and brainstone", () => { const data = new PlayerData(); data.power.area1 = 4; data.power.area2 = 1; @@ -42,7 +42,7 @@ describe("PlayerData", () => { }); describe("burn Power", () => { - it ("should remove power tokens from power areas 2 to power area 3", () => { + it("should remove power tokens from power areas 2 to power area 3", () => { const data = new PlayerData(); data.power.area1 = 4; data.power.area2 = 4; @@ -56,7 +56,7 @@ describe("PlayerData", () => { }); describe("charge Power with brainstone", () => { - it ("should move power tokens from power area 1 to power area 3 and brainstone from area 2 to 3", () => { + it("should move power tokens from power area 1 to power area 3 and brainstone from area 2 to 3", () => { const data = new PlayerData(); data.power.area1 = 2; data.power.area2 = 1; diff --git a/src/player-data.ts b/src/player-data.ts index 360f6f38..8155b83e 100644 --- a/src/player-data.ts +++ b/src/player-data.ts @@ -1,8 +1,21 @@ import Reward from "./reward"; import { GaiaHex } from "./gaia-hex"; -import { ResearchField, Building, Booster, TechTile, AdvTechTile, Federation, Resource, BrainstoneArea, TechTilePos, AdvTechTilePos, Command, Expansion } from "./enums"; +import { + ResearchField, + Building, + Booster, + TechTile, + AdvTechTile, + Federation, + Resource, + BrainstoneArea, + TechTilePos, + AdvTechTilePos, + Command, + Expansion, +} from "./enums"; import { EventEmitter } from "eventemitter3"; -import { EventSource } from './events'; +import { EventSource } from "./events"; import { fromPairs, cloneDeep } from "lodash"; import { lastTile } from "./research-tracks"; @@ -33,19 +46,26 @@ export default class PlayerData extends EventEmitter { area1: 0, area2: 0, area3: 0, - gaia: 0 + gaia: 0, }; brainstone: BrainstoneArea = null; buildings: { - [key in Building]: number - } = fromPairs(Object.values(Building).map(bld => [bld, 0])) as any; + [key in Building]: number; + } = fromPairs(Object.values(Building).map((bld) => [bld, 0])) as any; satellites = 0; research: { - [key in ResearchField]: number + [key in ResearchField]: number; } = { - terra: 0, nav: 0, int: 0, gaia: 0, eco: 0, sci: 0, trade: 0, ship: 0 + terra: 0, + nav: 0, + int: 0, + gaia: 0, + eco: 0, + sci: 0, + trade: 0, + ship: 0, }; range = 1; shipRange = 0; @@ -58,12 +78,12 @@ export default class PlayerData extends EventEmitter { tiles: { booster: Booster; - techs: Array<{ tile: TechTile | AdvTechTile; pos: TechTilePos | AdvTechTilePos; enabled: boolean}>; - federations: Array<{tile: Federation; green: boolean}>; + techs: Array<{ tile: TechTile | AdvTechTile; pos: TechTilePos | AdvTechTilePos; enabled: boolean }>; + federations: Array<{ tile: Federation; green: boolean }>; } = { booster: null, techs: [], - federations: [] + federations: [], }; /** Number of federations built (used for ivits) */ @@ -92,8 +112,7 @@ export default class PlayerData extends EventEmitter { canUpgradeResearch = true; turns = 0; // when picking rewards - toPick: {rewards: Reward[]; count: number; source: EventSource} = undefined; - + toPick: { rewards: Reward[]; count: number; source: EventSource } = undefined; toJSON(): Record { const ret = { @@ -124,7 +143,7 @@ export default class PlayerData extends EventEmitter { tradeTokens: this.tradeTokens, wildTradeTokens: this.wildTradeTokens, advancedShips: this.advancedShips, - autoChargePower: this.autoChargePower + autoChargePower: this.autoChargePower, }; return ret; @@ -142,7 +161,7 @@ export default class PlayerData extends EventEmitter { } gainRewards(rewards: Reward[], forced = false, source?: EventSource) { - if (!forced && this.brainstone && rewards.some(rew => rew.type === Resource.ChargePower)) { + if (!forced && this.brainstone && rewards.some((rew) => rew.type === Resource.ChargePower)) { // We need to do something about the brainstone const [cloneHeuristic, cloneNoHeuristic] = [this.clone(), this.clone()]; cloneHeuristic.followBrainStoneHeuristics = true; @@ -155,7 +174,7 @@ export default class PlayerData extends EventEmitter { // The brainstone can end up in two different places. if (this.brainstoneDest === undefined) { // Interrupt by asking player where to put the brainstone - this.emit('brainstone', [cloneHeuristic.brainstone, cloneNoHeuristic.brainstone]); + this.emit("brainstone", [cloneHeuristic.brainstone, cloneNoHeuristic.brainstone]); } this.followBrainStoneHeuristics = this.brainstoneDest === cloneHeuristic.brainstone; @@ -192,28 +211,72 @@ export default class PlayerData extends EventEmitter { } switch (resource) { - case Resource.Ore: this.ores = Math.min(MAX_ORE, this.ores + count); break; - case Resource.Credit: this.credits = Math.min(MAX_CREDIT, this.credits + count); break; - case Resource.Knowledge: this.knowledge = Math.min(MAX_KNOWLEDGE, this.knowledge + count); break; - case Resource.SpaceShip: count = Math.min(count, MAX_SHIP + this.advancedShips - this.ships); break; - case Resource.VictoryPoint: this.victoryPoints += count; break; - case Resource.Qic: this.qics += count; break; - case Resource.GainToken: count > 0 ? this.power.area1 += count : this.discardPower(-count); break; - case Resource.GainTokenGaiaArea: count > 0 ? this.chargeGaiaPower(count) : this.discardGaiaPower(-count); break; - case Resource.MoveTokenToGaiaArea: this.movePowerToGaia(-count); break; - case Resource.ChargePower: count > 0 ? this.chargePower(count) : this.spendPower(-count); break; - case Resource.Range: this.range += count; break; - case Resource.TemporaryRange: this.temporaryRange += count; break; - case Resource.SpaceShipRange: this.shipRange += 1; break; - case Resource.SpaceShipMove: this.movingShips += 1; break; - case Resource.GaiaFormer: count > 0 ? this.gaiaformers += count : this.gaiaformersInGaia -= count; break; - case Resource.TerraformCostDiscount: this.terraformCostDiscount += count; break; - case Resource.TemporaryStep: this.temporaryStep += count; break; - case Resource.TokenArea3: if (count < 0) { this.power.area3 += count; this.power.gaia -= count; } break; - case Resource.AdvancedSpaceShip: this.advancedShips += count; break; - case Resource.Turn: this.turns += count; break; + case Resource.Ore: + this.ores = Math.min(MAX_ORE, this.ores + count); + break; + case Resource.Credit: + this.credits = Math.min(MAX_CREDIT, this.credits + count); + break; + case Resource.Knowledge: + this.knowledge = Math.min(MAX_KNOWLEDGE, this.knowledge + count); + break; + case Resource.SpaceShip: + count = Math.min(count, MAX_SHIP + this.advancedShips - this.ships); + break; + case Resource.VictoryPoint: + this.victoryPoints += count; + break; + case Resource.Qic: + this.qics += count; + break; + case Resource.GainToken: + count > 0 ? (this.power.area1 += count) : this.discardPower(-count); + break; + case Resource.GainTokenGaiaArea: + count > 0 ? this.chargeGaiaPower(count) : this.discardGaiaPower(-count); + break; + case Resource.MoveTokenToGaiaArea: + this.movePowerToGaia(-count); + break; + case Resource.ChargePower: + count > 0 ? this.chargePower(count) : this.spendPower(-count); + break; + case Resource.Range: + this.range += count; + break; + case Resource.TemporaryRange: + this.temporaryRange += count; + break; + case Resource.SpaceShipRange: + this.shipRange += 1; + break; + case Resource.SpaceShipMove: + this.movingShips += 1; + break; + case Resource.GaiaFormer: + count > 0 ? (this.gaiaformers += count) : (this.gaiaformersInGaia -= count); + break; + case Resource.TerraformCostDiscount: + this.terraformCostDiscount += count; + break; + case Resource.TemporaryStep: + this.temporaryStep += count; + break; + case Resource.TokenArea3: + if (count < 0) { + this.power.area3 += count; + this.power.gaia -= count; + } + break; + case Resource.AdvancedSpaceShip: + this.advancedShips += count; + break; + case Resource.Turn: + this.turns += count; + break; - default: break; // Not implemented + default: + break; // Not implemented } if (count > 0) { @@ -228,23 +291,37 @@ export default class PlayerData extends EventEmitter { } availableWildTradeTokens() { - return (this.research[ResearchField.TradingVolume] === lastTile(ResearchField.TradingVolume) ? 5 : 0) - this.wildTradeTokens; + return ( + (this.research[ResearchField.TradingVolume] === lastTile(ResearchField.TradingVolume) ? 5 : 0) - + this.wildTradeTokens + ); } hasResource(reward: Reward) { switch (reward.type) { - case Resource.Ore: return this.ores >= reward.count; - case Resource.Credit: return this.credits >= reward.count; - case Resource.Knowledge: return this.knowledge >= reward.count; - case Resource.VictoryPoint: return this.victoryPoints >= reward.count; - case Resource.Qic: return this.qics >= reward.count; - case Resource.None: return true; + case Resource.Ore: + return this.ores >= reward.count; + case Resource.Credit: + return this.credits >= reward.count; + case Resource.Knowledge: + return this.knowledge >= reward.count; + case Resource.VictoryPoint: + return this.victoryPoints >= reward.count; + case Resource.Qic: + return this.qics >= reward.count; + case Resource.None: + return true; case Resource.MoveTokenToGaiaArea: - case Resource.GainToken: return this.discardablePowerTokens() >= reward.count; - case Resource.GainTokenGaiaArea: return this.gaiaPowerTokens() >= reward.count; - case Resource.ChargePower: return this.spendablePowerTokens() >= reward.count; - case Resource.TokenArea3: return this.power.area3 >= reward.count; - case Resource.GaiaFormer: return this.gaiaformers - this.gaiaformersInGaia - this.buildings[Building.GaiaFormer] >= reward.count; + case Resource.GainToken: + return this.discardablePowerTokens() >= reward.count; + case Resource.GainTokenGaiaArea: + return this.gaiaPowerTokens() >= reward.count; + case Resource.ChargePower: + return this.spendablePowerTokens() >= reward.count; + case Resource.TokenArea3: + return this.power.area3 >= reward.count; + case Resource.GaiaFormer: + return this.gaiaformers - this.gaiaformersInGaia - this.buildings[Building.GaiaFormer] >= reward.count; } return false; @@ -289,7 +366,9 @@ export default class PlayerData extends EventEmitter { let brainstonePos = this.brainstone; // needed to avoid wrong usage of the brainstone - if (power === 0) { return 0; } + if (power === 0) { + return 0; + } if (brainstonePos === BrainstoneArea.Area1) { if (this.followBrainStoneHeuristics || this.power.area1 < power) { @@ -303,7 +382,7 @@ export default class PlayerData extends EventEmitter { power -= area1ToUp; if (brainstonePos === BrainstoneArea.Area2 && power > 0) { - if (this.followBrainStoneHeuristics || (this.power.area2 + area1ToUp) < power) { + if (this.followBrainStoneHeuristics || this.power.area2 + area1ToUp < power) { brainstoneUsage += 1; power -= 1; brainstonePos = BrainstoneArea.Area3; @@ -330,7 +409,7 @@ export default class PlayerData extends EventEmitter { if (this.power.area3 >= power) { if (this.brainstoneDest === undefined) { // Interrupt by asking player where to put the brainstone - this.emit('brainstone', [BrainstoneArea.Area3, BrainstoneArea.Area1]); + this.emit("brainstone", [BrainstoneArea.Area3, BrainstoneArea.Area1]); } if (this.brainstoneDest === BrainstoneArea.Area3) { @@ -345,16 +424,19 @@ export default class PlayerData extends EventEmitter { power = Math.max(power - 3, 0); } } - this.power.area3 -= Math.ceil( power / this.tokenModifier ); - this.power.area1 += Math.ceil( power / this.tokenModifier ); + this.power.area3 -= Math.ceil(power / this.tokenModifier); + this.power.area1 += Math.ceil(power / this.tokenModifier); } tokensBelowArea(area: BrainstoneArea) { let power = 0; switch (area) { - case BrainstoneArea.Area3: power += this.power.area3; - case BrainstoneArea.Area2: power += this.power.area2; - case BrainstoneArea.Area1: power += this.power.area1; + case BrainstoneArea.Area3: + power += this.power.area3; + case BrainstoneArea.Area2: + power += this.power.area2; + case BrainstoneArea.Area1: + power += this.power.area1; } return power; } @@ -366,10 +448,10 @@ export default class PlayerData extends EventEmitter { power -= 1; } else if (this.tokensBelowArea(this.brainstone) < power) { if (this.brainstoneDest === undefined) { - this.emit("brainstone", [this.brainstone, 'discard']); + this.emit("brainstone", [this.brainstone, "discard"]); } - if (this.brainstoneDest === 'discard') { + if (this.brainstoneDest === "discard") { this.brainstone = null; power -= 1; } @@ -422,7 +504,7 @@ export default class PlayerData extends EventEmitter { discardGaiaPower(power: number) { this.power.gaia -= power; - this.emit('discardGaia', power); + this.emit("discardGaia", power); } burnablePower() { @@ -437,7 +519,7 @@ export default class PlayerData extends EventEmitter { } this.power.area2 -= 2 * power; this.power.area3 += power; - this.emit('burn', power); + this.emit("burn", power); } advanceResearch(which: ResearchField, count: number) { @@ -456,11 +538,11 @@ export default class PlayerData extends EventEmitter { } hasGreenFederation() { - return this.tiles.federations.some(fed => fed.green); + return this.tiles.federations.some((fed) => fed.green); } gaiaFormingDiscount() { - return this.gaiaformers > 1 ? this.gaiaformers : 0; + return this.gaiaformers > 1 ? this.gaiaformers : 0; } /** @@ -497,7 +579,7 @@ export default class PlayerData extends EventEmitter { removeGreenFederation() { // console.log("removing green federation..."); - this.tiles.federations.some(fed => { + this.tiles.federations.some((fed) => { if (fed.green) { fed.green = false; return true; diff --git a/src/player.spec.ts b/src/player.spec.ts index 8da2ff78..05017dc9 100644 --- a/src/player.spec.ts +++ b/src/player.spec.ts @@ -1,5 +1,5 @@ -import {expect} from "chai"; -import 'mocha'; +import { expect } from "chai"; +import "mocha"; import Player from "./player"; import { Faction, Planet, Building, Resource, Player as PlayerEnum, Operator, Command } from "./enums"; import Reward from "./reward"; @@ -13,7 +13,7 @@ describe("Player", () => { player.loadFaction(Faction.Terrans); - const {cost} = player.canBuild(Planet.Terra, Building.Mine, {addedCost: [new Reward(1, Resource.Qic)]}); + const { cost } = player.canBuild(Planet.Terra, Building.Mine, { addedCost: [new Reward(1, Resource.Qic)] }); // tslint:disable-next-line no-unused-expression expect(Reward.match(Reward.parse("2c,o,q"), cost)).to.be.true; @@ -34,7 +34,7 @@ describe("Player", () => { expect(Reward.match(player.events[Operator.Income][1].rewards, [new Reward("1c")])).to.be.true; }); - it ("should work on events that were activated", () => { + it("should work on events that were activated", () => { const player = new Player(); player.loadEvents(Event.parse(["+k", "=> 4c", "+c"], Command.ChooseIncome)); @@ -54,7 +54,7 @@ describe("Player", () => { sector: "s1", planet: Planet.Lost, player: PlayerEnum.Player2, - building: Building.Mine + building: Building.Mine, }); // tslint:disable-next-line no-unused-expression @@ -66,11 +66,13 @@ describe("Player", () => { it("should order based on type order", () => { const player = new Player(); - player.loadEvents(Event.parse([ "+t", "+k", "+c", "+o"], Command.ChooseIncome)); - const orderedEvents = Reward.toString(Reward.merge([].concat(...player.events[Operator.Income].map(event => event.rewards))), true); + player.loadEvents(Event.parse(["+t", "+k", "+c", "+o"], Command.ChooseIncome)); + const orderedEvents = Reward.toString( + Reward.merge([].concat(...player.events[Operator.Income].map((event) => event.rewards))), + true + ); expect(orderedEvents).to.be.equal("1c,1o,1k,1t"); - }); }); }); diff --git a/src/player.ts b/src/player.ts index a102b334..061d893b 100644 --- a/src/player.ts +++ b/src/player.ts @@ -1,24 +1,42 @@ -import { Faction, Operator, ResearchField, Planet, Building, Resource, Booster, Condition, Federation, FinalTile, TechTile, AdvTechTile, BrainstoneArea, TechTilePos, AdvTechTilePos, Command, TradeToken} from './enums'; -import PlayerData from './player-data'; -import Event, {EventSource, TechPos} from './events'; -import { factionBoard, FactionBoard } from './faction-boards'; +import { + Faction, + Operator, + ResearchField, + Planet, + Building, + Resource, + Booster, + Condition, + Federation, + FinalTile, + TechTile, + AdvTechTile, + BrainstoneArea, + TechTilePos, + AdvTechTilePos, + Command, + TradeToken, +} from "./enums"; +import PlayerData from "./player-data"; +import Event, { EventSource, TechPos } from "./events"; +import { factionBoard, FactionBoard } from "./faction-boards"; import { uniq, sum, difference, zipWith, merge, countBy, uniqWith } from "lodash"; -import factions from './factions'; -import Reward from './reward'; -import { CubeCoordinates, Hex, Grid } from 'hexagrid'; -import researchTracks, {lastTile, keyNeeded} from './research-tracks'; -import { terraformingStepsRequired } from './planets'; -import boosts from './tiles/boosters'; -import { Player as PlayerEnum } from './enums'; -import { stdBuildingValue } from './buildings'; -import SpaceMap from './map'; -import { GaiaHex } from './gaia-hex'; -import spanningTree from './algorithms/spanning-tree'; -import { FederationInfo, isOutclassedBy } from './federation'; +import factions from "./factions"; +import Reward from "./reward"; +import { CubeCoordinates, Hex, Grid } from "hexagrid"; +import researchTracks, { lastTile, keyNeeded } from "./research-tracks"; +import { terraformingStepsRequired } from "./planets"; +import boosts from "./tiles/boosters"; +import { Player as PlayerEnum } from "./enums"; +import { stdBuildingValue } from "./buildings"; +import SpaceMap from "./map"; +import { GaiaHex } from "./gaia-hex"; +import spanningTree from "./algorithms/spanning-tree"; +import { FederationInfo, isOutclassedBy } from "./federation"; import federationTiles, { isGreen } from "./tiles/federations"; import { EventEmitter } from "eventemitter3"; -import { finalScorings } from './tiles/scoring'; -import techs, { isAdvanced } from './tiles/techs'; +import { finalScorings } from "./tiles/scoring"; +import techs, { isAdvanced } from "./tiles/techs"; import assert from "assert"; const TERRAFORMING_COST = 3; @@ -44,7 +62,7 @@ export default class Player extends EventEmitter { [Operator.Activate]: [], [Operator.Pass]: [], [Operator.Special]: [], - [Operator.AdvShip4]: [] + [Operator.AdvShip4]: [], }; // To avoid recalculating federations every time federationCache: FederationCache; @@ -57,15 +75,18 @@ export default class Player extends EventEmitter { constructor(public player: PlayerEnum = PlayerEnum.Player1) { super(); - this.data.on('advance-research', (track, dest) => this.onResearchAdvanced(track, dest)); + this.data.on("advance-research", (track, dest) => this.onResearchAdvanced(track, dest)); } get income() { - return Reward.toString(Reward.merge([].concat(...this.events[Operator.Income].map(event => event.rewards))), true); + return Reward.toString( + Reward.merge([].concat(...this.events[Operator.Income].map((event) => event.rewards))), + true + ); } get actions() { - return this.events[Operator.Activate].map(event => event.action()); + return this.events[Operator.Activate].map((event) => event.action()); } progress(finalTile: FinalTile) { @@ -81,7 +102,7 @@ export default class Player extends EventEmitter { } get ownedPlanetsCount() { - return countBy(this.ownedPlanets, 'data.planet'); + return countBy(this.ownedPlanets, "data.planet"); } toJSON() { @@ -91,17 +112,17 @@ export default class Player extends EventEmitter { data: this.data, events: this.events, name: this.name, - dropped: this.dropped + dropped: this.dropped, } as any; if (this.federationCache) { json.federationCache = { availableSatellites: this.federationCache.availableSatellites, - federations: this.federationCache.federations.map(fedInfo => ({ + federations: this.federationCache.federations.map((fedInfo) => ({ planets: fedInfo.planets, satellites: fedInfo.satellites, - hexes: fedInfo.hexes.map(h => h.toString()) - })) + hexes: fedInfo.hexes.map((h) => h.toString()), + })), }; } @@ -116,7 +137,7 @@ export default class Player extends EventEmitter { } for (const kind of Object.keys(data.events)) { - player.events[kind] = data.events[kind].map(ev => new Event(ev)); + player.events[kind] = data.events[kind].map((ev) => new Event(ev)); } player.name = data.name; @@ -125,7 +146,7 @@ export default class Player extends EventEmitter { if (data.federationCache) { player.federationCache = data.federationCache; for (const fed of player.federationCache.federations) { - fed.hexes = (fed.hexes as any as string[]).map(hex => map.getS(hex)); + fed.hexes = ((fed.hexes as any) as string[]).map((hex) => map.getS(hex)); } } @@ -156,10 +177,14 @@ export default class Player extends EventEmitter { gainRewards(rewards: Reward[], source: EventSource, toPick = 0) { if (toPick) { - this.data.toPick = {count: toPick, rewards: [...rewards], source}; + this.data.toPick = { count: toPick, rewards: [...rewards], source }; this.emit("pick-rewards"); } else { - this.data.gainRewards(rewards.map(rew => this.factionReward(rew)), false, source); + this.data.gainRewards( + rewards.map((rew) => this.factionReward(rew)), + false, + source + ); } } @@ -179,17 +204,25 @@ export default class Player extends EventEmitter { for (let max = 0; ; max += 1) { for (const rew of rewards) { - if (!this.data.hasResource(new Reward( rew.count * (max + 1), rew.type ))) { + if (!this.data.hasResource(new Reward(rew.count * (max + 1), rew.type))) { return max; } } } } - canBuild(targetPlanet: Planet, building: Building, {isolated, addedCost, existingBuilding}: {isolated?: boolean; addedCost?: Reward[]; existingBuilding?: Building} = {}): {cost?: Reward[]; possible: boolean; steps?: number} { + canBuild( + targetPlanet: Planet, + building: Building, + { + isolated, + addedCost, + existingBuilding, + }: { isolated?: boolean; addedCost?: Reward[]; existingBuilding?: Building } = {} + ): { cost?: Reward[]; possible: boolean; steps?: number } { if (this.data.buildings[building] >= this.maxBuildings(building)) { // Too many buildings of the same kind - return {possible: false}; + return { possible: false }; } if (!addedCost) { @@ -197,7 +230,7 @@ export default class Player extends EventEmitter { } if (!this.canPay(addedCost)) { - return {possible: false}; + return { possible: false }; } let steps = 0; @@ -214,30 +247,38 @@ export default class Player extends EventEmitter { } else { // Already a gaia-former on the planet, so no need to pay a Q.I.C. } - } else { // Get the number of terraforming steps to pay discounting terraforming track + } else { + // Get the number of terraforming steps to pay discounting terraforming track steps = terraformingStepsRequired(factions[this.faction].planet, targetPlanet); - addedCost.push(new Reward((TERRAFORMING_COST - this.data.terraformCostDiscount) * Math.max(steps - this.data.temporaryStep, 0), Resource.Ore)); + addedCost.push( + new Reward( + (TERRAFORMING_COST - this.data.terraformCostDiscount) * Math.max(steps - this.data.temporaryStep, 0), + Resource.Ore + ) + ); } } const cost = Reward.merge(this.board.cost(targetPlanet, building, isolated), addedCost); if (!this.canPay(cost)) { - return {possible: false}; + return { possible: false }; } return { possible: true, cost, - steps + steps, }; } maxBuildings(building: Building) { - return building === Building.GaiaFormer ? (this.data.gaiaformers - this.data.gaiaformersInGaia) : this.board.buildings[building].income.length; + return building === Building.GaiaFormer + ? this.data.gaiaformers - this.data.gaiaformersInGaia + : this.board.buildings[building].income.length; } get ownedPlanets(): GaiaHex[] { - return this.data.occupied.filter(hex => hex.data.planet !== Planet.Empty && hex.isMainOccupier(this.player)); + return this.data.occupied.filter((hex) => hex.data.planet !== Planet.Empty && hex.isMainOccupier(this.player)); } loadFaction(faction: Faction, expansions: number, skipIncome = false) { @@ -282,7 +323,11 @@ export default class Player extends EventEmitter { if (event.operator === Operator.Once) { const times = this.eventConditionCount(event.condition); - this.gainRewards(event.rewards.map(reward => new Reward(reward.count * times, reward.type)), event.source, event.toPick); + this.gainRewards( + event.rewards.map((reward) => new Reward(reward.count * times, reward.type)), + event.source, + event.toPick + ); } else if (event.operator === Operator.AdvShip4) { const nShips = this.data.shipLocations.length; this.data.shipRange += 4; @@ -305,11 +350,11 @@ export default class Player extends EventEmitter { removeEvent(event: Event) { // First try same source & same definition - let index = this.events[event.operator].findIndex(ev => ev.spec === event.spec && ev.source === event.source); + let index = this.events[event.operator].findIndex((ev) => ev.spec === event.spec && ev.source === event.source); // Then try just same definition if (index === -1) { - index = this.events[event.operator].findIndex(ev => ev.spec === event.spec); + index = this.events[event.operator].findIndex((ev) => ev.spec === event.spec); } if (index !== -1) { @@ -320,9 +365,11 @@ export default class Player extends EventEmitter { } } - removeRoundBoosterEvents( type?: Operator.Income) { + removeRoundBoosterEvents(type?: Operator.Income) { let eventList = Event.parse(boosts[this.data.tiles.booster], this.data.tiles.booster); - eventList = eventList.filter( ev => (type && ev.operator === Operator.Income ) || ( !type && ev.operator !== Operator.Income )); + eventList = eventList.filter( + (ev) => (type && ev.operator === Operator.Income) || (!type && ev.operator !== Operator.Income) + ); for (const event of eventList) { this.removeEvent(event); @@ -343,8 +390,10 @@ export default class Player extends EventEmitter { // this is managing Income phase to solve +t and +pw ordering // it's assuming that each reward belongs to a different event, which has only that reward // in case of multiple matchings pick the first - for ( const rew of rewards) { - const event = this.events[Operator.Income].find(ev => !ev.activated && ev.rewards.some(rew2 => Reward.match([rew], [rew2]))); + for (const rew of rewards) { + const event = this.events[Operator.Income].find( + (ev) => !ev.activated && ev.rewards.some((rew2) => Reward.match([rew], [rew2])) + ); assert(event); @@ -353,7 +402,6 @@ export default class Player extends EventEmitter { } } - /** * Second parameter is necessary in case someone advances research mutliple times in one go, we don't * want to remove multiple green federations for one track @@ -384,11 +432,10 @@ export default class Player extends EventEmitter { this.federationCache = null; } - if (this.federationCache) { assert(wasOccupied, "logic error"); - if (this.buildingValue(hex, {federation: true}) === this.buildingValue(hex, {federation: true, building})) { + if (this.buildingValue(hex, { federation: true }) === this.buildingValue(hex, { federation: true, building })) { // No need to clear federation cache, when the building value remains the same } else if (!hex.belongsToFederationOf(this.player)) { this.federationCache = null; @@ -436,7 +483,7 @@ export default class Player extends EventEmitter { // Add to nearby federation if (building !== Building.GaiaFormer && !hex.belongsToFederationOf(this.player)) { const group: GaiaHex[] = this.buildingGroup(hex, map); - const hasFederation = map.grid.neighbours(hex).some(hx => hx.belongsToFederationOf(this.player)); + const hasFederation = map.grid.neighbours(hex).some((hx) => hx.belongsToFederationOf(this.player)); if (hasFederation) { for (const h of group) { @@ -493,12 +540,12 @@ export default class Player extends EventEmitter { this.receivePassIncome(); // remove the remaing reward of the round booster events this.removeRoundBoosterEvents(); - this.data.tiles.booster = undefined; + this.data.tiles.booster = undefined; } getRoundBooster(roundBooster: Booster) { // add the booster to the the player - this.data.tiles.booster = roundBooster; + this.data.tiles.booster = roundBooster; this.loadEvents(Event.parse(boosts[roundBooster], roundBooster)); } @@ -507,34 +554,36 @@ export default class Player extends EventEmitter { if (advanced) { this.data.removeGreenFederation(); } - this.data.tiles.techs.push({tile, pos, enabled: true}); - this.loadEvents(Event.parse(techs[tile], !advanced ? `tech-${pos}` as TechPos : pos as AdvTechTilePos)); + this.data.tiles.techs.push({ tile, pos, enabled: true }); + this.loadEvents(Event.parse(techs[tile], !advanced ? (`tech-${pos}` as TechPos) : (pos as AdvTechTilePos))); // resets federationCache if Special PA->4pw - if ( tile === TechTile.Tech3 ) { this.federationCache = null; } + if (tile === TechTile.Tech3) { + this.federationCache = null; + } } coverTechTile(pos: TechTilePos) { - const tile = this.data.tiles.techs.find(tech => tech.pos === pos); + const tile = this.data.tiles.techs.find((tech) => tech.pos === pos); tile.enabled = false; this.removeEvents(Event.parse(techs[tile.tile], `tech-${pos}` as TechPos)); } - needIncomeSelection(): { events?: Event[]; needed: boolean; descs: Reward[]} { + needIncomeSelection(): { events?: Event[]; needed: boolean; descs: Reward[] } { // we need to check if rewards contains Resource.GainToken and Resource.GainPower // player has to select the order - const allEvents = this.events[Operator.Income].filter( ev => !ev.activated); + const allEvents = this.events[Operator.Income].filter((ev) => !ev.activated); - const gainTokens = allEvents.filter(ev => ev.rewards.some(rw => rw.type === Resource.GainToken)); - const chargePowers = allEvents.filter(ev => ev.rewards.some(rw => rw.type === Resource.ChargePower)); + const gainTokens = allEvents.filter((ev) => ev.rewards.some((rw) => rw.type === Resource.GainToken)); + const chargePowers = allEvents.filter((ev) => ev.rewards.some((rw) => rw.type === Resource.ChargePower)); return { events: gainTokens.concat(chargePowers), needed: gainTokens.length > 0 && chargePowers.length > 0, descs: [ - ... gainTokens.map(ev => ev.rewards.find(rw => rw.type === Resource.GainToken)), - ... chargePowers.map(ev => ev.rewards.find(rw => rw.type === Resource.ChargePower)) - ] + ...gainTokens.map((ev) => ev.rewards.find((rw) => rw.type === Resource.GainToken)), + ...chargePowers.map((ev) => ev.rewards.find((rw) => rw.type === Resource.ChargePower)), + ], }; } @@ -572,7 +621,7 @@ export default class Player extends EventEmitter { if (!event.activated) { // Taklons + brainstone need to not activate the event until the reward is gained... // This is UGLY. Maybe a better handling of placing ships in income phase would avoid this hack - if (!event.rewards.some(rew => rew.type === Resource.ChargePower)) { + if (!event.rewards.some((rew) => rew.type === Resource.ChargePower)) { event.activated = true; // before next line, in case it trigger events (like placing ship) } this.gainRewards(event.rewards, event.source); @@ -591,7 +640,10 @@ export default class Player extends EventEmitter { // this is for pass tile income (e.g. rounboosters, adv tiles) for (const event of this.events[Operator.Pass]) { const times = this.eventConditionCount(event.condition); - this.gainRewards(event.rewards.map(reward => new Reward(reward.count * times, reward.type)), event.source); + this.gainRewards( + event.rewards.map((reward) => new Reward(reward.count * times, reward.type)), + event.source + ); } } @@ -599,7 +651,10 @@ export default class Player extends EventEmitter { // this is for roundboosters, techtiles and adv tile for (const event of this.events[Operator.Trigger]) { // only new mine trigger event for Lantids in other's planet - if (Condition.matchesBuilding(event.condition, building, planet) && (!isAdditionalMine || event.condition === Condition.Mine)) { + if ( + Condition.matchesBuilding(event.condition, building, planet) && + (!isAdditionalMine || event.condition === Condition.Mine) + ) { this.gainRewards(event.rewards, event.source); } } @@ -616,7 +671,10 @@ export default class Player extends EventEmitter { receiveTerraformingStepTriggerIncome(stepsReq: number) { for (const event of this.events[Operator.Trigger]) { if (event.condition === Condition.TerraformStep) { - this.gainRewards(event.rewards.map( rw => new Reward(rw.count * stepsReq, rw.type)), event.source); + this.gainRewards( + event.rewards.map((rw) => new Reward(rw.count * stepsReq, rw.type)), + event.source + ); } } } @@ -627,10 +685,10 @@ export default class Player extends EventEmitter { gaiaPhase() { /* Move gaia power tokens to regular power areas */ - this.emit('gaiaPhase-beforeTokenMove'); + this.emit("gaiaPhase-beforeTokenMove"); this.data.power.area1 += this.data.power.gaia; - if (this.data.brainstone === BrainstoneArea.Gaia ) { + if (this.data.brainstone === BrainstoneArea.Gaia) { this.data.brainstone = BrainstoneArea.Area1; } @@ -638,7 +696,7 @@ export default class Player extends EventEmitter { this.data.gaiaformersInGaia = 0; } - buildingValue(hex: GaiaHex, options?: {federation?: boolean; building?: Building}) { + buildingValue(hex: GaiaHex, options?: { federation?: boolean; building?: Building }) { const building = options?.building ?? hex.buildingOf(this.player); const forFederation = options?.federation ?? false; @@ -646,7 +704,7 @@ export default class Player extends EventEmitter { return 1; } - let baseValue = stdBuildingValue(building); + let baseValue = stdBuildingValue(building); // Space stations and gaia-formers can't get leech when someone makes a structure nearby if (baseValue === 0) { @@ -657,14 +715,23 @@ export default class Player extends EventEmitter { baseValue = 4; } - const addedBescods = this.faction === Faction.Bescods && this.data.buildings[Building.PlanetaryInstitute] === 1 && hex.data.planet === Planet.Titanium ? 1 : 0; + const addedBescods = + this.faction === Faction.Bescods && + this.data.buildings[Building.PlanetaryInstitute] === 1 && + hex.data.planet === Planet.Titanium + ? 1 + : 0; return baseValue + addedBescods; } maxLeech(extraPowerToken?: boolean) { // considers real chargeable power and victory points - return Math.min(this.data.leechPossible, this.data.chargePower(this.data.leechPossible, false) + (extraPowerToken ? 2 : 0), this.data.victoryPoints + 1); + return Math.min( + this.data.leechPossible, + this.data.chargePower(this.data.leechPossible, false) + (extraPowerToken ? 2 : 0), + this.data.victoryPoints + 1 + ); } canLeech(): boolean { @@ -683,7 +750,7 @@ export default class Player extends EventEmitter { gainFederationToken(federation: Federation) { this.data.tiles.federations.push({ tile: federation, - green: isGreen(federation) + green: isGreen(federation), }); this.gainRewards(Reward.parse(federationTiles[federation]), Command.FormFederation); @@ -692,7 +759,11 @@ export default class Player extends EventEmitter { factionReward(reward: Reward): Reward { // this is for Gleens getting ore instead of qics until Academy2 - if (this.faction === Faction.Gleens && this.data.buildings[Building.Academy2] === 0 && reward.type === Resource.Qic) { + if ( + this.faction === Faction.Gleens && + this.data.buildings[Building.Academy2] === 0 && + reward.type === Resource.Qic + ) { return new Reward(reward.count, Resource.Ore); } return reward; @@ -710,26 +781,61 @@ export default class Player extends EventEmitter { eventConditionCount(condition: Condition): number { switch (condition) { - case Condition.None: return 1; - case Condition.Mine: return this.data.buildings[Building.Mine] + this.data.lostPlanet; - case Condition.TradingStation: return this.data.buildings[Building.TradingStation]; - case Condition.ResearchLab: return this.data.buildings[Building.ResearchLab]; - case Condition.PlanetaryInstituteOrAcademy: return this.data.buildings[Building.Academy1] + this.data.buildings[Building.Academy2] + this.data.buildings[Building.PlanetaryInstitute]; - case Condition.Federation: return this.data.tiles.federations.length; - case Condition.Gaia: return this.ownedPlanets.filter(hex => hex.data.planet === Planet.Gaia).length; - case Condition.PlanetType: return uniq(this.ownedPlanets.map( hex => hex.data.planet)).length; - case Condition.Sector: return uniq(this.data.occupied.filter(hex => hex.colonizedBy(this.player)).map(hex => hex.data.sector)).length; - case Condition.Structure: return this.data.occupied.filter(hex => hex.colonizedBy(this.player)).length; - case Condition.StructureFed: return this.data.occupied.filter(hex => hex.colonizedBy(this.player) && hex.belongsToFederationOf(this.player)).length; - case Condition.Satellite: return this.data.satellites + this.data.buildings[Building.SpaceStation]; - case Condition.StructureValue: return sum(this.data.occupied.map(hex => this.buildingValue(hex, {federation: true}))); - case Condition.StructureFedValue: return sum(this.data.occupied.map(hex => hex.belongsToFederationOf(this.player) ? this.buildingValue(hex, {federation: true}) : 0 )); - case Condition.Trade: return this.data.tradeTokens + this.data.wildTradeTokens; + case Condition.None: + return 1; + case Condition.Mine: + return this.data.buildings[Building.Mine] + this.data.lostPlanet; + case Condition.TradingStation: + return this.data.buildings[Building.TradingStation]; + case Condition.ResearchLab: + return this.data.buildings[Building.ResearchLab]; + case Condition.PlanetaryInstituteOrAcademy: + return ( + this.data.buildings[Building.Academy1] + + this.data.buildings[Building.Academy2] + + this.data.buildings[Building.PlanetaryInstitute] + ); + case Condition.Federation: + return this.data.tiles.federations.length; + case Condition.Gaia: + return this.ownedPlanets.filter((hex) => hex.data.planet === Planet.Gaia).length; + case Condition.PlanetType: + return uniq(this.ownedPlanets.map((hex) => hex.data.planet)).length; + case Condition.Sector: + return uniq(this.data.occupied.filter((hex) => hex.colonizedBy(this.player)).map((hex) => hex.data.sector)) + .length; + case Condition.Structure: + return this.data.occupied.filter((hex) => hex.colonizedBy(this.player)).length; + case Condition.StructureFed: + return this.data.occupied.filter( + (hex) => hex.colonizedBy(this.player) && hex.belongsToFederationOf(this.player) + ).length; + case Condition.Satellite: + return this.data.satellites + this.data.buildings[Building.SpaceStation]; + case Condition.StructureValue: + return sum(this.data.occupied.map((hex) => this.buildingValue(hex, { federation: true }))); + case Condition.StructureFedValue: + return sum( + this.data.occupied.map((hex) => + hex.belongsToFederationOf(this.player) ? this.buildingValue(hex, { federation: true }) : 0 + ) + ); + case Condition.Trade: + return this.data.tradeTokens + this.data.wildTradeTokens; // Max 8 (for tech tile which gains 1k per planet) - case Condition.PlanetsWithTradeToken: return Math.min(this.data.occupied.filter(hex => hex.isMainOccupier(this.player) && hex.colonizedBy(this.player) && hex.hasTradeTokens()).length, 8); - case Condition.AdvanceResearch: return sum(Object.values(this.data.research)); - case Condition.HighestResearchLevel: return Math.max(...Object.values(this.data.research)); - case Condition.Culture: return this.cultureLevel(); + case Condition.PlanetsWithTradeToken: + return Math.min( + this.data.occupied.filter( + (hex) => hex.isMainOccupier(this.player) && hex.colonizedBy(this.player) && hex.hasTradeTokens() + ).length, + 8 + ); + case Condition.AdvanceResearch: + return sum(Object.values(this.data.research)); + case Condition.HighestResearchLevel: + return Math.max(...Object.values(this.data.research)); + case Condition.Culture: + return this.cultureLevel(); } return 0; @@ -737,17 +843,19 @@ export default class Player extends EventEmitter { cultureLevel() { // Buildings including space stations - const buildings = sum(this.data.occupied.map(hex => this.buildingValue(hex, {federation: true}))); + const buildings = sum(this.data.occupied.map((hex) => this.buildingValue(hex, { federation: true }))); // Two satellites = 1pw const satellites = Math.floor(this.data.satellites / 2); // Federation tiles const federations = this.data.tiles.federations.length * 3; // Spaceship income - const ships = (Reward.parse(this.income).find(rew => rew.type === Resource.SpaceShip) || new Reward('~')).count; + const ships = (Reward.parse(this.income).find((rew) => rew.type === Resource.SpaceShip) || new Reward("~")).count; // Gaia formers const gaiaFormers = this.data.gaiaformers; // Highest level or Adv Tech - const advanced = Object.values(this.data.research).filter(val => val === 5).length + this.data.tiles.techs.filter(tech => isAdvanced(tech.pos)).length; + const advanced = + Object.values(this.data.research).filter((val) => val === 5).length + + this.data.tiles.techs.filter((tech) => isAdvanced(tech.pos)).length; return buildings + satellites + federations + ships + gaiaFormers + advanced; } @@ -758,7 +866,7 @@ export default class Player extends EventEmitter { if (this.federationCache) { if (maxSatellites <= this.federationCache.availableSatellites) { - return this.federationCache.federations.filter(fed => fed.satellites <= maxSatellites); + return this.federationCache.federations.filter((fed) => fed.satellites <= maxSatellites); } else { // Only try federations with building combinations not in federationCache.federations } @@ -766,11 +874,13 @@ export default class Player extends EventEmitter { const excluded = map.excludedHexesForBuildingFederation(this.player, this.faction); - const hexes = this.data.occupied.filter(hex => !excluded.has(hex)); + const hexes = this.data.occupied.filter((hex) => !excluded.has(hex)); const buildingGroups = this.buildingGroups(hexes, map); const buildingGroupsList = uniq([...buildingGroups.values()]); - const values = buildingGroupsList.map(buildings => sum(buildings.map(node => this.buildingValue(node, {federation: true})))); + const values = buildingGroupsList.map((buildings) => + sum(buildings.map((node) => this.buildingValue(node, { federation: true }))) + ); // The current algorithm is not all-knowing, so in some cases we allow player to generate their own federation if (values.length >= 6 && maxSatellites >= 8) { @@ -781,11 +891,15 @@ export default class Player extends EventEmitter { } } - let combinations = this.possibleCombinationsForFederations(zipWith(buildingGroupsList, values, (val1, val2) => ({hexes: val1, value: val2}))); + let combinations = this.possibleCombinationsForFederations( + zipWith(buildingGroupsList, values, (val1, val2) => ({ hexes: val1, value: val2 })) + ); // Ivits can only expand their first federation if (this.faction === Faction.Ivits && this.data.federationCount > 0) { - combinations = combinations.filter(combination => combination.some(hexList => hexList[0].belongsToFederationOf(this.player))); + combinations = combinations.filter((combination) => + combination.some((hexList) => hexList[0].belongsToFederationOf(this.player)) + ); } // We now have several combinations of buildings that can form federations @@ -802,19 +916,35 @@ export default class Player extends EventEmitter { // // Because of this second constraint, we do avoid some valid possibilites. // However, those possibilites are explored in another combination - const flexibleExcluded: Set = new Set([].concat(...this.data.occupied.map(hex => buildingsInDestGroups.has(hex) ? [] : [hex, ...map.grid.neighbours(hex)]))); - const allHexes = [...map.grid.values()].filter(hex => !excluded.has(hex) && (!flexible || !flexibleExcluded.has(hex))); - const workingGrid = new Grid>(...allHexes.map(hex => new Hex(hex.q, hex.r, {cost: occupiedSet.has(hex) ? 0 : 1}))); - const convertedDestGroups = destGroups.map(destGroup => destGroup.map(hex => workingGrid.get(hex))); - let tree = spanningTree(convertedDestGroups, workingGrid, maxSatellites, "heuristic", hex => hex.data.cost); + const flexibleExcluded: Set = new Set( + [].concat( + ...this.data.occupied.map((hex) => (buildingsInDestGroups.has(hex) ? [] : [hex, ...map.grid.neighbours(hex)])) + ) + ); + const allHexes = [...map.grid.values()].filter( + (hex) => !excluded.has(hex) && (!flexible || !flexibleExcluded.has(hex)) + ); + const workingGrid = new Grid>( + ...allHexes.map((hex) => new Hex(hex.q, hex.r, { cost: occupiedSet.has(hex) ? 0 : 1 })) + ); + const convertedDestGroups = destGroups.map((destGroup) => destGroup.map((hex) => workingGrid.get(hex))); + let tree = spanningTree(convertedDestGroups, workingGrid, maxSatellites, "heuristic", (hex) => hex.data.cost); if (tree && !flexible && flexibleExcluded.size > 0) { // In non flexible mode, we still try to suggest federations without extra planets, as long // as they don't add additional satellites - const allHexes = [...map.grid.values()].filter(hex => !excluded.has(hex) && !flexibleExcluded.has(hex)); - const workingGrid = new Grid>(...allHexes.map(hex => new Hex(hex.q, hex.r, {cost: occupiedSet.has(hex) ? 0 : 1}))); - const convertedDestGroups = destGroups.map(destGroup => destGroup.map(hex => workingGrid.get(hex))); - const treeWithoutOtherPlanets = spanningTree(convertedDestGroups, workingGrid, maxSatellites, "heuristic", hex => hex.data.cost); + const allHexes = [...map.grid.values()].filter((hex) => !excluded.has(hex) && !flexibleExcluded.has(hex)); + const workingGrid = new Grid>( + ...allHexes.map((hex) => new Hex(hex.q, hex.r, { cost: occupiedSet.has(hex) ? 0 : 1 })) + ); + const convertedDestGroups = destGroups.map((destGroup) => destGroup.map((hex) => workingGrid.get(hex))); + const treeWithoutOtherPlanets = spanningTree( + convertedDestGroups, + workingGrid, + maxSatellites, + "heuristic", + (hex) => hex.data.cost + ); if (treeWithoutOtherPlanets && treeWithoutOtherPlanets.cost <= tree.cost) { tree = treeWithoutOtherPlanets; @@ -823,18 +953,29 @@ export default class Player extends EventEmitter { if (tree) { // Convert from regular hex to gaia hex of grid - federations.push(this.addAdjacentBuildings(tree.path.map(hex => map.grid.get(hex)), map)); + federations.push( + this.addAdjacentBuildings( + tree.path.map((hex) => map.grid.get(hex)), + map + ) + ); } } const uniqFederations = uniqWith(federations, (fed1, fed2) => { - const fed1coords = fed1.map(x => x.toString()).sort().join(','); - const fed2coords = fed2.map(x => x.toString()).sort().join(','); + const fed1coords = fed1 + .map((x) => x.toString()) + .sort() + .join(","); + const fed2coords = fed2 + .map((x) => x.toString()) + .sort() + .join(","); return fed1coords === fed2coords; }); - const fedsWithInfo: FederationInfo[] = uniqFederations.map(federation => this.federationInfo(federation)); + const fedsWithInfo: FederationInfo[] = uniqFederations.map((federation) => this.federationInfo(federation)); // Remove federations with one more planet & one more satellite // Also remove federations containing another @@ -848,12 +989,12 @@ export default class Player extends EventEmitter { } } - const feds = difference(fedsWithInfo, toRemove).filter(fed => fed.satellites <= maxSatellites); + const feds = difference(fedsWithInfo, toRemove).filter((fed) => fed.satellites <= maxSatellites); this.federationCache = { availableSatellites: maxSatellites, federations: feds, - custom + custom, }; return feds; @@ -874,13 +1015,13 @@ export default class Player extends EventEmitter { federationInfo(federation: GaiaHex[]): FederationInfo { // Be careful of Ivits & space stations for nSatellites! - const satellites = federation.filter(hex => !hex.occupyingPlayers()?.includes(this.player)); - const nPlanets = federation.filter(hex => hex.colonizedBy(this.player)).length; + const satellites = federation.filter((hex) => !hex.occupyingPlayers()?.includes(this.player)); + const nPlanets = federation.filter((hex) => hex.colonizedBy(this.player)).length; return { hexes: federation, satellites: satellites.length, - planets: nPlanets + planets: nPlanets, }; } @@ -893,7 +1034,10 @@ export default class Player extends EventEmitter { } hex.addToFederationOf(this.player); } - this.payCosts([new Reward(newSatellites, this.faction === Faction.Ivits ? Resource.Qic : Resource.GainToken)], Command.FormFederation); + this.payCosts( + [new Reward(newSatellites, this.faction === Faction.Ivits ? Resource.Qic : Resource.GainToken)], + Command.FormFederation + ); this.data.satellites += newSatellites; this.gainFederationToken(token); this.data.federationCount += 1; @@ -901,17 +1045,17 @@ export default class Player extends EventEmitter { } checkAndGetFederationInfo(location: string, map: SpaceMap, flexible: boolean): FederationInfo { - const coords = location.split(',').map(loc => map.parse(loc)); + const coords = location.split(",").map((loc) => map.parse(loc)); for (const coord of coords) { assert(map.grid.get(coord), `Coord ${coord.q}x${coord.r} is not part of the map`); } - assert (coords.length <= 30, "The federation is too big, it is impossible to build with only 23 satellites"); + assert(coords.length <= 30, "The federation is too big, it is impossible to build with only 23 satellites"); - let hexes: GaiaHex[] = uniq(coords.map(coord => map.grid.get(coord))); + let hexes: GaiaHex[] = uniq(coords.map((coord) => map.grid.get(coord))); - assert (hexes.length === coords.length, "There are repeating coordinates in the given federation"); + assert(hexes.length === coords.length, "There are repeating coordinates in the given federation"); // Extend to nearby buidlings hexes = this.addAdjacentBuildings(hexes, map); @@ -919,44 +1063,67 @@ export default class Player extends EventEmitter { // Check if no forbidden square const excluded = map.excludedHexesForBuildingFederation(this.player, this.faction); for (const hex of hexes) { - assert (!excluded.has(hex), `${hex.toString()} can't be part of a new federation`); + assert(!excluded.has(hex), `${hex.toString()} can't be part of a new federation`); } // Check if all the buildings are in one group - assert(map.grid.groups(hexes).length === 1, 'The hexes of the federation must be adjacent'); + assert(map.grid.groups(hexes).length === 1, "The hexes of the federation must be adjacent"); // Get the power value of the buildings - const powerValue = sum(hexes.map(hex => this.buildingValue(hex, {federation: true}))); - assert(powerValue >= this.federationCost, "Your buildings need to have a total value of at least " + this.federationCost); + const powerValue = sum(hexes.map((hex) => this.buildingValue(hex, { federation: true }))); + assert( + powerValue >= this.federationCost, + "Your buildings need to have a total value of at least " + this.federationCost + ); const info = this.federationInfo(hexes); // Check if outclassed by available federations const available = this.availableFederations(map, flexible); - const outclasser = available.find(fed => isOutclassedBy(info, fed)); + const outclasser = available.find((fed) => isOutclassedBy(info, fed)); - assert(!outclasser, "Federation is outclassed by other federation at " + (outclasser?.hexes ?? []).join(',')); + assert(!outclasser, "Federation is outclassed by other federation at " + (outclasser?.hexes ?? []).join(",")); // Check if federation can be built with less satellites if (!flexible) { - const allHexes = [...map.grid.values()].filter(hex => !excluded.has(hex)); + const allHexes = [...map.grid.values()].filter((hex) => !excluded.has(hex)); const occupiedSet = new Set(this.data.occupied); - const workingGrid = new Grid>(...allHexes.map(hex => new Hex(hex.q, hex.r, {cost: occupiedSet.has(hex) ? 0 : 1}))); - const allGroups = [...this.buildingGroups(hexes.filter(hx => hx.belongsToFederationOf(this.player) || this.buildingValue(hx, {federation: true}) > 0), map).values()]; + const workingGrid = new Grid>( + ...allHexes.map((hex) => new Hex(hex.q, hex.r, { cost: occupiedSet.has(hex) ? 0 : 1 })) + ); + const allGroups = [ + ...this.buildingGroups( + hexes.filter( + (hx) => hx.belongsToFederationOf(this.player) || this.buildingValue(hx, { federation: true }) > 0 + ), + map + ).values(), + ]; const groups: GaiaHex[][] = uniq(allGroups); - const convertedDestGroups = groups.map(destGroup => destGroup.map(hex => workingGrid.get(hex))); + const convertedDestGroups = groups.map((destGroup) => destGroup.map((hex) => workingGrid.get(hex))); - const tree = spanningTree(convertedDestGroups, workingGrid, info.satellites, "heuristic", hex => hex.data.cost); + const tree = spanningTree(convertedDestGroups, workingGrid, info.satellites, "heuristic", (hex) => hex.data.cost); if (tree) { - const smallFederation = this.addAdjacentBuildings(tree.path.map(hex => map.grid.get(hex)), map); + const smallFederation = this.addAdjacentBuildings( + tree.path.map((hex) => map.grid.get(hex)), + map + ); const info2 = this.federationInfo(smallFederation); - assert(info2.satellites >= info.satellites, "The federation can be built with less satellites, for example: " + tree.path.join(",")); + assert( + info2.satellites >= info.satellites, + "The federation can be built with less satellites, for example: " + tree.path.join(",") + ); } } - assert (this.faction !== Faction.Ivits || this.data.federationCount === 0 || hexes.some(hex => hex.belongsToFederationOf(this.player)), "Ivits must extend their first federation"); + assert( + this.faction !== Faction.Ivits || + this.data.federationCount === 0 || + hexes.some((hex) => hex.belongsToFederationOf(this.player)), + "Ivits must extend their first federation" + ); return info; } @@ -971,10 +1138,13 @@ export default class Player extends EventEmitter { return 7; } - possibleCombinationsForFederations(nodes: Array<{hexes: GaiaHex[]; value: number}>, toReach = this.federationCost): GaiaHex[][][] { + possibleCombinationsForFederations( + nodes: Array<{ hexes: GaiaHex[]; value: number }>, + toReach = this.federationCost + ): GaiaHex[][][] { const ret: GaiaHex[][][] = []; - for (let i = 0; i < nodes.length; i ++) { + for (let i = 0; i < nodes.length; i++) { if (nodes[i].value === 0) { continue; } @@ -1012,10 +1182,13 @@ export default class Player extends EventEmitter { buildingGroup(hex: GaiaHex, map: SpaceMap): GaiaHex[] { const ret = []; - const addHex = hx => { + const addHex = (hx) => { ret.push(hx); for (const hx2 of map.grid.neighbours(hx)) { - if (!ret.includes(hx2) && (hx2.belongsToFederationOf(this.player) || this.buildingValue(hx2, {federation: true})) > 0) { + if ( + !ret.includes(hx2) && + (hx2.belongsToFederationOf(this.player) || this.buildingValue(hx2, { federation: true })) > 0 + ) { addHex(hx2); } } @@ -1026,7 +1199,7 @@ export default class Player extends EventEmitter { } addAdjacentBuildings(hexes: GaiaHex[], map: SpaceMap): GaiaHex[] { - return uniq([].concat(...hexes.map(hex => this.buildingGroup(hex, map)))); + return uniq([].concat(...hexes.map((hex) => this.buildingGroup(hex, map)))); } /** diff --git a/src/research-tracks.ts b/src/research-tracks.ts index 68a00741..c258abcb 100644 --- a/src/research-tracks.ts +++ b/src/research-tracks.ts @@ -1,30 +1,28 @@ import { ResearchField } from "./enums"; export default { - [ResearchField.Terraforming]: [ - [], ["2o"], ["d"], ["d", "3pw"], ["2o"], [] - ], - [ResearchField.Navigation]: [ - [], ["q"], ["r"], ["q" , "3pw"], ["r"], ["r"] - ], - [ResearchField.Intelligence]: [ - [], ["q"], ["q"], ["2q", "3pw"], ["2q"], ["4q"] - ], - [ResearchField.GaiaProject]: [ - [], [">gf"], ["3t"], [">gf", "3pw"], [">gf"], ["4vp", "g > vp"] - ], - [ResearchField.Economy]: [ - [], ["+2c,pw"], ["+2c,1o,2pw"], ["+3c,1o,3pw", "3pw"], ["+4c,2o,4pw"], ["6c,3o,6pw"] - ], - [ResearchField.Science]: [ - [], ["+k"], ["+2k"], ["+3k", "3pw"], ["+4k"], ["9k"] - ], + [ResearchField.Terraforming]: [[], ["2o"], ["d"], ["d", "3pw"], ["2o"], []], + [ResearchField.Navigation]: [[], ["q"], ["r"], ["q", "3pw"], ["r"], ["r"]], + [ResearchField.Intelligence]: [[], ["q"], ["q"], ["2q", "3pw"], ["2q"], ["4q"]], + [ResearchField.GaiaProject]: [[], [">gf"], ["3t"], [">gf", "3pw"], [">gf"], ["4vp", "g > vp"]], + [ResearchField.Economy]: [[], ["+2c,pw"], ["+2c,1o,2pw"], ["+3c,1o,3pw", "3pw"], ["+4c,2o,4pw"], ["6c,3o,6pw"]], + [ResearchField.Science]: [[], ["+k"], ["+2k"], ["+3k", "3pw"], ["+4k"], ["9k"]], [ResearchField.TradingBonus]: [ - ["trade >> 2k"], ["trade 1>> 2k,3c"], ["trade 1>> 2k,3c", "tech"], ["trade 1>> 2k,1o,3c", "3pw"], ["trade 1>> 2k,1o,3c,q", "tech"], ["trade 2>> 2k,1o,3c,q"] + ["trade >> 2k"], + ["trade 1>> 2k,3c"], + ["trade 1>> 2k,3c", "tech"], + ["trade 1>> 2k,1o,3c", "3pw"], + ["trade 1>> 2k,1o,3c,q", "tech"], + ["trade 2>> 2k,1o,3c,q"], ], [ResearchField.TradingVolume]: [ - ["+ship"], ["+ship", "ship-range"], ["+2ship", "ship-move"], ["+2ship", "ship-range", "3pw"], ["+3ship", "ship-move", "1> up-nav,up-int"], ["+4ship", "ship-move", "ship-range"] - ] + ["+ship"], + ["+ship", "ship-range"], + ["+2ship", "ship-move"], + ["+2ship", "ship-range", "3pw"], + ["+3ship", "ship-move", "1> up-nav,up-int"], + ["+4ship", "ship-move", "ship-range"], + ], }; export function lastTile(field: ResearchField) { diff --git a/src/research.spec.ts b/src/research.spec.ts index 88ee3b8a..54a74546 100644 --- a/src/research.spec.ts +++ b/src/research.spec.ts @@ -1,10 +1,10 @@ -import { expect } from 'chai'; -import Engine from './engine'; -import { Player } from './enums'; +import { expect } from "chai"; +import Engine from "./engine"; +import { Player } from "./enums"; const parseMoves = Engine.parseMoves; -describe('Research', () => { +describe("Research", () => { it("should grant a qic when upgrading navigation", () => { const moves = parseMoves(` init 2 randomSeed @@ -68,7 +68,7 @@ describe('Research', () => { expect(() => engine.move("p1 up gaia.")).to.throw(); }); - it("should prevent upgrading to last research track when another player is there", function() { + it("should prevent upgrading to last research track when another player is there", function () { this.timeout(10000); const moves = Engine.parseMoves(` @@ -133,7 +133,7 @@ describe('Research', () => { const engine = new Engine(moves); - expect(() => engine.move('lantids up terra.')).to.throw(); + expect(() => engine.move("lantids up terra.")).to.throw(); }); it("should give a second leech for lost planet", () => { @@ -241,7 +241,7 @@ describe('Research', () => { expect(() => new Engine(moves)).to.not.throw(); }); - it ("should upgrade 0 level research fine", function() { + it("should upgrade 0 level research fine", function () { this.timeout(10000); const moves = parseMoves(` init 2 playtest-spaceships-2 @@ -354,19 +354,21 @@ describe('Research', () => { spaceShips: true, advancedRules: true, map: { - sectors : [ - {sector : "3", rotation : 5, center : {q : 0, r : 0, s : 0}}, - {sector : "4", rotation : 5, center : {q : 5, r : -2, s : -3}}, - {sector : "2", rotation : 1, center : {q : 2, r : 3, s : -5}}, - {sector : "7B", rotation : 1, center : {q : -3, r : 5, s : -2}}, - {sector : "1", rotation : 4, center : {q : -5, r : 2, s : 3}}, - {sector : "5B", rotation : 5, center : {q : -2, r : -3, s : 5}}, - {sector : "6B", rotation : 0, center : {q : 3, r : -5, s : 2}} + sectors: [ + { sector: "3", rotation: 5, center: { q: 0, r: 0, s: 0 } }, + { sector: "4", rotation: 5, center: { q: 5, r: -2, s: -3 } }, + { sector: "2", rotation: 1, center: { q: 2, r: 3, s: -5 } }, + { sector: "7B", rotation: 1, center: { q: -3, r: 5, s: -2 } }, + { sector: "1", rotation: 4, center: { q: -5, r: 2, s: 3 } }, + { sector: "5B", rotation: 5, center: { q: -2, r: -3, s: 5 } }, + { sector: "6B", rotation: 0, center: { q: 3, r: -5, s: 2 } }, ], - mirror : false - } + mirror: false, + }, }); - expect(() => engine.move("ambas build ac2 -4x5. tech adv-gaia. cover move. up int. up terra. up sci. up ship. up nav.")).to.not.throw(); + expect(() => + engine.move("ambas build ac2 -4x5. tech adv-gaia. cover move. up int. up terra. up sci. up ship. up nav.") + ).to.not.throw(); }); }); diff --git a/src/reward.spec.ts b/src/reward.spec.ts index 9ee9f140..c962bcdf 100644 --- a/src/reward.spec.ts +++ b/src/reward.spec.ts @@ -1,13 +1,14 @@ -import {expect} from "chai"; -import 'mocha'; +import { expect } from "chai"; +import "mocha"; import Reward from "./reward"; import { Resource } from "./enums"; import { AssertionError } from "assert"; -describe('Reward', () => { - - it('should construct from strings', () => { - const [R3vp, R2vp, Rvp, R1vp, Rq, R5c, Ro, R4vp] = ["3vp", "2vp", "vp", "1vp", "q", "5c", "o", "vp+4"].map(str => new Reward(str)); +describe("Reward", () => { + it("should construct from strings", () => { + const [R3vp, R2vp, Rvp, R1vp, Rq, R5c, Ro, R4vp] = ["3vp", "2vp", "vp", "1vp", "q", "5c", "o", "vp+4"].map( + (str) => new Reward(str) + ); expect(R3vp.count).to.equal(3); expect(R3vp.type).to.equal(Resource.VictoryPoint); @@ -31,7 +32,7 @@ describe('Reward', () => { expect(R4vp.type).to.equal(Resource.VictoryPoint); }); - it('should give empty rewards on invalid strings', () => { + it("should give empty rewards on invalid strings", () => { expect(new Reward("vp").isEmpty()).to.equal(false); expect(new Reward("2c").isEmpty()).to.equal(false); expect(new Reward("up-gaia").isEmpty()).to.equal(false); @@ -40,25 +41,27 @@ describe('Reward', () => { expect(new Reward("15.2vp").isEmpty()).to.equal(true); }); - it('should convert back to a string', () => { + it("should convert back to a string", () => { expect(new Reward("3vp").toString()).to.equal("3vp"); expect(new Reward("1vp").toString()).to.equal("1vp"); expect(new Reward("vp").toString()).to.equal("1vp"); expect(new Reward("5c").toString()).to.equal("5c"); }); - it ('should convert an array of rewards to a string', () => { + it("should convert an array of rewards to a string", () => { expect(Reward.toString([new Reward("3vp"), new Reward("q")], true)).to.equal("1q,3vp"); }); - it ('should be able to test whether two sets of rewards are equal', () => { + it("should be able to test whether two sets of rewards are equal", () => { // tslint:disable-next-line no-unused-expression - expect(Reward.match(Reward.parse("c,o,3q"), [new Reward("c"), new Reward(3, Resource.Qic), new Reward("o")])).to.be.true; + expect(Reward.match(Reward.parse("c,o,3q"), [new Reward("c"), new Reward(3, Resource.Qic), new Reward("o")])).to.be + .true; // tslint:disable-next-line no-unused-expression - expect(Reward.match(Reward.parse("c,o,2q"), [new Reward("c"), new Reward(3, Resource.Qic), new Reward("o")])).to.be.false; + expect(Reward.match(Reward.parse("c,o,2q"), [new Reward("c"), new Reward(3, Resource.Qic), new Reward("o")])).to.be + .false; }); - it ("should test if an array of rewards contains another", () => { + it("should test if an array of rewards contains another", () => { // tslint:disable-next-line no-unused-expression expect(Reward.includes(Reward.parse("q"), Reward.parse("4pw"))).to.be.false; // tslint:disable-next-line no-unused-expression diff --git a/src/reward.ts b/src/reward.ts index bb49bd8e..808c4576 100644 --- a/src/reward.ts +++ b/src/reward.ts @@ -14,12 +14,12 @@ export default class Reward { const str = count as string; if (str.indexOf("+") > 0) { - const regex = /^(.*)\+([0-9]*)$/; + const regex = /^(.*)\+([0-9]*)$/; let _unused; [_unused, type, count] = regex.exec(str) as any; } else { - const regex = /^(-?[0-9]*)?(.*)$/; + const regex = /^(-?[0-9]*)?(.*)$/; let _unused; [_unused, count, type] = regex.exec(str) as any; } @@ -29,14 +29,14 @@ export default class Reward { this.count = 0; this.type = Resource.None; } else { - this.count = typeof count === "number" ? count : ((count !== undefined && count.length > 0) ? +count : 1); + this.count = typeof count === "number" ? count : count !== undefined && count.length > 0 ? +count : 1; this.type = type as Resource; } } toString() { if (this.isEmpty()) { - return '~'; + return "~"; } return `${this.count}${this.type}`; } @@ -50,9 +50,9 @@ export default class Reward { } static parse(source: string): Reward[] { - assert (typeof source === "string", `Reward.parse: ${source}'s type is not string, but ${typeof source}`); + assert(typeof source === "string", `Reward.parse: ${source}'s type is not string, but ${typeof source}`); - return source.split(",").map(rew => new Reward(rew)); + return source.split(",").map((rew) => new Reward(rew)); } /** @@ -64,24 +64,34 @@ export default class Reward { static merge(...rewards: Reward[][]): Reward[] { const grouped = groupBy([].concat(...rewards), "type"); - return Object.keys(grouped).map(key => new Reward(grouped[key].reduce((val, rew) => val + rew.count, 0), key as Resource)).filter(rew => !rew.isEmpty()); + return Object.keys(grouped) + .map( + (key) => + new Reward( + grouped[key].reduce((val, rew) => val + rew.count, 0), + key as Resource + ) + ) + .filter((rew) => !rew.isEmpty()); } static negative(rewards: Reward[]): Reward[] { - return rewards.map(reward => new Reward(-reward.count, reward.type)); + return rewards.map((reward) => new Reward(-reward.count, reward.type)); } static toString(rewards: Reward[], sorted = true) { // const sortOrder = ['c', 'o', 'k', 'q', 'pw']; - const sortOrder = ['pw', 'q', 'k', 'o', 'c']; + const sortOrder = ["pw", "q", "k", "o", "c"]; if (sorted) { - rewards.sort((rew1, rew2) => ( sortOrder.findIndex( so => so === rew2.type ) - sortOrder.findIndex(so => so === rew1.type))); + rewards.sort( + (rew1, rew2) => sortOrder.findIndex((so) => so === rew2.type) - sortOrder.findIndex((so) => so === rew1.type) + ); } if (rewards.length === 0) { return "~"; } - return rewards.map(rew => rew.toString()).join(","); + return rewards.map((rew) => rew.toString()).join(","); } static match(rewards1: Reward[], rewards2: Reward[]): boolean { @@ -89,7 +99,7 @@ export default class Reward { } static includes(container: Reward[], contained: Reward[]): boolean { - const indexed: {[res in Resource]?: number} = {}; + const indexed: { [res in Resource]?: number } = {}; for (const reward of container) { indexed[reward.type] = (indexed[reward.type] || 0) + reward.count; } diff --git a/src/sector.ts b/src/sector.ts index e4547d98..bb57f13c 100644 --- a/src/sector.ts +++ b/src/sector.ts @@ -1,7 +1,7 @@ -import { Grid} from "hexagrid"; +import { Grid } from "hexagrid"; import { Planet } from "./enums"; -import { GaiaHex } from "./gaia-hex"; +import { GaiaHex } from "./gaia-hex"; export default class Sector { /** @@ -10,7 +10,7 @@ export default class Sector { * @param definition The contents of the sector * @param id The id of the sector */ - public static create(definition: Planet[] | string, name: string, center = {q: 0, r: 0, s: 0}): Grid { + public static create(definition: Planet[] | string, name: string, center = { q: 0, r: 0, s: 0 }): Grid { // Converts a string like eee,dsee,eeere,eeem,ove into an array of array of planets if (typeof definition === "string") { definition = definition.split("") as Planet[]; @@ -18,8 +18,8 @@ export default class Sector { // flatten the array const planetArray: Planet[] = [].concat(...definition); - const dataArray = planetArray.map(planet => ({planet, sector: name})); - const grid = new Grid(...GaiaHex.hexagon(2, {center, data: dataArray}) as GaiaHex[]); + const dataArray = planetArray.map((planet) => ({ planet, sector: name })); + const grid = new Grid(...(GaiaHex.hexagon(2, { center, data: dataArray }) as GaiaHex[])); return grid; } diff --git a/src/tiles/boosters.spec.ts b/src/tiles/boosters.spec.ts index 832ab950..2381c4bd 100644 --- a/src/tiles/boosters.spec.ts +++ b/src/tiles/boosters.spec.ts @@ -1,15 +1,15 @@ -import { expect } from 'chai'; -import Engine from '../engine'; -import {Operator, Player} from '../enums'; +import { expect } from "chai"; +import Engine from "../engine"; +import { Operator, Player } from "../enums"; const parseMoves = Engine.parseMoves; describe("boosters", () => { it("should have the correct number of round boosters depending on the number of players", () => { - const engine2 = new Engine(['init 2 randomSeed']); - const engine3 = new Engine(['init 3 randomSeed']); - const engine4 = new Engine(['init 4 randomSeed']); - const engine5 = new Engine(['init 5 randomSeed']); + const engine2 = new Engine(["init 2 randomSeed"]); + const engine3 = new Engine(["init 3 randomSeed"]); + const engine4 = new Engine(["init 4 randomSeed"]); + const engine5 = new Engine(["init 5 randomSeed"]); expect(Object.keys(engine2.tiles.boosters)).to.have.length(5); expect(Object.keys(engine3.tiles.boosters)).to.have.length(6); @@ -90,7 +90,10 @@ describe("boosters", () => { expect(() => new Engine([...moves, "p1 special step"])).to.not.throw(); // tslint:disable-next-line no-unused-expression - expect(new Engine([...moves, "p1 special step. build m -2x2."]).player(Player.Player1).events[Operator.Activate][0].activated).to.be.true; + expect( + new Engine([...moves, "p1 special step. build m -2x2."]).player(Player.Player1).events[Operator.Activate][0] + .activated + ).to.be.true; // The step special action can't be used to build a gaia-former expect(() => new Engine([...moves, "p1 special step. build gf -2x3."])).to.throw(); diff --git a/src/tiles/boosters.ts b/src/tiles/boosters.ts index 3c563db1..a7391113 100644 --- a/src/tiles/boosters.ts +++ b/src/tiles/boosters.ts @@ -13,5 +13,5 @@ export default { [Booster.Booster10]: ["+4c", "g | vp"], [Booster.Ship1]: ["trade >> 3vp", "=>range+1"], [Booster.Ship2]: ["+ship", "=>move-all"], - [Booster.Ship3]: ["+2k", "L | vp"] + [Booster.Ship3]: ["+2k", "L | vp"], }; diff --git a/src/tiles/federations.spec.ts b/src/tiles/federations.spec.ts index 96c8d444..2e656f1c 100644 --- a/src/tiles/federations.spec.ts +++ b/src/tiles/federations.spec.ts @@ -1,6 +1,6 @@ import { expect } from "chai"; import Engine from "../engine"; -import { Player } from '../enums'; +import { Player } from "../enums"; const parseMoves = Engine.parseMoves; @@ -46,7 +46,10 @@ describe("Federation", () => { expect(data.victoryPoints).to.equal(vp + 8 + 5); expect(data.power.gaia).to.be.gte(0); expect(data.satellites).to.equal(2); - expect(data.discardablePowerTokens()).to.be.equal(powerTokens - 2, "The 2 satellites should remove one power token each"); + expect(data.discardablePowerTokens()).to.be.equal( + powerTokens - 2, + "The 2 satellites should remove one power token each" + ); // Test other federation with the same buildings expect(() => new Engine([...moves, "p1 federation -1x2,-2x3,-3x3,-3x4,-4x2,-4x3 fed2"])).to.not.throw(); diff --git a/src/tiles/federations.ts b/src/tiles/federations.ts index f661aef1..fc709ce2 100644 --- a/src/tiles/federations.ts +++ b/src/tiles/federations.ts @@ -1,6 +1,6 @@ import { Federation } from "../enums"; -export default { +export default { [Federation.Fed1]: "12vp", [Federation.Fed2]: "8vp,q", [Federation.Fed3]: "8vp,2t", @@ -8,7 +8,7 @@ export default { [Federation.Fed5]: "7vp,6c", [Federation.Fed6]: "6vp,2k", [Federation.Gleens]: "o,k,2c", - [Federation.Ship]: "adv-ship" + [Federation.Ship]: "adv-ship", }; export function isGreen(federation: Federation) { diff --git a/src/tiles/index.ts b/src/tiles/index.ts index 56814fbb..78ae5eea 100644 --- a/src/tiles/index.ts +++ b/src/tiles/index.ts @@ -1,5 +1,5 @@ import techs from "./techs"; -import {roundScorings, finalScorings} from "./scoring"; +import { roundScorings, finalScorings } from "./scoring"; import boosters from "./boosters"; import federations from "./federations"; @@ -8,5 +8,5 @@ export default { roundScorings, finalScorings, boosters, - federations + federations, }; diff --git a/src/tiles/scoring.ts b/src/tiles/scoring.ts index c5c1c43f..2eb1f5e4 100644 --- a/src/tiles/scoring.ts +++ b/src/tiles/scoring.ts @@ -1,6 +1,6 @@ import { ScoringTile, FinalTile, Condition } from "../enums"; -const roundScorings = { +const roundScorings = { [ScoringTile.Score1]: ["step >> 2vp"], [ScoringTile.Score2]: ["a >> 2vp"], [ScoringTile.Score3]: ["m >> 2vp"], @@ -15,15 +15,15 @@ const roundScorings = { [ScoringTile.Ship2]: ["trade >> 3vp"], }; -const finalScorings = { +const finalScorings = { [FinalTile.Structure]: { condition: Condition.Structure, neutralPlayer: 11 }, - [FinalTile.StructureFed]: { condition: Condition.StructureFed, neutralPlayer: 10 }, - [FinalTile.PlanetType]: { condition: Condition.PlanetType, neutralPlayer: 5 }, + [FinalTile.StructureFed]: { condition: Condition.StructureFed, neutralPlayer: 10 }, + [FinalTile.PlanetType]: { condition: Condition.PlanetType, neutralPlayer: 5 }, [FinalTile.Gaia]: { condition: Condition.Gaia, neutralPlayer: 4 }, [FinalTile.Sector]: { condition: Condition.Sector, neutralPlayer: 6 }, [FinalTile.Satellite]: { condition: Condition.Satellite, neutralPlayer: 8 }, [FinalTile.Culture]: { condition: Condition.Culture, neutralPlayer: 20 }, - [FinalTile.TradeTokens]: { condition: Condition.Trade, neutralPlayer: 8 } + [FinalTile.TradeTokens]: { condition: Condition.Trade, neutralPlayer: 8 }, }; -export {roundScorings, finalScorings}; +export { roundScorings, finalScorings }; diff --git a/src/tiles/techs.spec.ts b/src/tiles/techs.spec.ts index 85bc4877..76f08121 100644 --- a/src/tiles/techs.spec.ts +++ b/src/tiles/techs.spec.ts @@ -1,6 +1,6 @@ -import { expect } from 'chai'; -import Engine from '../engine'; -import {Player, AdvTechTilePos, TechTilePos, Command} from '../enums'; +import { expect } from "chai"; +import Engine from "../engine"; +import { Player, AdvTechTilePos, TechTilePos, Command } from "../enums"; describe("Tech Tiles", () => { it("should prevent picking the same tech tile twice", () => { @@ -31,7 +31,7 @@ describe("Tech Tiles", () => { const engine = new Engine(moves); - expect(() => engine.move('p1 build ac1 -3x4. tech free1')).to.throw(); + expect(() => engine.move("p1 build ac1 -3x4. tech free1")).to.throw(); }); it("should allow to upgrade research area after building a RL, pick tech in nav", () => { @@ -52,13 +52,13 @@ describe("Tech Tiles", () => { const engine = new Engine(moves); /** Spends two green federations: one for the last tile, one for the advanced tech */ - expect(() => engine.move('p1 build lab -1x2. tech nav. up nav.')).to.not.throw(); + expect(() => engine.move("p1 build lab -1x2. tech nav. up nav.")).to.not.throw(); // tslint:disable-next-line no-unused-expression - expect(engine.player(Player.Player1).data.tiles.techs.find(tile => tile.pos === TechTilePos.Navigation)).to.not.be.undefined; + expect(engine.player(Player.Player1).data.tiles.techs.find((tile) => tile.pos === TechTilePos.Navigation)).to.not.be + .undefined; const engine1 = new Engine(moves); - expect(() => engine1.move('p1 build lab -1x2. tech nav. decline.')).to.not.throw(); - + expect(() => engine1.move("p1 build lab -1x2. tech nav. decline.")).to.not.throw(); }); it("should allow to get an advanced tech tiles when conditions are met", () => { @@ -115,17 +115,17 @@ describe("Tech Tiles", () => { const engine = new Engine(moves); /** Spends two green federations: one for the last tile, one for the advanced tech */ - expect(() => engine.move('p1 build lab -2x3. tech adv-gaia. cover free1. up gaia.')).to.throw(); + expect(() => engine.move("p1 build lab -2x3. tech adv-gaia. cover free1. up gaia.")).to.throw(); const engine1 = new Engine(moves); - expect(() => engine1.move('p1 build lab -2x3. tech adv-gaia. cover free1. up terra.')).to.not.throw(); + expect(() => engine1.move("p1 build lab -2x3. tech adv-gaia. cover free1. up terra.")).to.not.throw(); // tslint:disable-next-line no-unused-expression - expect(engine1.player(Player.Player1).data.tiles.techs.find(tile => tile.pos === AdvTechTilePos.GaiaProject)).to.not.be.undefined; + expect(engine1.player(Player.Player1).data.tiles.techs.find((tile) => tile.pos === AdvTechTilePos.GaiaProject)).to + .not.be.undefined; expect(engine1.tiles.techs[AdvTechTilePos.GaiaProject].count).to.equal(0); const engine2 = new Engine(moves); - expect(() => engine2.move('p1 build lab -2x3. tech adv-gaia. cover free1. decline.')).to.not.throw(); - + expect(() => engine2.move("p1 build lab -2x3. tech adv-gaia. cover free1. decline.")).to.not.throw(); }); it("should refuse advanced tech tile when no tech tile to cover", () => { @@ -211,6 +211,6 @@ describe("Tech Tiles", () => { const availableCommand = engine.findAvailableCommand(Player.Player1, Command.ChooseTechTile); // tslint:disable-next-line no-unused-expression - expect(availableCommand.data.tiles.find(tech => tech.pos === AdvTechTilePos.Economy)).to.be.undefined; + expect(availableCommand.data.tiles.find((tech) => tech.pos === AdvTechTilePos.Economy)).to.be.undefined; }); }); diff --git a/src/tiles/techs.ts b/src/tiles/techs.ts index a57f0e4f..6e6f1381 100644 --- a/src/tiles/techs.ts +++ b/src/tiles/techs.ts @@ -1,6 +1,6 @@ import { TechTile, AdvTechTile, Operator, TechTilePos, AdvTechTilePos } from "../enums"; -export default { +export default { [TechTile.Tech1]: ["o,q"], [TechTile.Tech2]: ["pt > k"], [TechTile.Tech3]: [Operator.Special], @@ -37,7 +37,6 @@ export default { [AdvTechTile.Ship6]: ["=> q,o,2turn"], }; - export function isAdvanced(pos: TechTilePos | AdvTechTilePos): boolean { return pos.startsWith("adv"); } diff --git a/src/utils.ts b/src/utils.ts index 1c810f82..fb68fcc1 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,4 +1,4 @@ -import { mergeWith } from 'lodash'; +import { mergeWith } from "lodash"; function customizer(objValue, srcValue) { if (Array.isArray(objValue)) { diff --git a/tsconfig.json b/tsconfig.json index 1d4b9832..cf7dd09b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,21 +5,11 @@ "module": "commonjs", "esModuleInterop": true, // "declaration": true, /* Generates corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ + "sourceMap": true /* Generates corresponding '.map' file. */, // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "./dist", /* Redirect output structure to the directory. */ + "outDir": "./dist" /* Redirect output structure to the directory. */ }, - "types": [ - "node" - ], - "include": [ - "src/**/*.ts", - "index.ts", - "wrapper.ts" - ], - "exclude": [ - "node_modules", - "dist", - "**/*.spec.ts" - ] -} \ No newline at end of file + "types": ["node"], + "include": ["src/**/*.ts", "index.ts", "wrapper.ts"], + "exclude": ["node_modules", "dist", "**/*.spec.ts"] +} diff --git a/tslint.json b/tslint.json index 88112f3a..f7c89bbe 100644 --- a/tslint.json +++ b/tslint.json @@ -1,8 +1,6 @@ { "defaultSeverity": "error", - "extends": [ - "tslint:recommended" - ], + "extends": ["tslint:recommended"], "rules": { "quotemark": false, "indent": [true, "spaces", 2], diff --git a/wrapper.ts b/wrapper.ts index aab3cbc3..cb76e968 100644 --- a/wrapper.ts +++ b/wrapper.ts @@ -1,41 +1,48 @@ -import axios from 'axios'; -import Engine from './index'; +import axios from "axios"; +import Engine from "./index"; import crypto from "crypto"; -import { EngineOptions } from './src/engine'; -import { Round } from './src/enums'; +import { EngineOptions } from "./src/engine"; +import { Round } from "./src/enums"; import assert from "assert"; -export async function init (nbPlayers: number, expansions: string[], options: EngineOptions & {balancedGeneration: boolean}, seed?: string): Promise { +export async function init( + nbPlayers: number, + expansions: string[], + options: EngineOptions & { balancedGeneration: boolean }, + seed?: string +): Promise { if (!seed) { - seed = crypto.randomBytes(8).toString('base64'); + seed = crypto.randomBytes(8).toString("base64"); } let numberSeed: number; // If the seed is a number, use it directly, otherwise use a number generated from its hash - if ('' + parseInt(seed, 10) === seed) { + if ("" + parseInt(seed, 10) === seed) { numberSeed = parseInt(seed, 10); } else { const md5sum = crypto.createHash("md5"); md5sum.update(seed); - numberSeed = ('' + parseInt(seed, 10)) === seed ? parseInt(seed, 10) : parseInt(md5sum.digest("hex").slice(-10), 16); + numberSeed = "" + parseInt(seed, 10) === seed ? parseInt(seed, 10) : parseInt(md5sum.digest("hex").slice(-10), 16); } if (expansions.includes("spaceships")) { options.spaceShips = true; } - if (options.balancedGeneration || options.layout === 'balanced') { + if (options.balancedGeneration || options.layout === "balanced") { delete options.balancedGeneration; - const resp = await axios.post('http://gaia-project.hol.es', {seed: numberSeed, player: nbPlayers}).then(r => r.data); + const resp = await axios + .post("http://gaia-project.hol.es", { seed: numberSeed, player: nbPlayers }) + .then((r) => r.data); - options.map = {sectors: resp.map}; + options.map = { sectors: resp.map }; // We use different standards for sides A & B of sectors than the online generator if (nbPlayers === 2) { - options.map.sectors.forEach(val => val.sector = val.sector.replace(/A/, 'B')); + options.map.sectors.forEach((val) => (val.sector = val.sector.replace(/A/, "B"))); } else { - options.map.sectors.forEach(val => val.sector = val.sector.replace(/B/, 'A')); + options.map.sectors.forEach((val) => (val.sector = val.sector.replace(/B/, "A"))); } } @@ -45,7 +52,7 @@ export async function init (nbPlayers: number, expansions: string[], options: En return engine; } -export function setPlayerMetaData(engine: Engine, player: number, metaData: {name: string}) { +export function setPlayerMetaData(engine: Engine, player: number, metaData: { name: string }) { engine.players[player].name = metaData.name; return engine; @@ -105,23 +112,23 @@ function automove(engine: Engine) { } while (modified); } -export function ended (engine: Engine) { +export function ended(engine: Engine) { return engine.ended; } -export function cancelled (engine: Engine) { +export function cancelled(engine: Engine) { return engine.ended && engine.round < Round.LastRound; } -export function scores (engine: Engine) { - return engine.players.map(pl => pl.data.victoryPoints); +export function scores(engine: Engine) { + return engine.players.map((pl) => pl.data.victoryPoints); } -export function factions (engine: Engine) { - return engine.players.map(pl => pl.faction); +export function factions(engine: Engine) { + return engine.players.map((pl) => pl.faction); } -export async function replay (engine: Engine) { +export async function replay(engine: Engine) { const oldPlayers = engine.players; engine = new Engine(engine.moveHistory, engine.options); @@ -142,7 +149,7 @@ export async function replay (engine: Engine) { return engine; } -export async function dropPlayer (engine: Engine, player: number) { +export async function dropPlayer(engine: Engine, player: number) { engine = engine instanceof Engine ? engine : Engine.fromData(engine); engine.players[player].dropped = true; @@ -156,33 +163,33 @@ export async function dropPlayer (engine: Engine, player: number) { return engine; } -export function currentPlayer (engine: Engine) { +export function currentPlayer(engine: Engine) { return engine.playerToMove; } -export function toSave (engine: Engine) { +export function toSave(engine: Engine) { if (!engine.newTurn || (engine as any).noSave) { return undefined; } return engine; } -export function messages (engine: Engine) { +export function messages(engine: Engine) { const messages = (engine as any).messages || []; delete (engine as any).messages; return { messages, - data: engine + data: engine, }; } -export function logLength (engine: Engine) { +export function logLength(engine: Engine) { return engine.moveHistory.length; } -export function logSlice (engine: Engine, options?: {player?: number; start?: number; end?: number}) { - return {state: engine}; +export function logSlice(engine: Engine, options?: { player?: number; start?: number; end?: number }) { + return { state: engine }; } export function round(engine: Engine) {