diff --git a/engine/src/analysis.ts b/engine/src/analysis.ts index 865b007..b0df0ba 100644 --- a/engine/src/analysis.ts +++ b/engine/src/analysis.ts @@ -5,19 +5,12 @@ import { QUEBEC_RECHARGED_TOP_PLANTS, removedPlants, RUSSIA_ORIGINAL_NEXT_PLANTS, + spainStep2Plants, SPAIN_STEP_2_PLANTS, } from './deckChanges'; import { defaultSetupDeck, reconstructState, setup, stripSecret } from './engine'; -import { GameState, PowerPlant, PowerPlantType } from './gamestate'; -import { - gameDeck, - isEcological, - isPlugPlant, - labelledPlant, - lastPlugPlant, - plantCatalogue, - PLANT_LABEL_PATTERN, -} from './powerPlants'; +import { GameState, PowerPlant, PowerPlantType, SingleDeck } from './gamestate'; +import { gameDeck, isEcological, isPlugPlant, labelledPlant, plantCatalogue, PLANT_LABEL_PATTERN } from './powerPlants'; import { shuffle } from './utils'; /** Unknown cards come from the published catalogue, never the live draw pile. */ @@ -38,15 +31,25 @@ export function createAnalysisScenario( const name = s.map.name; const n = s.players.length; const powerPlantDeck = gameDeck(s.options); + const isShuffled = powerPlantDeck === 'shuffled' || powerPlantDeck === 'shuffledUnique'; // Spain & Portugal's held-back plants return at Step 2; Manhattan boxes its Step 3 card. let excluded = removedPlants(name, powerPlantDeck, n, s.options.variant!); - if (name === 'Spain & Portugal' && s.step !== 1) excluded = []; + // With the shuffled decks, only the held-back copies that were dealt return. + const held = s.heldPowerPlants?.map((p) => p.number); + if (name === 'Spain & Portugal' && s.step !== 1) + excluded = held ? spainStep2Plants(powerPlantDeck).filter((number) => !held.includes(number)) : []; if (name === 'Manhattan') excluded = [99, ...excluded]; const catalogue = JSON.parse(JSON.stringify(plantCatalogue(name, powerPlantDeck))) as PowerPlant[]; for (const region of new Set(s.regionDraft ? [] : s.map.cities.map((c) => c.region))) { for (const replacement of s.map.regionalPowerPlants?.[region] || []) { + // The shuffled decks: the regional card replaces every copy of its number. + if (isShuffled) { + for (let i = catalogue.length - 1; i >= 0; i--) + if (Math.floor(catalogue[i].number) === replacement.number) catalogue.splice(i, 1); + } const i = catalogue.findIndex((p) => p.number === replacement.number); if (i >= 0) catalogue[i] = { ...replacement }; + else catalogue.splice(catalogue.length - 1, 0, { ...replacement }); } } const byNumber = (number: number) => catalogue.find((p) => p.number === number)!; @@ -136,29 +139,59 @@ export function createAnalysisScenario( const count = s.cardsLeft - fixedBottom.length - Number(!!step3); const fixedTop: number[] = []; const original = s.options.variant === 'original'; - if (original && name !== 'China' && name !== 'Manhattan') { - for (const number of originalTopPlants(name, powerPlantDeck)) if (!seen.has(number)) fixedTop.push(number); + // Cards drawn since the opening market (Russia's holds six plants). + const drawnPastMarket = s.knownPowerPlantDeck.length - (name === 'Russia' ? 6 : 8); + const shuffledQuebec = isShuffled && name === 'Quebec'; + if (original && name !== 'China' && name !== 'Manhattan' && !shuffledQuebec) { + const tops = originalTopPlants(name, powerPlantDeck); + // The top plants are drawn first. A shuffled deck may not have dealt them: once + // that many cards have been drawn past the opening market, any still unseen + // were never in the game. + const undealt = isShuffled && drawnPastMarket >= tops.length; + if (!undealt) for (const number of tops) if (!seen.has(number)) fixedTop.push(number); } - if (!original && name === 'Quebec') { + if (shuffledQuebec && drawnPastMarket <= 2) { + // One plug card, then the two smallest ecological plants dealt (see quebec.ts). + const unseen = candidates.filter((p) => p.number !== 99); + if (original && drawnPastMarket === 0) { + const plug = + unseen.find((p) => p.number === originalTopPlants(name, powerPlantDeck)[0]) ?? + [...unseen].sort((a, b) => a.number - b.number).find((p) => isPlugPlant(p, powerPlantDeck)); + if (plug) fixedTop.push(plug.number); + } + const winds = unseen + .filter((p) => isEcological(p, s.options.fusionEcological) && !fixedTop.includes(p.number)) + .sort((a, b) => a.number - b.number) + .slice(0, 2 - Math.max(0, drawnPastMarket - 1)); + fixedTop.push(...winds.map((p) => p.number)); + } + if (!original && name === 'Quebec' && !isShuffled) { // The first low plant is followed by the two guaranteed ecological plants. for (const number of QUEBEC_RECHARGED_TOP_PLANTS[powerPlantDeck]) if (!seen.has(number)) fixedTop.push(number); } if (name === 'Spain & Portugal' && s.step === 2) { - for (const number of SPAIN_STEP_2_PLANTS[powerPlantDeck]) if (!seen.has(number)) fixedTop.push(number); + for (const number of held ?? SPAIN_STEP_2_PLANTS[powerPlantDeck as SingleDeck]) + if (!seen.has(number)) fixedTop.push(number); } - const top = fixedTop.map(byNumber).filter((p) => candidates.some((c) => c.number === p.number)); + const top = fixedTop + .map(byNumber) + .filter((p) => candidates.some((c) => c.number === p.number)) + .slice(0, Math.max(0, count)); candidates = candidates.filter((p) => !top.some((t) => t.number === p.number)); const mandatory = (p: PowerPlant) => - (name === 'Brazil' && p.type === PowerPlantType.Garbage && p.number > lastPlugPlant(powerPlantDeck)) || + (name === 'Brazil' && p.type === PowerPlantType.Garbage && !isPlugPlant(p, powerPlantDeck)) || // Games without the stored ruling built their Québec deck protecting fusion too. (name === 'Quebec' && isEcological(p, s.options.fusionEcological ?? true)) || - (name === 'Russia' && original && RUSSIA_ORIGINAL_NEXT_PLANTS[powerPlantDeck].includes(p.number)); + (name === 'Russia' && + original && + !isShuffled && + RUSSIA_ORIGINAL_NEXT_PLANTS[powerPlantDeck as SingleDeck].includes(p.number)); // A plug-back top card is public information in the recharged edition. if ( (!original || name === 'Manhattan') && name !== 'China' && count > 0 && - (top.length === 0 || (name === 'Quebec' && s.nextCardWeak)) + (top.length === 0 || (name === 'Quebec' && s.nextCardWeak && !(isShuffled && drawnPastMarket > 0))) ) { candidates = candidates.filter(mandatory).concat(candidates.filter((p) => !mandatory(p))); const index = candidates.findIndex( @@ -169,7 +202,8 @@ export function createAnalysisScenario( if (index >= 0) top.unshift(...candidates.splice(index, 1)); } const select = (cards: PowerPlant[], amount: number) => { - const required = cards.filter(mandatory); + // A shuffled deck holds more copies of the protected plants than it dealt. + const required = cards.filter(mandatory).slice(0, Math.max(0, amount)); return required.concat(cards.filter((p) => !mandatory(p)).slice(0, Math.max(0, amount - required.length))); }; let rest: PowerPlant[]; @@ -187,7 +221,9 @@ export function createAnalysisScenario( seedrandom(seed + ':catalogue-counts'), s.options.useNewRechargedSetup ?? true, powerPlantDeck, - name + name, + 0, + powerPlantDeck === 'shuffled' && s.options.shuffledSample === true ) : setup(n, s.options, seed + ':catalogue-counts'); const low = (p: { number: number }) => (name === 'India' ? p.number <= 16 : isPlugPlant(p, powerPlantDeck)); @@ -196,13 +232,21 @@ export function createAnalysisScenario( ).length; const seenLow = [...seen].filter((number) => low({ number })).length; const recycledLow = [...recycled].filter((number) => low({ number }) && !unavailable.has(number)).length; - const lowCount = initialLow - seenLow + recycledLow - top.filter(low).length; - rest = select(candidates.filter(low), Math.max(0, lowCount)).concat( + // A shuffled deck's plug-card count varies with the deal; keep the estimate in the deck. + const lowCount = Math.min( + Math.max(0, initialLow - seenLow + recycledLow - top.filter(low).length), + count - top.length + ); + const lowPlants = select(candidates.filter(low), lowCount); + rest = lowPlants.concat( select( candidates.filter((p) => !low(p)), - count - top.length - Math.max(0, lowCount) + count - top.length - lowPlants.length ) ); + // Fewer socket cards left than the estimate allows: fill with plug cards. + const spare = candidates.filter((p) => low(p) && !rest.includes(p)); + rest = rest.concat(spare.slice(0, Math.max(0, count - top.length - rest.length))); rest = shuffle(rest, seed + ':remaining'); } else rest = select(candidates, Math.max(0, count - top.length)); let deck = [...top, ...rest]; @@ -210,7 +254,14 @@ export function createAnalysisScenario( if (original) { const remainingWindow = Math.max(0, 6 - Math.max(0, s.knownPowerPlantDeck.length - 6)); const topNumber = originalTopPlants(name, powerPlantDeck)[0]; - const nextNumbers = RUSSIA_ORIGINAL_NEXT_PLANTS[powerPlantDeck]; + // The shuffled decks: the 7th and 8th smallest plants this deal holds. + const opening = new Set(s.knownPowerPlantDeck.slice(0, 6).map((p) => p.number)); + const nextNumbers = isShuffled + ? [...seen, ...deck.map((p) => p.number)] + .filter((number) => !opening.has(number) && number !== topNumber && number !== 99) + .sort((a, b) => a - b) + .slice(0, 2) + : RUSSIA_ORIGINAL_NEXT_PLANTS[powerPlantDeck as SingleDeck]; const first = deck.filter((p) => p.number === topNumber); const guaranteed = deck.filter((p) => nextNumbers.includes(p.number)); const others = deck.filter((p) => p.number !== topNumber && !nextNumbers.includes(p.number)); @@ -224,19 +275,21 @@ export function createAnalysisScenario( others ); } else { - const lastPlug = lastPlugPlant(powerPlantDeck); - deck = deck.filter((p) => p.number <= lastPlug).concat(deck.filter((p) => p.number > lastPlug)); + deck = deck + .filter((p) => isPlugPlant(p, powerPlantDeck)) + .concat(deck.filter((p) => !isPlugPlant(p, powerPlantDeck))); } } if (name === 'China') { - const low = deck.filter((p) => p.number <= 30).sort((a, b) => a.number - b.number); + const printed = (p: PowerPlant) => Math.floor(p.number); + const low = deck.filter((p) => printed(p) <= 30).sort((a, b) => a.number - b.number); const middle = shuffle( - deck.filter((p) => p.number >= 31 && p.number <= 35).concat(step3 ? [step3] : []), + deck.filter((p) => printed(p) >= 31 && printed(p) <= 35).concat(step3 ? [step3] : []), seed + ':middle' ); deck = low.concat( middle, - deck.filter((p) => p.number >= 36) + deck.filter((p) => printed(p) >= 36) ); } else if (step3) { deck.splice(name === 'UK & Ireland' ? Math.max(0, deck.length - 2) : deck.length, 0, step3); diff --git a/engine/src/deckBuildText.spec.ts b/engine/src/deckBuildText.spec.ts new file mode 100644 index 0000000..c7e068e --- /dev/null +++ b/engine/src/deckBuildText.spec.ts @@ -0,0 +1,134 @@ +import { expect } from 'chai'; +import 'mocha'; +import { deckBuildText, DECK_BUILD_TEMPLATES } from './deckBuildText'; +import { setup } from './engine'; +import { GameOptions, MapName, PowerPlantDeck, PowerPlantType, Variant } from './gamestate'; +import { maps } from './maps'; +import { availableDecks } from './powerPlants'; + +// The text must name the plants the engine actually deals, so read the numbers back +// out of the generated sentences and compare them with real setups. +const listAfter = (sentences: string[], pattern: RegExp): number[] | undefined => { + for (const sentence of sentences) { + const match = pattern.exec(sentence); + if (match) return match[1].split(', ').map(Number); + } + return undefined; +}; + +const singleDecks: PowerPlantDeck[] = ['standard', 'deck1', 'deck2']; +const seeds = ['a', 'b', 'c']; + +describe('Deck build text', () => { + it('fills every placeholder and uses only known templates', () => { + const templates = Object.values(DECK_BUILD_TEMPLATES).map( + (t) => new RegExp('^' + t.replace(/[.*+?^$()|[\]\\]/g, '\\$&').replace(/\\?\{p\d+\\?\}/g, '(.+)') + '$') + ); + for (const map of maps) { + for (const variant of ['original', 'recharged'] as Variant[]) { + for (const deck of availableDecks()) { + for (const players of [2, 3, 4, 5, 6]) { + const options: GameOptions = { map: map.name as MapName, variant, powerPlantDeck: deck }; + const { standard, map: notes } = deckBuildText(map.name, options, players); + for (const sentence of [...standard, ...notes]) { + expect(sentence, `${map.name} ${variant} ${deck}`).not.to.match(/\{p\d+\}|undefined|NaN/); + expect( + templates.some((t) => t.test(sentence)), + `${map.name} ${variant} ${deck}: ${sentence}` + ).to.equal(true); + } + } + } + } + } + }); + + for (const map of maps) { + for (const variant of ['original', 'recharged'] as Variant[]) { + it(`names the plants ${map.name} ${variant} deals with each single deck`, () => { + for (const deck of singleDecks) { + for (const players of [2, 3, 4, 5, 6]) { + const options: GameOptions = { map: map.name as MapName, variant, powerPlantDeck: deck }; + const { standard, map: notes } = deckBuildText(map.name, options, players); + const label = `${map.name} ${variant} ${deck} ${players}P`; + for (const seed of seeds) { + const G = setup(players, options, seed); + const market = [...G.actualMarket, ...G.futureMarket].map((p) => p.number); + const inGame = [...market, ...G.powerPlantsDeck.map((p) => p.number)]; + + const removed = [ + ...(listAfter(notes, /^Power plants? ([\d, ]+) (?:is|are) removed from the game/) ?? + []), + ...(listAfter(notes, /^Power plants ([\d, ]+) also go into the game box/) ?? []), + ]; + for (const number of removed) expect(inGame, `${label}: ${number}`).not.to.include(number); + + const always = listAfter(notes, /^Power plants? ([\d, ]+) always starts? in the market/); + for (const number of always ?? []) expect(market, `${label}: ${number}`).to.include(number); + + const held = listAfter(notes, /^Power plants ([\d, ]+) are set aside at setup/); + for (const number of held ?? []) + expect(inGame, `${label}: ${number}`).not.to.include(number); + + const mines = listAfter(notes, /^The uranium mines \(([\d, ]+)\)/); + if (mines) { + const uranium = G.powerPlantsDeck + .concat(G.actualMarket, G.futureMarket) + .filter((p) => p.type == PowerPlantType.Uranium); + // The player-count removal can take mines out of the deck too. + for (const p of uranium) expect(mines, label).to.include(p.number); + } + + if (variant != 'original') continue; + const russia = notes.find((s) => s.startsWith('The market is ')); + if (russia) { + const [current, future] = /^The market is ([\d, ]+) \/ ([\d, ]+)\./ + .exec(russia)! + .slice(1) + .map((list) => list.split(', ').map(Number)); + expect( + G.actualMarket.map((p) => p.number), + label + ).to.deep.equal(current); + expect( + G.futureMarket.map((p) => p.number), + label + ).to.deep.equal(future); + } else if (!['China', 'Manhattan', 'Europe', 'Middle East'].includes(map.name)) { + const sentence = standard.find((s) => s.startsWith('The market is fixed'))!; + const [current, future] = + /power plants ([\d, ]+) are the current market and ([\d, ]+) the future/ + .exec(sentence)! + .slice(1) + .map((list) => list.split(', ').map(Number)); + expect( + G.actualMarket.map((p) => p.number), + label + ).to.deep.equal(current); + expect( + G.futureMarket.map((p) => p.number), + label + ).to.deep.equal(future); + } + + // The plant on top of the deck: the map's own list where it gives one. + const top = + listAfter( + notes, + /^Power plants? ([\d, ]+) (?:is|are) set aside and then placed on top/ + ) ?? + listAfter(notes, /^Power plant ([\d, ]+) is placed on top of the deck in place/) ?? + (notes.some((s) => s.startsWith('No power plant goes on top')) + ? [] + : listAfter(standard, /^Power plant ([\d, ]+) goes on top of the deck and/)); + // Middle East's Step 1 rule then refills the market from the top of the deck. + if (['China', 'Manhattan', 'Europe', 'Middle East'].includes(map.name) || !top?.length) + continue; + expect(G.powerPlantsDeck[0].number, label).to.equal(top[0]); + } + } + } + }); + } + } +}); diff --git a/engine/src/deckBuildText.ts b/engine/src/deckBuildText.ts new file mode 100644 index 0000000..b3a6c9b --- /dev/null +++ b/engine/src/deckBuildText.ts @@ -0,0 +1,320 @@ +import { + originalTopPlants, + QUEBEC_RECHARGED_TOP_PLANTS, + rechargedMarketPlants, + removedPlants, + RUSSIA_ORIGINAL_NEXT_PLANTS, + SPAIN_STEP_2_PLANTS, +} from './deckChanges'; +import { GameOptions, PowerPlant, PowerPlantDeck, PowerPlantType, SingleDeck } from './gamestate'; +import { gameDeck, isPlugPlant, plantCatalogue, plantCopy } from './powerPlants'; + +// The rules dialog's "Deck build" section, generated from the same tables the decks +// are dealt from, so it names the right plants for the deck in play. Each sentence is +// a template whose {pN} values are plant numbers: the viewer's catalogues translate +// the templates, so keep every one a single string constant. +export const DECK_BUILD_TEMPLATES = { + shuffledSample: 'All three decks are shuffled together and a standard-sized deck is dealt from them.', + shuffledFull: 'All three decks are shuffled together into one deck.', + shuffledUnique: 'All three decks are shuffled together, keeping one random copy of each plant number.', + shuffledLegend: + 'Lists with three parts give the Original deck / Deck 1 / Deck 2 plants; each rule applies only to the plants dealt into this game.', + plugPlants: + 'The low power plants are the "plug plants" ({p0}), named for the plug on the back of the printed cards.', + rechargedMarket: + 'Shuffle the low plants, draw 8 and sort them ascending: the 4 cheapest form the current market, the next 4 the future market.', + rechargedTop: 'One of the remaining low plants goes face down on top of the draw deck.', + rechargedRemoval: + 'Player-count removal: 2 players remove 1 low + 5 higher plants; 3 players remove 2 low + 6 higher; 4 players remove 1 low + 3 higher; 5-6 players remove none.', + rechargedRest: 'The leftover low plants are shuffled into the deck, with the Step 3 card on the bottom.', + originalMarket: 'The market is fixed: power plants {p0} are the current market and {p1} the future market.', + originalMarketShuffled: + 'The 8 smallest plants dealt form the market: the 4 cheapest are the current market, the next 4 the future market.', + originalSetAside: + 'Power plant {p0} and the Step 3 card are set aside and the rest of the deck is shuffled, then 8 random plants are removed for 2-3 players, 4 for 4 players, and none for 5-6 players.', + originalSetAsideNone: + 'The Step 3 card is set aside and the rest of the deck is shuffled, then 8 random plants are removed for 2-3 players, 4 for 4 players, and none for 5-6 players.', + originalTop: 'Power plant {p0} goes on top of the deck and the Step 3 card on the bottom.', + originalTopIfDealt: 'Power plant {p0} goes on top of the deck if it was dealt, and the Step 3 card on the bottom.', + originalTopNone: 'The Step 3 card goes on the bottom of the deck.', + standardSetup: 'Otherwise standard setup.', + removedOne: 'Power plant {p0} is removed from the game.', + removedMany: 'Power plants {p0} are removed from the game.', + noFurtherRemoval: 'No further power plants are removed for the number of players.', + marketAlwaysOne: + 'Power plant {p0} always starts in the market; the rest of the market is drawn from the low plants.', + marketAlwaysMany: + 'Power plants {p0} always start in the market; the rest of the market is drawn from the low plants.', + australiaMines: 'The uranium mines ({p0}) stay in the deck.', + brazilGarbage: + 'Garbage plants {p0}, the ones above the plug plants, are set aside during the player-count removal and shuffled back in, so no garbage plant ever leaves the game.', + brazilOriginalGarbage: 'Garbage plants are excluded from the player-count removal and shuffled back in.', + topInOrderOne: 'Power plant {p0} is set aside and then placed on top of the deck.', + topInOrderMany: 'Power plants {p0} are set aside and then placed on top of the deck, in that order.', + franceTopInPlace: 'Power plant {p0} is placed on top of the deck in place of the usual top plant.', + franceNoTop: 'No power plant goes on top of the deck.', + franceRemoval: + 'Removal by player count: 2 players remove 6 higher plants, 3 players remove 1 low and 6 higher, 4 players remove 3 higher.', + bremenMarket: + 'The opening market of eight is drawn from the low plants; of the low plants left over, one is placed on top of the draw deck and the rest are shuffled into it, with the Step 3 card on the bottom.', + chinaOrder: + 'The deck is ordered, not shuffled: the plants up to 30 in ascending order on top, then plants 31-35 shuffled together with the Step 3 card, then the plants from 36 up shuffled on the bottom.', + chinaMarket: 'The starting market has one plant per player and the future market starts empty.', + europeMarket: + 'The power plant market starts as 4 current + 5 future power plants (9 total), all drawn from the plug plants; the top card of the draw deck is never a plug plant.', + manhattanPlug: + 'Plug plants are put in the game box at random until nine remain: 8 form the starting market and 1 goes on top of the deck.', + manhattanRest: 'The rest of the deck is random with no plug plants. The Step 3 card is removed from the game.', + manhattanBoxed: 'Power plants {p0} also go into the game box.', + northernEuropeRegional: + 'The regions in play swap in regional versions of certain power plants (same numbers, different fuel or output).', + northernEuropeShuffled: + 'Each regional power plant in play takes the place of a dealt plant with its number, and every other dealt copy of that number leaves the game. A regional plant whose number was not dealt is shuffled into the deck.', + quebecMarketFrom: 'The starting market is drawn from power plants {p0}.', + quebecTopBeneath: 'One more low plant goes on top of the deck, with power plants {p0} directly beneath it.', + quebecTopVery: 'Power plants {p0} go on the very top of the deck.', + quebecEcological: 'Ecological plants are never removed during setup.', + quebecEcologicalOriginal: 'Ecological plants are excluded from the player-count removal.', + quebecShuffledRecharged: + 'One plug card goes on top of the deck, with the two smallest dealt ecological plants not in the market directly beneath it.', + quebecShuffledOriginal: + 'Power plant {p0} goes on top of the deck if it was dealt, otherwise the smallest plug card left, with the two smallest dealt ecological plants not in the market directly beneath it.', + russiaRechargedMarket: + 'The market has 6 plants (3 current, 3 future) drawn at random from the low plants; the undrawn low plants sit shuffled on top of the deck.', + russiaRechargedRemoval: + 'Removal by player count (higher plants only): 2 players remove 6, 3 players remove 8, 4 players remove 4.', + russiaOriginalMarket: 'The market is {p0} / {p1}.', + russiaOriginalTop: + 'Power plant {p0} goes on top of the deck, then five shuffled cards (plants {p1} and the top three of the deck), then the rest, with the Step 3 card on the bottom.', + russiaShuffledMarket: 'The six smallest dealt plants open the market (3 current, 3 future).', + russiaShuffledTop: + 'Power plant {p0} goes on top of the deck if it was dealt, then five shuffled cards (the 7th and 8th smallest plants and the top three of the deck).', + spainHeld: + 'Power plants {p0} are set aside at setup; when Step 2 begins they are placed on top of the deck, smallest on top.', + ukStep3: 'The Step 3 card is placed third from the bottom of the deck (two plants below it).', +} as const; + +type Template = keyof typeof DECK_BUILD_TEMPLATES; + +export interface DeckBuildText { + // How the deck is built when a map says nothing special, for the deck in play. + standard: string[]; + // This map's departure from it; empty when the map builds its deck normally. + map: string[]; +} + +function fill(template: Template, ...values: string[]): string { + return DECK_BUILD_TEMPLATES[template].replace(/\{p(\d+)\}/g, (_, i) => values[+i]); +} + +const isShuffled = (deck: PowerPlantDeck) => deck == 'shuffled' || deck == 'shuffledUnique'; +const SINGLE_DECKS: SingleDeck[] = ['standard', 'deck1', 'deck2']; +// The shuffled decks' copy numbering (see plantCopy). +const COPY: Record = { standard: 0, deck1: 0.1, deck2: 0.2 }; +const eachDeck = (numbers: (deck: SingleDeck) => number[]) => ([] as number[]).concat(...SINGLE_DECKS.map(numbers)); + +// "18, 22, 27" for a single deck; "18, 22, 27 / 15, 16, 26 / 17, 24, 28" (Original +// deck / Deck 1 / Deck 2, by copy) for the shuffled decks. +function plantList(numbers: number[], deck: PowerPlantDeck): string { + const join = (list: number[]) => list.sort((a, b) => a - b).join(', '); + if (!isShuffled(deck)) return numbers.join(', '); + return [0, 1, 2] + .map((copy) => join(numbers.filter((n) => plantCopy(n) == copy).map(Math.floor)) || '–') + .join(' / '); +} + +function removed(mapName: string, deck: PowerPlantDeck, numPlayers: number, variant: string): string[] { + let numbers = removedPlants(mapName, deck, numPlayers, variant); + // India's single decks leave their plant out of the catalogue itself. + if (mapName == 'India' && !isShuffled(deck)) { + const india = new Set(plantCatalogue('India', deck).map((p) => p.number)); + numbers = plantCatalogue('', deck) + .map((p) => p.number) + .filter((n) => !india.has(n)); + } + if (!numbers.length) return []; + return [fill(numbers.length == 1 ? 'removedOne' : 'removedMany', plantList(numbers, deck))]; +} + +function plugRange(deck: PowerPlantDeck): string { + const range = (single: PowerPlantDeck) => { + const plug = plantCatalogue('', single) + .filter((p) => p.type != PowerPlantType.Step3 && isPlugPlant(p, single)) + .map((p) => p.number); + return `${plug[0]}-${plug[plug.length - 1]}`; + }; + return isShuffled(deck) ? SINGLE_DECKS.map(range).join(' / ') : range(deck); +} + +// The plants in a single-deck game once the map's removals are made, smallest first. +function dealtPlants(mapName: string, deck: PowerPlantDeck, numPlayers: number, variant: string): PowerPlant[] { + const gone = removedPlants(mapName, deck, numPlayers, variant); + return plantCatalogue(mapName, deck).filter((p) => p.type != PowerPlantType.Step3 && !gone.includes(p.number)); +} + +const numbers = (plants: PowerPlant[]) => plants.map((p) => p.number).join(', '); + +// The Original edition's top plant: the shuffled decks use the standard deck's. +function topSentences(top: number[], deck: PowerPlantDeck): string[] { + if (!top.length) return [fill('originalTopNone')]; + return [fill(isShuffled(deck) ? 'originalTopIfDealt' : 'originalTop', top.join(', '))]; +} + +function standardText(mapName: string, options: GameOptions, numPlayers: number): string[] { + const deck = gameDeck(options); + const intro = !isShuffled(deck) + ? [] + : [ + fill( + deck == 'shuffledUnique' + ? 'shuffledUnique' + : options.shuffledSample + ? 'shuffledSample' + : 'shuffledFull' + ), + fill('shuffledLegend'), + ]; + if (options.variant == 'original') { + // A top plant the map removes (Deck 2's 13 on India and Bremen) leaves no top plant. + const gone = removedPlants(mapName, deck, numPlayers, 'original'); + const inGame = new Set(dealtPlants(mapName, deck, numPlayers, 'original').map((p) => p.number)); + const top = originalTopPlants('', deck).filter((n) => (isShuffled(deck) ? !gone.includes(n) : inGame.has(n))); + const market = isShuffled(deck) + ? [fill('originalMarketShuffled')] + : (() => { + const plants = dealtPlants(mapName, deck, numPlayers, 'original'); + return [fill('originalMarket', numbers(plants.slice(0, 4)), numbers(plants.slice(4, 8)))]; + })(); + return [ + ...intro, + ...market, + top.length ? fill('originalSetAside', top.join(', ')) : fill('originalSetAsideNone'), + ...topSentences(top, deck), + ]; + } + return [ + ...intro, + fill('plugPlants', plugRange(deck)), + fill('rechargedMarket'), + fill('rechargedTop'), + fill('rechargedRemoval'), + fill('rechargedRest'), + ]; +} + +function many(one: Template, more: Template, plants: number[], deck: PowerPlantDeck): string { + return fill(plants.length == 1 && !isShuffled(deck) ? one : more, plantList(plants, deck)); +} + +function mapText(mapName: string, options: GameOptions, numPlayers: number): string[] { + const deck = gameDeck(options); + const variant = options.variant ?? 'original'; + const original = variant == 'original'; + const shuffled = isShuffled(deck); + const gone = removed(mapName, deck, numPlayers, variant); + switch (mapName) { + case 'Australia': { + const mines = (single: SingleDeck) => + dealtPlants(mapName, single, numPlayers, variant) + .filter((p) => p.type == PowerPlantType.Uranium) + .map((p) => p.number + (shuffled ? COPY[single] : 0)); + const all = shuffled ? eachDeck(mines) : mines(deck as SingleDeck); + return [...gone, fill('australiaMines', plantList(all, deck)), fill('standardSetup')]; + } + case 'Brazil': { + if (original) { + const top = originalTopPlants(mapName, deck); + return [many('topInOrderOne', 'topInOrderMany', top, deck), fill('brazilOriginalGarbage')]; + } + const garbage = (single: SingleDeck) => + plantCatalogue(mapName, single) + .filter((p) => p.type == PowerPlantType.Garbage && !isPlugPlant(p, single)) + .map((p) => p.number + (shuffled ? COPY[single] : 0)); + const highGarbage = shuffled ? eachDeck(garbage) : garbage(deck as SingleDeck); + return [ + many('marketAlwaysOne', 'marketAlwaysMany', rechargedMarketPlants(mapName, deck), deck), + fill('brazilGarbage', plantList(highGarbage, deck)), + ]; + } + case 'Bremen': + return [...gone, fill('noFurtherRemoval'), ...(original ? [] : [fill('bremenMarket')])]; + case 'China': + return [...gone, fill('chinaOrder'), fill('chinaMarket')]; + case 'Europe': + return [fill('europeMarket')]; + case 'France': { + if (original) { + const top = originalTopPlants(mapName, deck); + return [...gone, fill(top.length ? 'franceTopInPlace' : 'franceNoTop', top.join(', '))]; + } + return [ + ...gone, + many('marketAlwaysOne', 'marketAlwaysMany', rechargedMarketPlants(mapName, deck), deck), + fill('franceRemoval'), + ]; + } + case 'India': + case 'South Africa': + return [...gone, fill('standardSetup')]; + case 'Manhattan': { + const boxed = removedPlants(mapName, deck, numPlayers, variant); + return [ + fill('manhattanPlug'), + fill('manhattanRest'), + ...(boxed.length ? [fill('manhattanBoxed', plantList(boxed, deck))] : []), + ]; + } + case 'Northern Europe': + return [fill(shuffled ? 'northernEuropeShuffled' : 'northernEuropeRegional')]; + case 'Quebec': { + const ecological = fill(original ? 'quebecEcologicalOriginal' : 'quebecEcological'); + if (shuffled) { + return [ + original + ? fill('quebecShuffledOriginal', originalTopPlants('', deck).join(', ')) + : fill('quebecShuffledRecharged'), + fill('quebecEcological'), + ]; + } + if (original) + return [many('topInOrderOne', 'topInOrderMany', originalTopPlants(mapName, deck), deck), ecological]; + const market = rechargedMarketPlants(mapName, deck); + const top = QUEBEC_RECHARGED_TOP_PLANTS[deck as SingleDeck]; + return [ + market.length + ? many('marketAlwaysOne', 'marketAlwaysMany', market, deck) + : fill('quebecMarketFrom', '3-10, 13'), + ...(top.length + ? [fill(deck == 'standard' ? 'quebecTopBeneath' : 'quebecTopVery', top.join(', '))] + : []), + ecological, + ]; + } + case 'Russia': { + if (!original) return [...gone, fill('russiaRechargedMarket'), fill('russiaRechargedRemoval')]; + const top = originalTopPlants('', deck).join(', '); + if (shuffled) return [...gone, fill('russiaShuffledMarket'), fill('russiaShuffledTop', top)]; + const plants = dealtPlants(mapName, deck, numPlayers, variant); + const next = RUSSIA_ORIGINAL_NEXT_PLANTS[deck as SingleDeck]; + return [ + ...gone, + fill('russiaOriginalMarket', numbers(plants.slice(0, 3)), numbers(plants.slice(3, 6))), + fill('russiaOriginalTop', top, next.join(', ')), + ]; + } + case 'Spain & Portugal': { + const held = shuffled + ? eachDeck((single) => SPAIN_STEP_2_PLANTS[single].map((n) => n + COPY[single])) + : SPAIN_STEP_2_PLANTS[deck as SingleDeck]; + return [fill('spainHeld', plantList(held, deck))]; + } + case 'UK & Ireland': + return [fill('ukStep3'), fill('standardSetup')]; + default: + return []; + } +} + +export function deckBuildText(mapName: string, options: GameOptions, numPlayers: number): DeckBuildText { + return { standard: standardText(mapName, options, numPlayers), map: mapText(mapName, options, numPlayers) }; +} diff --git a/engine/src/deckChanges.ts b/engine/src/deckChanges.ts index c5afa95..73113d1 100644 --- a/engine/src/deckChanges.ts +++ b/engine/src/deckChanges.ts @@ -7,38 +7,48 @@ import { PowerPlantDeck, SingleDeck } from './gamestate'; type PerDeck = Record; -// The shuffled decks are only offered on maps without these rules (see availableDecks). const isShuffled = (deck: PowerPlantDeck): deck is 'shuffled' | 'shuffledUnique' => deck == 'shuffled' || deck == 'shuffledUnique'; -// Plants out of the game from the start. Manhattan's boxed Step 3 card and India's -// plant (see plantCatalogue) are handled where those decks are built. +// The shuffled decks follow every deck's rule at once, for whichever copies were +// dealt: Deck 1's and Deck 2's copies are numbered n.1 and n.2 (see plantCopy). +function forDeck(table: PerDeck, deck: PowerPlantDeck): number[] { + if (!isShuffled(deck)) return table[deck]; + return [...table.standard, ...table.deck1.map((n) => n + 0.1), ...table.deck2.map((n) => n + 0.2)]; +} + +// Plants out of the game from the start. Manhattan's boxed Step 3 card is handled +// where its deck is built, and so is India's plant in the single decks (see +// plantCatalogue). export function removedPlants(mapName: string, deck: PowerPlantDeck, numPlayers: number, variant: string): number[] { - if (isShuffled(deck)) return []; const fewPlayers = numPlayers <= 3; switch (mapName) { case 'France': // The New Power Plants rulebook: on France, simply remove plant 11. - return { standard: [13], deck1: variant == 'original' ? [11] : [10], deck2: [11] }[deck]; + return forDeck({ standard: [13], deck1: variant == 'original' ? [11] : [10], deck2: [11] }, deck); case 'Russia': - return { standard: [6, 14], deck1: [6, 21], deck2: [5, 14] }[deck]; + return forDeck({ standard: [6, 14], deck1: [6, 21], deck2: [5, 14] }, deck); + case 'India': + return isShuffled(deck) ? forDeck({ standard: [11], deck1: [8], deck2: [13] }, deck) : []; case 'Australia': - return { standard: [17], deck1: [19], deck2: [21] }[deck]; + return forDeck({ standard: [17], deck1: [19], deck2: [21] }, deck); case 'South Africa': - return { standard: [7], deck1: [7], deck2: [10] }[deck]; + return forDeck({ standard: [7], deck1: [7], deck2: [10] }, deck); case 'Spain & Portugal': // Held back until Step 2, then put on top of the deck. - return SPAIN_STEP_2_PLANTS[deck]; + return spainStep2Plants(deck); case 'Bremen': { const table: PerDeck = { standard: [11, 17, 23, 28, 34, 36, 38, 39, 46, ...(numPlayers <= 4 ? [31, 50] : [])], deck1: [8, 19, 24, 31, 37, 38, 42, 46, 50, ...(numPlayers <= 4 ? [34, 44] : [])], deck2: [13, 21, 32, 33, 34, 37, 38, 46, 50, ...(numPlayers <= 4 ? [22, 44] : [])], }; - return table[deck]; + return forDeck(table, deck); } case 'Manhattan': - return fewPlayers ? { standard: [20, 22, 37], deck1: [16, 28, 38], deck2: [22, 28, 36] }[deck] : []; + return fewPlayers + ? forDeck({ standard: [20, 22, 37], deck1: [16, 28, 38], deck2: [22, 28, 36] }, deck) + : []; case 'China': { const table: PerDeck = { standard: [ @@ -57,7 +67,11 @@ export function removedPlants(mapName: string, deck: PowerPlantDeck, numPlayers: [3, 6, 31], ], }; - return table[deck][fewPlayers ? 0 : numPlayers == 4 ? 1 : 2]; + const column = fewPlayers ? 0 : numPlayers == 4 ? 1 : 2; + return forDeck( + { standard: table.standard[column], deck1: table.deck1[column], deck2: table.deck2[column] }, + deck + ); } default: return []; @@ -66,39 +80,41 @@ export function removedPlants(mapName: string, deck: PowerPlantDeck, numPlayers: // Original edition: the plants placed on top of the deck, topmost first, once the // eight smallest plants have opened the market. Plants not in the game are skipped. +// The shuffled decks don't stack every deck's top plants: they use the standard deck's. export function originalTopPlants(mapName: string, deck: PowerPlantDeck): number[] { - // The shuffled decks put the standard deck's 13 on top. - if (isShuffled(deck)) return [13]; - switch (mapName) { - case 'France': - // The nuclear plant comes up first; Deck 1's (08) already opens the market. - return { standard: [11], deck1: [], deck2: [13] }[deck]; - case 'Brazil': - // The low biogas plants that don't open the market follow the usual top plant. - return { standard: [13, 14], deck1: [11], deck2: [13, 14] }[deck]; - case 'Quebec': - return { standard: [13, 18, 22], deck1: [11, 15, 16], deck2: [11, 17, 24] }[deck]; - default: - return { standard: [13], deck1: [11], deck2: [13] }[deck]; - } + const table = ((): PerDeck => { + switch (mapName) { + case 'France': + // The nuclear plant comes up first; Deck 1's (08) already opens the market. + return { standard: [11], deck1: [], deck2: [13] }; + case 'Brazil': + // The low biogas plants that don't open the market follow the usual top plant. + return { standard: [13, 14], deck1: [11], deck2: [13, 14] }; + case 'Quebec': + return { standard: [13, 18, 22], deck1: [11, 15, 16], deck2: [11, 17, 24] }; + default: + return { standard: [13], deck1: [11], deck2: [13] }; + } + })(); + return table[isShuffled(deck) ? 'standard' : deck]; } // Original Russia: the two plants shuffled into the top five cards, beneath the top -// plant; they are the two plants after the six-plant opening market. +// plant; they are the two plants after the six-plant opening market. The shuffled +// decks take the 7th and 8th smallest dealt plants instead (see maps/russia.ts). export const RUSSIA_ORIGINAL_NEXT_PLANTS: PerDeck = { standard: [10, 11], deck1: [8, 9], deck2: [10, 11] }; // Recharged edition: plants that always open the market; the rest of its eight are // drawn from the remaining plug cards. export function rechargedMarketPlants(mapName: string, deck: PowerPlantDeck): number[] { - if (isShuffled(deck)) return []; switch (mapName) { case 'France': - return { standard: [11], deck1: [8], deck2: [13] }[deck]; + return forDeck({ standard: [11], deck1: [8], deck2: [13] }, deck); case 'Brazil': - return { standard: [6, 14], deck1: [6], deck2: [5, 14] }[deck]; + return forDeck({ standard: [6, 14], deck1: [6], deck2: [5, 14] }, deck); case 'Quebec': // The standard deck's Québec market is drawn from 03–10 plus 13 instead. - return { standard: [], deck1: [11, 15, 16], deck2: [11] }[deck]; + return forDeck({ standard: [], deck1: [11, 15, 16], deck2: [11] }, deck); default: return []; } @@ -106,6 +122,7 @@ export function rechargedMarketPlants(mapName: string, deck: PowerPlantDeck): nu // Recharged Québec: plants set aside and placed on top of the finished deck, topmost // first. The standard deck puts them beneath one plug card; Deck 2 on the very top. +// The shuffled decks follow the rule's purpose instead (see maps/quebec.ts). export const QUEBEC_RECHARGED_TOP_PLANTS: PerDeck = { standard: [18, 22], deck1: [], deck2: [17, 24] }; // Spain & Portugal: the ecological plants held back until Step 2, then drawn first. @@ -114,3 +131,8 @@ export const SPAIN_STEP_2_PLANTS: PerDeck = { deck1: [15, 16, 26], deck2: [17, 24, 28], }; + +// Every copy a game can hold back: in the shuffled decks, all three decks' plants. +export function spainStep2Plants(deck: PowerPlantDeck): number[] { + return forDeck(SPAIN_STEP_2_PLANTS, deck); +} diff --git a/engine/src/decks.spec.ts b/engine/src/decks.spec.ts index 332e513..78862e1 100644 --- a/engine/src/decks.spec.ts +++ b/engine/src/decks.spec.ts @@ -2,19 +2,35 @@ import { expect } from 'chai'; import { range } from 'lodash'; import 'mocha'; import seedrandom from 'seedrandom'; +import { createAnalysisScenario } from './analysis'; import { availableMoves } from './available-moves'; -import { QUEBEC_RECHARGED_TOP_PLANTS, removedPlants, SPAIN_STEP_2_PLANTS } from './deckChanges'; +import { + QUEBEC_RECHARGED_TOP_PLANTS, + rechargedMarketPlants, + removedPlants, + spainStep2Plants, + SPAIN_STEP_2_PLANTS, +} from './deckChanges'; import { ended, move, moveAI, reconstructionOptions, setup, updatePlayerCapacity } from './engine'; -import { GameState, MapName, Phase, PowerPlantDeck, PowerPlantType, ResourceType, Variant } from './gamestate'; +import { + GameState, + MapName, + Phase, + PowerPlant, + PowerPlantDeck, + PowerPlantType, + ResourceType, + Variant, +} from './gamestate'; import { maps, mapsRecharged } from './maps'; import { Move, MoveName } from './move'; import { alternatePowerPlants, dealtCatalogue, deck1PowerPlants, + isEcological, isPlugPlant, labelledPlant, - NUMBERED_SETUP_MAPS, plantCatalogue, plantLabel, powerPlants, @@ -383,15 +399,13 @@ describe('shuffled power plant decks', () => { expect(labelledPlant('46', undefined)).to.equal(46); }); - it('is only offered on maps whose rules name no plant numbers', () => { + it('is offered on every map and edition', () => { for (const deck of ['shuffled', 'shuffledUnique'] as PowerPlantDeck[]) { - for (const map of NUMBERED_SETUP_MAPS as MapName[]) { - const G = setup(4, { map, variant: 'recharged', powerPlantDeck: deck }, 'blocked'); - expect(G.options, `${map} ${deck}`).to.not.have.property('powerPlantDeck'); - } - for (const map of ['USA', 'Germany', 'Italy', 'Benelux', 'Europe', 'UK & Ireland'] as MapName[]) { - const G = setup(4, { map, variant: 'recharged', powerPlantDeck: deck }, 'offered'); - expect(G.options.powerPlantDeck, `${map} ${deck}`).to.equal(deck); + for (const variant of ['original', 'recharged'] as Variant[]) { + for (const map of new Set((variant == 'original' ? maps : mapsRecharged).map((m) => m.name))) { + const G = setup(4, { map: map as MapName, variant, powerPlantDeck: deck }, 'offered'); + expect(G.options.powerPlantDeck, `${map} ${variant} ${deck}`).to.equal(deck); + } } } }); @@ -566,3 +580,350 @@ describe('shuffled power plant decks', () => { } }); }); + +describe('shuffled power plant decks on maps with deck-specific changes', function () { + this.timeout(120000); + // Every map whose rules name plant numbers, now with all three decks' rules at once. + const combinedMaps: [MapName, Variant[]][] = [ + ['Australia', ['original', 'recharged']], + ['Brazil', ['original', 'recharged']], + ['Bremen', ['original', 'recharged']], + ['China', ['original', 'recharged']], + ['France', ['original', 'recharged']], + ['India', ['original', 'recharged']], + ['Manhattan', ['original', 'recharged']], + ['Middle East', ['original', 'recharged']], + ['Quebec', ['original', 'recharged']], + ['Russia', ['original', 'recharged']], + ['South Africa', ['original', 'recharged']], + ['Spain & Portugal', ['original', 'recharged']], + ]; + const decks: PowerPlantDeck[] = ['shuffled', 'shuffledUnique']; + // The map setups deal from the seeded catalogue before any other draw. + const dealtFor = (map: MapName, deck: PowerPlantDeck, seed: string) => + numbers(dealtCatalogue(map, deck, seedrandom(seed), deck == 'shuffled')); + + it("follows every deck's removals for the copies dealt, and deals no other card", () => { + for (const [map, variants] of combinedMaps) { + for (const variant of variants) { + for (const deck of decks) { + for (const numPlayers of [2, 3, 4, 5, 6]) { + const seed = `${map}-${variant}-${deck}-${numPlayers}`; + const G = setup(numPlayers, { map, variant, powerPlantDeck: deck }, seed); + const removed = removedPlants(map, deck, numPlayers, variant); + const dealt = dealtFor(map, deck, seed); + for (const number of numbers(visible(G))) { + expect(removed, `${seed}: ${number} is removed`).to.not.include(number); + expect(dealt, `${seed}: ${number} was dealt`).to.include(number); + } + expect(G.options.powerPlantDeck, seed).to.equal(deck); + } + } + } + } + expect(removedPlants('Australia', 'shuffled', 4, 'recharged')).to.deep.equal([17, 19.1, 21.2]); + expect(removedPlants('France', 'shuffled', 4, 'original')).to.deep.equal([13, 11.1, 11.2]); + expect(removedPlants('France', 'shuffled', 4, 'recharged')).to.deep.equal([13, 10.1, 11.2]); + expect(removedPlants('India', 'shuffled', 4, 'recharged')).to.deep.equal([11, 8.1, 13.2]); + expect(removedPlants('India', 'standard', 4, 'recharged')).to.deep.equal([]); + }); + + it("opens the Recharged France and Brazil markets with every dealt copy of the decks' plants", () => { + for (const map of ['France', 'Brazil'] as MapName[]) { + for (const deck of decks) { + for (const seed of range(12).map((i) => `${map}-${deck}-${i}`)) { + const G = setup(4, { map, variant: 'recharged', powerPlantDeck: deck }, seed); + const forced = rechargedMarketPlants(map, deck); + const market = numbers([...G.actualMarket, ...G.futureMarket]); + expect(market, seed).to.include.members( + dealtFor(map, deck, seed).filter((n) => forced.includes(n)) + ); + expect(market.length, seed).to.equal(8); + expect(market).to.deep.equal([...market].sort((a, b) => a - b)); + } + } + } + expect(rechargedMarketPlants('Brazil', 'shuffled')).to.deep.equal([6, 14, 6.1, 5.2, 14.2]); + }); + + it('keeps every dealt Brazil biogas plant above the plug cards in the game', () => { + for (const variant of ['original', 'recharged'] as Variant[]) { + for (const deck of decks) { + const seed = `brazil-biogas-${variant}-${deck}`; + const G = setup(2, { map: 'Brazil', variant, powerPlantDeck: deck }, seed); + const biogas = dealtCatalogue('Brazil', deck, seedrandom(seed), deck == 'shuffled').filter( + (pp) => pp.type == PowerPlantType.Garbage && !isPlugPlant(pp, deck) + ); + expect(numbers(visible(G)), seed).to.include.members(numbers(biogas)); + } + } + }); + + it("uses the standard deck's Original top plants, when dealt", () => { + for (const seed of range(8).map((i) => `france-top-${i}`)) { + const G = setup(4, { map: 'France', variant: 'original', powerPlantDeck: 'shuffledUnique' }, seed); + if (dealtFor('France', 'shuffledUnique', seed).includes(11)) + expect(G.powerPlantsDeck[0].number, seed).to.equal(11); + else expect(numbers(visible(G)), seed).to.not.include(11); + } + }); + + it('sorts China by printed number, extra copies included', () => { + for (const deck of decks) { + for (const numPlayers of [2, 4, 6]) { + const seed = `china-${deck}-${numPlayers}`; + const G = setup(numPlayers, { map: 'China', variant: 'recharged', powerPlantDeck: deck }, seed); + const low = [...G.actualMarket, ...G.powerPlantsDeck].filter((pp) => Math.floor(pp.number) <= 30); + expect(numbers(low), seed).to.deep.equal([...numbers(low)].sort((a, b) => a - b)); + expect(G.actualMarket.length, seed).to.equal(numPlayers); + const removed = removedPlants('China', deck, numPlayers, 'recharged'); + const kept = dealtFor('China', deck, seed).filter((n) => !removed.includes(n)); + expect(numbers(visible(G)).sort(), seed).to.deep.equal(kept.sort()); + } + } + }); + + it('holds back the dealt Spain & Portugal ecological copies and returns them at Step 2', () => { + for (const deck of decks) { + const seed = `spain-${deck}`; + let G = setup(4, { map: 'Spain & Portugal', variant: 'recharged', powerPlantDeck: deck }, seed); + const held = numbers(G.heldPowerPlants!); + expect(held).to.deep.equal( + dealtFor('Spain & Portugal', deck, seed).filter((n) => spainStep2Plants(deck).includes(n)) + ); + expect(held.length, deck).to.be.greaterThan(0); + expect(numbers(visible(G))).to.not.include.members(held); + G.players.forEach((p) => (p.isAI = true)); + while (G.step == 1 && !ended(G)) G = moveAI(G, G.currentPlayers[0]); + // An early Step 3 card begins Step 2 first, then Step 3 shuffles the rest in and + // discards the smallest plant, which can be one that just came back. + const events = G.log.map((item) => (item.type == 'event' ? item.event : '')); + const step3First = events.some((e) => e.includes('the Step 3 card came first')); + const top = numbers([ + ...G.actualMarket, + ...G.futureMarket, + ...(step3First ? G.powerPlantsDeck : G.powerPlantsDeck.slice(0, held.length)), + ]); + const discarded = held.filter((n) => events.some((e) => e.includes(`${plantLabel(n)} discarded`))); + expect([...top, ...discarded], deck).to.include.members(held); + } + expect(setup(4, { map: 'Spain & Portugal', variant: 'recharged' }, 's')).to.not.have.property( + 'heldPowerPlants' + ); + }); + + it('builds the India deck with India garbage plants', () => { + const india = plantCatalogue('India', 'shuffled').filter((pp) => pp.type == PowerPlantType.Garbage); + const plain = plantCatalogue('USA', 'shuffled').filter((pp) => pp.type == PowerPlantType.Garbage); + expect(india.map((pp) => pp.cost)).to.deep.equal(plain.map((pp) => pp.cost + 1)); + }); + + for (const [map, variant, deck] of [ + ['Australia', 'recharged', 'shuffledUnique'], + ['Brazil', 'original', 'shuffled'], + ['Bremen', 'recharged', 'shuffled'], + ['China', 'recharged', 'shuffledUnique'], + ['France', 'recharged', 'shuffled'], + ['India', 'original', 'shuffledUnique'], + ['Manhattan', 'recharged', 'shuffled'], + ['Middle East', 'recharged', 'shuffled'], + ['Russia', 'recharged', 'shuffledUnique'], + ['South Africa', 'original', 'shuffled'], + ['Spain & Portugal', 'original', 'shuffled'], + ] as [MapName, Variant, PowerPlantDeck][]) { + it(`plays a whole bot game on ${map} ${variant} with ${deck}, rebuilds its deck and replays it`, () => { + let G = setup(4, { map, variant, powerPlantDeck: deck }, `bots-${map}-${deck}`); + G.players.forEach((p, i) => { + p.name = `AI ${i}`; + p.isAI = true; + }); + for (let turn = 0; turn < 8000 && !ended(G) && G.currentPlayers.length > 0; turn++) { + if (turn % 60 == 0) { + const scenario = createAnalysisScenario(G, { player: 0, seed: `analysis-${turn}` }); + expect(scenario.powerPlantsDeck.length, `turn ${turn}`).to.equal(G.cardsLeft); + } + G = moveAI(G, G.currentPlayers[0]); + } + expect(ended(G), 'game finished').to.be.true; + + let replay = setup(4, G.options, G.seed); + replay.players.forEach((p, i) => { + p.name = `AI ${i}`; + p.isAI = true; + }); + for (const item of G.log) { + if (item.type === 'move') replay = move(replay, item.move, item.player); + } + expect(replay.players.map((p) => p.money)).to.deep.equal(G.players.map((p) => p.money)); + }); + } +}); + +describe('shuffled power plant decks where the decks disagree', function () { + this.timeout(120000); + const decks: PowerPlantDeck[] = ['shuffled', 'shuffledUnique']; + const variants: Variant[] = ['original', 'recharged']; + const dealtFor = (map: MapName, deck: PowerPlantDeck, seed: string) => + dealtCatalogue(map, deck, seedrandom(seed), deck == 'shuffled'); + const sorted = (plants: { number: number }[]) => [...plants].sort((a, b) => a.number - b.number); + const playAll = (G: GameState, until: (G: GameState) => boolean) => { + G.players.forEach((p, i) => { + p.name = `AI ${i}`; + p.isAI = true; + }); + for (let turn = 0; turn < 8000 && !ended(G) && !until(G); turn++) G = moveAI(G, G.currentPlayers[0]); + return G; + }; + + const checkRegionalPlants = (G: GameState, label: string) => { + const regions = new Set(G.map.cities.map((city) => city.region)); + const northernEurope = maps.find((m) => m.name == 'Northern Europe')!; + const market = [...G.actualMarket, ...G.futureMarket]; + expect(market.length, label).to.equal(8); + expect(numbers(market), label).to.deep.equal(numbers(sorted(market))); + expect(G.cardsLeft, label).to.equal(G.powerPlantsDeck.length); + let checked = 0; + for (const region of regions) { + for (const regional of northernEurope.regionalPowerPlants![region] || []) { + const copies = visible(G).filter((pp) => Math.floor(pp.number) == regional.number); + expect(copies, `${label}: ${regional.number}`).to.deep.equal([regional]); + checked++; + } + } + expect(checked, label).to.be.greaterThan(0); + }; + + it('deals each Northern Europe regional plant in play once, in place of every copy of its number', () => { + for (const variant of variants) { + for (const deck of decks) { + for (const seed of range(10).map((i) => `ne-${variant}-${deck}-${i}`)) { + checkRegionalPlants( + setup(4, { map: 'Northern Europe', variant, powerPlantDeck: deck }, seed), + seed + ); + } + } + } + }); + + it('adds a Northern Europe regional plant whose number was not dealt', () => { + let added = 0; + for (const seed of range(40).map((i) => `ne-added-${i}`)) { + const G = setup(4, { map: 'Northern Europe', variant: 'recharged', powerPlantDeck: 'shuffled' }, seed); + const dealt = dealtFor('Northern Europe', 'shuffled', seed).map((pp) => Math.floor(pp.number)); + const regions = new Set(G.map.cities.map((city) => city.region)); + for (const region of regions) { + for (const regional of maps.find((m) => m.name == 'Northern Europe')!.regionalPowerPlants![region] || + []) { + if (!dealt.includes(regional.number)) { + expect(numbers(G.powerPlantsDeck), seed).to.include(regional.number); + added++; + } + } + } + } + expect(added, 'some regional number was not dealt').to.be.greaterThan(0); + }); + + it('applies the Northern Europe regional plants once the regions are drafted', () => { + for (const deck of decks) { + const label = `ne-draft-${deck}`; + let G = setup( + 4, + { map: 'Northern Europe', variant: 'recharged', powerPlantDeck: deck, chooseRegions: true }, + label + ); + expect(G.phase).to.equal(Phase.RegionSelection); + G = playAll(G, (state) => state.phase != Phase.RegionSelection); + expect(G.phase, label).to.equal(Phase.Auction); + checkRegionalPlants(G, label); + } + }); + + it('puts one plug card on top of the Québec deck, then the two smallest ecological plants', () => { + for (const variant of variants) { + for (const deck of decks) { + for (const numPlayers of [2, 3, 4, 5, 6]) { + const seed = `quebec-${variant}-${deck}-${numPlayers}`; + const G = setup(numPlayers, { map: 'Quebec', variant, powerPlantDeck: deck }, seed); + const ecological = (pp: PowerPlant) => isEcological(pp, G.options.fusionEcological); + const dealt = dealtFor('Quebec', deck, seed); + const market = [...G.actualMarket, ...G.futureMarket]; + const [top, ...beneath] = G.powerPlantsDeck; + if (variant == 'original') { + expect(numbers(market), seed).to.deep.equal(numbers(dealt.slice(0, 8))); + const rest = dealt.slice(8); + const expected = rest.find((pp) => pp.number == 13) ?? rest.find((pp) => isPlugPlant(pp, deck)); + expect(top.number, seed).to.equal(expected!.number); + } else { + expect( + market.every((pp) => isPlugPlant(pp, deck)), + seed + ).to.be.true; + expect(isPlugPlant(top, deck), seed).to.be.true; + } + const winds = sorted(dealt.filter((pp) => ecological(pp) && !market.includes(pp) && pp != top)) + .filter((pp) => !numbers(market).includes(pp.number) && pp.number != top.number) + .slice(0, 2); + expect(numbers(beneath.slice(0, 2)), seed).to.deep.equal(numbers(winds)); + // Ecological plants are never removed. + expect(numbers(visible(G)), seed).to.include.members(numbers(dealt.filter(ecological))); + } + } + } + }); + + it('opens Original Russia with the six smallest plants, 13 on top and the next two in the top five', () => { + for (const deck of decks) { + for (const numPlayers of [2, 3, 4, 5, 6]) { + const seed = `russia-${deck}-${numPlayers}`; + const G = setup(numPlayers, { map: 'Russia', variant: 'original', powerPlantDeck: deck }, seed); + const removed = removedPlants('Russia', deck, numPlayers, 'original'); + const dealt = dealtFor('Russia', deck, seed).filter( + (pp) => !removed.includes(pp.number) && pp.number != 99 + ); + expect(numbers([...G.actualMarket, ...G.futureMarket]), seed).to.deep.equal(numbers(dealt.slice(0, 6))); + const has13 = dealt.some((pp) => pp.number == 13); + if (has13) expect(G.powerPlantsDeck[0].number, seed).to.equal(13); + const window = numbers(G.powerPlantsDeck.slice(has13 ? 1 : 0, has13 ? 6 : 5)); + const next = numbers(dealt.slice(6).filter((pp) => pp.number != 13)).slice(0, 2); + expect(window, seed).to.include.members(next); + } + } + }); + + for (const [map, variant, deck, chooseRegions] of [ + ['Northern Europe', 'recharged', 'shuffled', false], + ['Northern Europe', 'original', 'shuffledUnique', true], + ['Quebec', 'original', 'shuffled', false], + ['Quebec', 'recharged', 'shuffledUnique', false], + ['Russia', 'original', 'shuffled', false], + ] as [MapName, Variant, PowerPlantDeck, boolean][]) { + const label = `${map} ${variant} with ${deck}${chooseRegions ? ' and drafted regions' : ''}`; + it(`plays a whole bot game on ${label}, rebuilds its deck and replays it`, () => { + let G = setup(4, { map, variant, powerPlantDeck: deck, chooseRegions }, `bots-${label}`); + G.players.forEach((p, i) => { + p.name = `AI ${i}`; + p.isAI = true; + }); + for (let turn = 0; turn < 8000 && !ended(G) && G.currentPlayers.length > 0; turn++) { + if (turn % 40 == 0 && G.phase != Phase.RegionSelection) { + const scenario = createAnalysisScenario(G, { player: 0, seed: `analysis-${turn}` }); + expect(scenario.powerPlantsDeck.length, `turn ${turn}`).to.equal(G.cardsLeft); + } + G = moveAI(G, G.currentPlayers[0]); + } + expect(ended(G), 'game finished').to.be.true; + + let replay = setup(4, G.options, G.seed); + replay.players.forEach((p, i) => { + p.name = `AI ${i}`; + p.isAI = true; + }); + for (const item of G.log) { + if (item.type === 'move') replay = move(replay, item.move, item.player); + } + expect(replay.players.map((p) => p.money)).to.deep.equal(G.players.map((p) => p.money)); + }); + } +}); diff --git a/engine/src/early-step3.spec.ts b/engine/src/early-step3.spec.ts new file mode 100644 index 0000000..2b3089e --- /dev/null +++ b/engine/src/early-step3.spec.ts @@ -0,0 +1,58 @@ +import { expect } from 'chai'; +import 'mocha'; +import { addPowerPlant, reconstructionOptions, setup } from './engine'; +import { GameOptions, GameState, Phase } from './gamestate'; + +// The Step 3 card drawn while the game is still in Step 1: Step 2's setup runs first, +// then Step 3's, back to back. +function drawStep3Early(options: GameOptions, phase: Phase): GameState { + const G = setup(4, options, 'early-step-3'); + const step3 = G.powerPlantsDeck.find((p) => p.number == 99)!; + G.powerPlantsDeck = [step3, ...G.powerPlantsDeck.filter((p) => p.number != 99)]; + G.phase = phase; + // A draw always refills a gap: here the end of the round sends the largest plant under the deck. + G.futureMarket.pop(); + addPowerPlant(G); + return G; +} + +const market = (G: GameState) => [...G.actualMarket, ...G.futureMarket].map((p) => p.number); +const events = (G: GameState) => G.log.filter((item) => item.type == 'event').map((item) => (item as any).event); + +describe('Step 3 card drawn before Step 2', () => { + it('begins Step 2 first on Spain & Portugal, returning the held-back plants', () => { + const G = drawStep3Early({ map: 'Spain & Portugal', variant: 'recharged' }, Phase.Bureaucracy); + const log = events(G); + const step2 = log.findIndex((e) => e.startsWith('Starting Step 2 (the Step 3 card came first)')); + const step3 = log.findIndex((e) => e.startsWith('Step 3 will begin next phase')); + expect(step2, log.join('\n')).to.be.greaterThan(-1); + expect(step3).to.be.greaterThan(step2); + // Step 2's replacement draw takes 18 from the top; 22 and 27 are shuffled in. + expect(market(G)).to.include(18); + const deck = G.powerPlantsDeck.map((p) => p.number); + expect(deck).to.include.members([22, 27]); + }); + + it('waits for the end of the auction when drawn during it', () => { + const G = drawStep3Early({ map: 'Spain & Portugal', variant: 'recharged' }, Phase.Auction); + expect(G.step).to.equal(1); + expect(G.futureMarket.map((p) => p.number)).to.include(99); + }); + + it('begins Step 2 first on a standard map', () => { + const G = drawStep3Early({ map: 'USA', variant: 'recharged' }, Phase.Bureaucracy); + expect(events(G).some((e) => e.startsWith('Starting Step 2 (the Step 3 card came first)'))).to.be.true; + }); + + it('keeps the old sequence for games created before the rule', () => { + const options = reconstructionOptions({ map: 'Spain & Portugal', variant: 'recharged' }); + expect(options.step2BeforeStep3).to.equal(false); + const G = drawStep3Early(options, Phase.Bureaucracy); + expect(events(G).some((e) => e.startsWith('Starting Step 2'))).to.be.false; + expect(market(G)).to.not.include(18); + }); + + it('stores the rule on new games', () => { + expect(setup(4, { map: 'USA', variant: 'recharged' }, 's').options.step2BeforeStep3).to.equal(true); + }); +}); diff --git a/engine/src/engine.ts b/engine/src/engine.ts index b411511..d392589 100644 --- a/engine/src/engine.ts +++ b/engine/src/engine.ts @@ -19,7 +19,7 @@ import { replacePoweringLog, restorePowering, } from './choice-revisions'; -import { originalTopPlants, removedPlants, SPAIN_STEP_2_PLANTS } from './deckChanges'; +import { originalTopPlants, removedPlants, spainStep2Plants, SPAIN_STEP_2_PLANTS } from './deckChanges'; import { countHeldPowerPlants, GameOptions, @@ -35,6 +35,7 @@ import { ResourceType, resupplyUraniumMine, sellUraniumMine, + SingleDeck, } from './gamestate'; import { LogItem } from './log'; import { GameMap, maps, mapsRecharged } from './maps'; @@ -47,7 +48,6 @@ import { gameDeck, isEcological, isPlugPlant, - lastPlugPlant, phaseOutPlants, plantCatalogue, plantLabel, @@ -88,8 +88,15 @@ export function defaultSetupDeck( let actualMarket: PowerPlant[]; let futureMarket: PowerPlant[]; const removed = removedPlants(mapName, deck, numPlayers, variant); - const catalogue = dealtCatalogue(mapName, deck, rng, sampleShuffled).filter((p) => !removed.includes(p.number)); + const dealt = dealtCatalogue(mapName, deck, rng, sampleShuffled); + const catalogue = dealt.filter((p) => !removed.includes(p.number)); let powerPlantsDeck: PowerPlant[] = cloneDeep(catalogue); + // Spain & Portugal with the shuffled decks: which held-back copies were dealt. + const held = spainStep2Plants(deck); + const heldPowerPlants = + mapName == 'Spain & Portugal' && (deck == 'shuffled' || deck == 'shuffledUnique') + ? cloneDeep(dealt.filter((p) => held.includes(p.number))) + : undefined; if (variant == 'original') { // The eight smallest plants open the market; the map's opening plants (13 in @@ -151,7 +158,7 @@ export function defaultSetupDeck( powerPlantsDeck.splice(powerPlantsDeck.length - step3FromBottom, 0, step3); } - return { actualMarket, futureMarket, powerPlantsDeck }; + return { actualMarket, futureMarket, powerPlantsDeck, ...(heldPowerPlants ? { heldPowerPlants } : {}) }; } export function setup( @@ -171,6 +178,7 @@ export function setup( powerPlantDeck, rechargedStartingResources = true, stallEnds = true, + step2BeforeStep3 = true, shuffledSample = true, fusionEcological = FUSION_IS_ECOLOGICAL, legacyEcological = false, @@ -207,7 +215,7 @@ export function setup( ? chosenMap.startingResources.recharged : chosenMap.startingResources.original; if (startingResources) chosenMap.startingResources = startingResources; - const decks = availableDecks(chosenMap.name); + const decks = availableDecks(); // A random deck is one of the three single decks. Dedicated rng so the pick // doesn't shift the rest of the setup's draws. const singleDecks: PowerPlantDeck[] = ['standard', 'deck1', 'deck2']; @@ -228,6 +236,7 @@ export function setup( let actualMarket: PowerPlant[]; let futureMarket: PowerPlant[]; let powerPlantsDeck: PowerPlant[]; + let heldPowerPlants: PowerPlant[] | undefined; if (forceDeck) { powerPlantsDeck = forceDeck; @@ -235,7 +244,7 @@ export function setup( futureMarket = powerPlantsDeck.splice(0, 4); } else { if (chosenMap.setupDeck) { - ({ actualMarket, futureMarket, powerPlantsDeck } = chosenMap.setupDeck( + ({ actualMarket, futureMarket, powerPlantsDeck, heldPowerPlants } = chosenMap.setupDeck( numPlayers, variant, rng, @@ -493,6 +502,7 @@ export function setup( // Australia: the separate uranium-mine market starts full (6 prices $2–$7, // two tokens each). Undefined on every other map. uraniumMineMarket: (forceMap || finalMap).name == 'Australia' ? [2, 2, 2, 2, 2, 2] : undefined, + ...(heldPowerPlants ? { heldPowerPlants } : {}), coalPrices, oilPrices, garbagePrices, @@ -534,6 +544,7 @@ export function setup( : {}), ...(variantStartingResources && rechargedStartingResources ? { rechargedStartingResources: true } : {}), ...(stallEnds ? { stallEnds: true } : {}), + ...(step2BeforeStep3 ? { step2BeforeStep3: true } : {}), ...(sampleShuffled ? { shuffledSample: true } : {}), ...(ecologicalRules ? { fusionEcological } : {}), ...(wienFreeGarbage ? { wienFreeGarbage: true } : {}), @@ -655,6 +666,9 @@ function filterMapToRegions(map: GameMap, playRegions: Set): GameMap { // matching plant numbers. Mutates the passed arrays in place. // The map's numbers win over the deck's: a regional card the deck has no plant for // (Deck 1 has no 18) is shuffled into the draw pile, below its top card. +// The shuffled decks: the regional card takes the place of one dealt copy of its +// number and the other copies leave the game; a regional card whose number wasn't +// dealt is shuffled in the same way. function applyRegionalPowerPlants( map: GameMap, playRegions: Set, @@ -669,10 +683,31 @@ function applyRegionalPowerPlants( } const catalogue = plantCatalogue(map.name, deck); const rng = seedrandom(seed + '-regional'); + const shuffledDeck = deck == 'shuffled' || deck == 'shuffledUnique'; + const actualSize = actualMarket.length; + const marketSize = actualSize + futureMarket.length; for (const region of playRegions) { const replacements = map.regionalPowerPlants[region]; if (replacements) { for (const newPlant of replacements) { + if (shuffledDeck) { + const sameNumber = (p: PowerPlant) => Math.floor(p.number) === newPlant.number; + const holders = [actualMarket, futureMarket, powerPlantsDeck]; + const keeper = holders.find((arr) => arr.some(sameNumber)); + if (keeper) { + const regional = { ...newPlant }; + keeper[keeper.findIndex(sameNumber)] = regional; + for (const arr of holders) { + for (let i = arr.length - 1; i >= 0; i--) { + if (sameNumber(arr[i]) && arr[i] !== regional) arr.splice(i, 1); + } + } + } else { + const index = 1 + Math.floor(rng() * (powerPlantsDeck.length - 1)); + powerPlantsDeck.splice(index, 0, { ...newPlant }); + } + continue; + } const swapIn = (arr: PowerPlant[]) => { const idx = arr.findIndex((p) => p.number === newPlant.number); if (idx !== -1) arr[idx] = { ...newPlant }; @@ -688,6 +723,14 @@ function applyRegionalPowerPlants( } } } + if (shuffledDeck) { + // A removed copy may have left the market: refill it from the top of the deck. + const market = [...actualMarket, ...futureMarket]; + while (market.length < marketSize && powerPlantsDeck.length > 1) market.push(powerPlantsDeck.shift()!); + market.sort((a, b) => a.number - b.number); + actualMarket.splice(0, actualMarket.length, ...market.slice(0, actualSize)); + futureMarket.splice(0, futureMarket.length, ...market.slice(actualSize)); + } } // Completes the chooseRegions draft: filters the map to the picked regions, applies @@ -709,6 +752,9 @@ function finalizeRegions(G: GameState) { ); // knownPowerPlantDeck mirrors actualMarket+futureMarket and must reflect any swap. G.knownPowerPlantDeck = G.actualMarket.concat(G.futureMarket); + // Regional cards can add plants to the deck, or (shuffled decks) take copies out. + G.cardsLeft = G.powerPlantsDeck.length; + G.nextCardWeak = G.options.variant === 'recharged' && G.cardsLeft > 0 && G.powerPlantsDeck[0].number <= 15; // UK & Ireland 2p caps the end-game target at the number of cities actually in // play, which is only known once the regions are chosen. @@ -1185,35 +1231,7 @@ export function move( G.map.name != 'Middle East' && G.map.name != 'Manhattan' ) { - const powerPlant = G.actualMarket.shift()!; - startStep( - G, - 2, - `Starting Step 2, Power Plant ${plantLabel(powerPlant?.number)} discarded.` - ); - - // Spain & Portugal: put the held-back plants on top (18, 22, 27 in the standard deck) - if (G.map.name == 'Spain & Portugal') { - const deck = gameDeck(G.options); - const held = SPAIN_STEP_2_PLANTS[deck]; - if (!G.powerPlantsDeck.find((p) => p.number == held[0])) { - G.powerPlantsDeck.unshift( - ...held.map((n) => getPowerPlant(n, G.map.name, deck)) - ); - } - } - - if (G.map.name == 'Europe') { - // Europe: do NOT draw a replacement from the deck. - // The future market shrinks from 5 to 4; reorganize - // the remaining 8 plants so actual stays at 4. - const market = [...G.actualMarket, ...G.futureMarket]; - market.sort((a, b) => a.number - b.number); - G.actualMarket = market.slice(0, 4); - G.futureMarket = market.slice(4); - } else { - addPowerPlant(G); - } + beginStep2(G, 'Starting Step 2'); } } @@ -2322,8 +2340,12 @@ export function reconstructState(gameState: GameState, to?: number, _forcePublic seedrandom('public-replay'), G.options.useNewRechargedSetup ?? true, gameDeck(G.options), - G.map.name + G.map.name, + 0, + gameDeck(G.options) == 'shuffled' && G.options.shuffledSample === true ).powerPlantsDeck; + // The placeholder setup's own filtering may have used up the discount. + G.plantDiscountActive = G.options.variant == 'recharged'; removePlantsForMiddleEastStep1(G); G.players[G.currentPlayers[0]].availableMoves = availableMoves(G, G.players[G.currentPlayers[0]]); } @@ -2462,6 +2484,11 @@ export function addPowerPlant(G: GameState): void { let skipAdd = false; if (powerPlant.number == 99) { + // Drawn before Step 2 has begun: Step 2's setup comes first, then Step 3's. + // In the auction it waits for the end of the phase, with Step 3's. + if (G.phase != Phase.Auction && step2BeforeStep3(G)) { + beginStep2(G, 'Starting Step 2 (the Step 3 card came first)'); + } if (G.powerPlantDeckAfterStep3) { G.powerPlantsDeck = G.powerPlantDeckAfterStep3; } else if (G.map.name == 'China') { @@ -2719,7 +2746,7 @@ function removePlantsForMiddleEastStep1(G: GameState) { removePowerPlant(G, plantToRemove); // Plug plants leave the game (06, 11 and 14 in the standard deck); others go under. - if (plantToRemove.number <= lastPlugPlant(gameDeck(G.options))) { + if (isPlugPlant(plantToRemove, gameDeck(G.options))) { G.log.push({ type: 'event', event: `Removing Power Plant ${plantLabel(plantToRemove.number)} from game.`, @@ -2758,6 +2785,49 @@ function removePlantsForMiddleEastStep1(G: GameState) { } } +// Maps with their own rule for an early Step 3 card: Middle East's second pass, +// China's ordered deck, and Manhattan, which has no Step 3. +const OWN_EARLY_STEP_3_MAPS = ['Middle East', 'China', 'Manhattan']; + +// The rulebooks: when the Step 3 card is drawn before Step 2 has begun, carry out +// everything that begins Step 2, then prepare Step 3, back to back. Games created +// before this rule was followed keep their old sequence (see reconstructionOptions). +function step2BeforeStep3(G: GameState): boolean { + return !!G.options.step2BeforeStep3 && G.step == 1 && !OWN_EARLY_STEP_3_MAPS.includes(G.map.name); +} + +// Step 2's setup: the smallest plant leaves the market and a new one is drawn (Spain & +// Portugal first puts its held-back plants on top). Also run, back to back with Step +// 3's, when the Step 3 card is drawn before Step 2 has begun. +function beginStep2(G: GameState, event: string) { + const powerPlant = G.actualMarket.shift()!; + startStep(G, 2, `${event}, Power Plant ${plantLabel(powerPlant?.number)} discarded.`); + + // Spain & Portugal: put the held-back plants on top (18, 22, 27 in the standard deck) + if (G.map.name == 'Spain & Portugal' && G.heldPowerPlants) { + // The shuffled decks: the held-back copies that were dealt, smallest on top. + G.powerPlantsDeck.unshift(...cloneDeep(G.heldPowerPlants)); + } else if (G.map.name == 'Spain & Portugal') { + const deck = gameDeck(G.options) as SingleDeck; + const held = SPAIN_STEP_2_PLANTS[deck]; + if (!G.powerPlantsDeck.find((p) => p.number == held[0])) { + G.powerPlantsDeck.unshift(...held.map((n) => getPowerPlant(n, G.map.name, deck))); + } + } + + if (G.map.name == 'Europe') { + // Europe: do NOT draw a replacement from the deck. + // The future market shrinks from 5 to 4; reorganize + // the remaining 8 plants so actual stays at 4. + const market = [...G.actualMarket, ...G.futureMarket]; + market.sort((a, b) => a.number - b.number); + G.actualMarket = market.slice(0, 4); + G.futureMarket = market.slice(4); + } else { + addPowerPlant(G); + } +} + function startStep(G: GameState, step: 2 | 3, event = `Starting Step ${step}.`) { if (G.step === step) return; G.step = step; @@ -2970,6 +3040,7 @@ export function reconstructionOptions(options: GameOptions, log: LogItem[] = []) ...options, rechargedStartingResources: options.rechargedStartingResources ?? false, stallEnds: options.stallEnds ?? false, + step2BeforeStep3: options.step2BeforeStep3 ?? false, shuffledSample: options.shuffledSample ?? false, legacyEcological: options.fusionEcological === undefined, ...(wienFreeGarbage ? { wienFreeGarbage: true } : {}), @@ -3146,6 +3217,11 @@ function toResourcesPhase(G: GameState) { if (G.map.name == 'Middle East' && G.step == 1) { enterStepTwoMiddleEast(G); } else { + if (step2BeforeStep3(G)) { + // Step 2's setup, then Step 3's, which shuffles the draw pile again. + beginStep2(G, 'Starting Step 2 (the Step 3 card came first)'); + G.powerPlantsDeck = shuffle(G.powerPlantsDeck, G.seed); + } const powerPlantDiscarded = G.actualMarket.shift(); G.futureMarket.pop(); startStep(G, 3, `Starting Step 3, Power Plant ${plantLabel(powerPlantDiscarded?.number)} discarded.`); diff --git a/engine/src/gamestate.ts b/engine/src/gamestate.ts index c448dfe..4486c94 100644 --- a/engine/src/gamestate.ts +++ b/engine/src/gamestate.ts @@ -78,6 +78,9 @@ export interface GameOptions { // game deals a standard-sized deck at random from all three decks. Older shuffled // games have none and play with every plant of all three decks. shuffledSample?: boolean; + // A Step 3 card drawn in Step 1 first begins Step 2 (with its setup), as the + // rulebooks say. Stored on new games; older games replay without it. + step2BeforeStep3?: boolean; // Whether fusion plants count as ecological (see FUSION_IS_ECOLOGICAL). Stored by // setup on the maps in ECOLOGICAL_RULE_MAPS; older games have none and play as // wind-only, except that their Québec deck setup protected fusion too. @@ -292,6 +295,9 @@ export interface GameState { knownPowerPlantDeck: PowerPlant[]; knownPowerPlantDeckStep3: PowerPlant[]; powerPlantDeckAfterStep3: PowerPlant[] | undefined; + // Spain & Portugal with the shuffled decks: the held-back copies that were dealt, + // set aside in the open until Step 2 puts them on top of the deck. + heldPowerPlants?: PowerPlant[]; // Manhattan market lifecycle (see applyManhattanMarketLifecycle in engine.ts). // The "separate pile" of plants set aside from the future market each round — // recyclable (reshuffled into a new deck at the first depletion), NOT boxed. diff --git a/engine/src/maps.ts b/engine/src/maps.ts index e4a0931..5f2e408 100644 --- a/engine/src/maps.ts +++ b/engine/src/maps.ts @@ -133,6 +133,8 @@ export interface GameMap { actualMarket: PowerPlant[]; futureMarket: PowerPlant[]; powerPlantsDeck: PowerPlant[]; + // Spain & Portugal with the shuffled decks: the held-back copies dealt. + heldPowerPlants?: PowerPlant[]; }; // Manhattan: with fewer players some building spaces are blocked at setup — // transitable (you still pay the flat-5 to route through them) but never @@ -146,12 +148,6 @@ export interface GameMap { // cost (there is no sea edge) and pay 10+position*5 + this surcharge. crossIslandSurcharge?: number; mapSpecificRules?: string; - // How this map's power-plant deck and opening market differ from the standard - // build. The rules dialog always shows the standard build for the variant in - // play, then this underneath as "On this map"; so write the DIFFERENCE, not a - // whole procedure, and omit it entirely when the map builds its deck normally. - // A map whose two variants diverge gives one string per variant. - deckBuild?: string | { recharged?: string; original?: string }; // Cities where a player's first house (or second network) must be placed. // Used by Japan: only the 6 designated starting cities are valid first builds, // and a second disconnected network can only begin in one of these cities. diff --git a/engine/src/maps/australia.ts b/engine/src/maps/australia.ts index 06f85ac..29f66ab 100644 --- a/engine/src/maps/australia.ts +++ b/engine/src/maps/australia.ts @@ -203,8 +203,15 @@ export const map: GameMap = { // Everything else follows the standard recharged/original deck setup. Note #17 is // a socket card (>15), so unlike South Africa (which removes weak plant 07 and // shrinks its starter pool to 12), Australia's plug pool stays 13. - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard') { - return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'Australia'); + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { + return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'Australia', 0, sampleShuffled); }, mapSpecificRules: 'Uranium mines: the five uranium power plants (11, 23, 28, 34, 39) are ' + @@ -233,8 +240,4 @@ export const map: GameMap = { 'Metropolises: Melbourne and Sydney each consist of two cities (1 and 2) ' + 'connected by a 0-cost edge. ' + 'Regions need not be adjacent: any combination of regions may be in play.\n', - deckBuild: - 'power plant 17 is removed from the game; the five uranium ' + - 'mines (11, 23, 28, 34, 39) stay in the deck. Otherwise standard setup ' + - 'for both variants.', }; diff --git a/engine/src/maps/brazil.ts b/engine/src/maps/brazil.ts index 9c49703..81170aa 100644 --- a/engine/src/maps/brazil.ts +++ b/engine/src/maps/brazil.ts @@ -4,7 +4,7 @@ import { originalTopPlants, rechargedMarketPlants } from '../deckChanges'; import { PowerPlant, PowerPlantDeck, PowerPlantType } from '../gamestate'; import { shuffle } from '../utils'; import { GameMap } from './../maps'; -import { lastPlugPlant, plantCatalogue } from './../powerPlants'; +import { dealtCatalogue, isPlugPlant } from './../powerPlants'; export enum Regions { Red = 'red', @@ -233,15 +233,22 @@ export const map: GameMap = { ], // Recharged rulebook: coal 1–8, oil 3–8, biogas 6–8, uranium 14–16. startingResources: { original: [24, 18, 6, 2], recharged: [24, 18, 9, 2] }, - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard') { - const catalogue = plantCatalogue('Brazil', deck); + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { + const catalogue = dealtCatalogue('Brazil', deck, rng, sampleShuffled); let powerPlantsDeck = cloneDeep(catalogue); let actualMarket: PowerPlant[]; let futureMarket: PowerPlant[]; // The biogas (garbage) plants beyond the plug cards sit out the player-count removal. const garbagePlants = powerPlantsDeck.filter( - (pp) => pp.type == PowerPlantType.Garbage && pp.number > lastPlugPlant(deck) + (pp) => pp.type == PowerPlantType.Garbage && !isPlugPlant(pp, deck) ); if (variant == 'original') { @@ -255,7 +262,7 @@ export const map: GameMap = { const step3 = powerPlantsDeck.pop()!; powerPlantsDeck = shuffle( - powerPlantsDeck.filter((pp) => pp.type != PowerPlantType.Garbage), + powerPlantsDeck.filter((pp) => !garbagePlants.includes(pp)), rng() + '' ); if (numPlayers == 2 || numPlayers == 3) { @@ -277,9 +284,10 @@ export const map: GameMap = { const marketPlants = rechargedMarketPlants('Brazil', deck); const biogasPlants = powerPlantsDeck.filter((pp) => marketPlants.includes(pp.number)); powerPlantsDeck = powerPlantsDeck.filter((pp) => !marketPlants.includes(pp.number)); - const plugCount = powerPlantsDeck.filter((pp) => pp.number <= lastPlugPlant(deck)).length; + const plugPlants = powerPlantsDeck.filter((pp) => isPlugPlant(pp, deck)); + powerPlantsDeck = powerPlantsDeck.filter((pp) => !isPlugPlant(pp, deck)); - let initialPowerPlants = shuffle(powerPlantsDeck.splice(0, plugCount), rng() + ''); + let initialPowerPlants = shuffle(plugPlants, rng() + ''); let initialPlantMarket = initialPowerPlants.splice(0, 8 - biogasPlants.length); initialPlantMarket.push(...biogasPlants); initialPlantMarket = initialPlantMarket.sort((a, b) => a.number - b.number); @@ -290,7 +298,7 @@ export const map: GameMap = { const step3 = powerPlantsDeck.pop()!; powerPlantsDeck = shuffle( - powerPlantsDeck.filter((pp) => pp.type != PowerPlantType.Garbage), + powerPlantsDeck.filter((pp) => !garbagePlants.includes(pp)), rng() + '' ); if (numPlayers == 2) { @@ -317,15 +325,4 @@ export const map: GameMap = { return { actualMarket, futureMarket, powerPlantsDeck }; }, mapSpecificRules: 'Play with all garbage power plants.\n', - deckBuild: { - recharged: - 'power plants 6 and 14 always start in the ' + - 'market; the other six market plants are drawn from the remaining low ' + - 'plants. Garbage plants above 14 are set aside during the player-count ' + - 'removal and shuffled back in, so no garbage plant ever leaves the game.', - original: - 'both 13 and 14 are set aside; after the ' + - 'player-count removal (garbage plants excluded and shuffled back in), ' + - '13 goes on top of the deck with 14 directly below it.', - }, }; diff --git a/engine/src/maps/bremen.ts b/engine/src/maps/bremen.ts index bead0e6..e45a6aa 100644 --- a/engine/src/maps/bremen.ts +++ b/engine/src/maps/bremen.ts @@ -5,7 +5,7 @@ import { originalTopPlants, removedPlants } from '../deckChanges'; import { PowerPlant, PowerPlantDeck } from '../gamestate'; import { shuffle } from '../utils'; import { GameMap } from './../maps'; -import { lastPlugPlant, plantCatalogue } from './../powerPlants'; +import { dealtCatalogue, isPlugPlant } from './../powerPlants'; export enum Regions { Blue = 'blue', @@ -225,9 +225,18 @@ export const map: GameMap = { // market is then drawn from the remaining "weak" pool (≤15) per the recharged // convention — 8 open the market, one goes on top of the deck and the leftovers // are shuffled in — and NO further player-count deck reduction is applied. - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, powerPlantDeck: PowerPlantDeck = 'standard') { + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + powerPlantDeck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { const removed = new Set(removedPlants('Bremen', powerPlantDeck, numPlayers, variant)); - const catalogue = plantCatalogue('Bremen', powerPlantDeck).filter((pp) => !removed.has(pp.number)); + const catalogue = dealtCatalogue('Bremen', powerPlantDeck, rng, sampleShuffled).filter( + (pp) => !removed.has(pp.number) + ); const deck = cloneDeep(catalogue); // The Step 3 card is the last entry of the master list and is never removed. const step3 = deck.pop()!; @@ -251,12 +260,11 @@ export const map: GameMap = { } // Recharged: the opening 8 plants come from the weak (plug) pool. - const lastPlug = lastPlugPlant(powerPlantDeck); const weak = shuffle( - deck.filter((pp) => pp.number <= lastPlug), + deck.filter((pp) => isPlugPlant(pp, powerPlantDeck)), rng() + '' ); - let rest = deck.filter((pp) => pp.number > lastPlug); + let rest = deck.filter((pp) => !isPlugPlant(pp, powerPlantDeck)); const initialMarket = weak.splice(0, 8).sort((a, b) => a.number - b.number); actualMarket = initialMarket.slice(0, 4); futureMarket = initialMarket.slice(4); @@ -280,18 +288,4 @@ export const map: GameMap = { 'players.\n' + 'Step 2 begins once a player has 5 connected districts (4 for 6 players); the ' + 'game ends when a player connects 13 districts (12 for 5 players, 11 for 6).\n', - deckBuild: { - recharged: - 'power plants 11, 17, 23, 28, 34, 36, 38, 39 and 46 ' + - 'are removed before setup — the six uranium plants plus the three plants ' + - 'that power 7 cities. With 2 to 4 players, plants 31 and 50 are removed as ' + - 'well. No further power plants are removed for the number of players. The ' + - 'opening market of eight is then drawn from the low plants (numbered 15 or ' + - 'less); of the low plants left over, one is placed on top of the draw deck ' + - 'and the rest are shuffled into it, with the Step 3 card on the bottom.', - original: - 'same removals; the market is the fixed 3-6 / 7-10 ' + - '(none of these are removed on Bremen), plant 13 is placed on top of the ' + - 'deck and the Step 3 card on the bottom.', - }, }; diff --git a/engine/src/maps/centraleurope.ts b/engine/src/maps/centraleurope.ts index ae45d19..a684740 100644 --- a/engine/src/maps/centraleurope.ts +++ b/engine/src/maps/centraleurope.ts @@ -236,4 +236,8 @@ export const map: GameMap = { [2, 3, 2], ], ], + mapSpecificRules: + 'Nuclear plants may only be purchased by players with at least one city in Czechia, Slovakia or Hungary. ' + + 'Players with cities only in Poland or Austria may not bid on or buy nuclear plants. ' + + 'A player with a city in Wien pays $1 less for each garbage, but never less than $1.\n', }; diff --git a/engine/src/maps/china.ts b/engine/src/maps/china.ts index 015950d..1211d3c 100644 --- a/engine/src/maps/china.ts +++ b/engine/src/maps/china.ts @@ -1,7 +1,7 @@ import { cloneDeep } from 'lodash'; import { removedPlants } from '../deckChanges'; import { PowerPlant, PowerPlantDeck, PowerPlantType } from '../gamestate'; -import { plantCatalogue } from '../powerPlants'; +import { dealtCatalogue } from '../powerPlants'; import { shuffle } from '../utils'; import { GameMap } from './../maps'; @@ -224,7 +224,14 @@ export const map: GameMap = { ], ], startingResources: [12, 12, 6, 0], - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard') { + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { /* Instructions for power plant setup: Depending on the number of players, remove the following power plants from the game and place them in the box: with 2 and 3 players: 3, 4, 9, 11, 16, 18, 20, 24, 30, 33, 46. @@ -236,19 +243,20 @@ export const map: GameMap = { already placed on the supply plants 5 – 30: sort in ascending order with 30 on the bottom and 5 on the top and place face-down on the supply */ - // The other decks remove their own plants (see removedPlants) but sort the same way. - const allPlants = cloneDeep(plantCatalogue('China', deck)); + // The other decks remove their own plants (see removedPlants) but sort the same way, + // by printed number. + const allPlants = cloneDeep(dealtCatalogue('China', deck, rng, sampleShuffled)); const plantsToRemove = removedPlants('China', deck, numPlayers, variant); const filteredPlants = allPlants.filter((p) => !plantsToRemove.includes(p.number)); - const lowPlants = filteredPlants.filter((p) => p.number <= 30); + const lowPlants = filteredPlants.filter((p) => Math.floor(p.number) <= 30); const step3Card = filteredPlants.filter((p) => p.type == PowerPlantType.Step3); const middlePlants = shuffle( - filteredPlants.filter((p) => p.number >= 31 && p.number <= 35).concat(step3Card), + filteredPlants.filter((p) => Math.floor(p.number) >= 31 && Math.floor(p.number) <= 35).concat(step3Card), rng() + '' ); const highPlants = shuffle( - filteredPlants.filter((p) => p.number >= 36 && p.number <= 50), + filteredPlants.filter((p) => Math.floor(p.number) >= 36 && Math.floor(p.number) <= 50), rng() + '' ); @@ -260,12 +268,4 @@ export const map: GameMap = { }, mapSpecificRules: 'There are several changes to when new plants are drawn. In particular, during steps 1 and 2, plants are only drawn from the deck during the bureaucracy phase.\n', - deckBuild: - 'the same plants are removed every game: with 2-3 players ' + - '3, 4, 9, 11, 16, 18, 20, 24, 30, 33, 46; with 4 players 3, 4, 11, 18, ' + - '24, 33, 46; with 5-6 players 3, 4, 33. The deck is ordered, not ' + - 'shuffled: plants 5-30 in ascending order on top, then plants 31-35 ' + - 'shuffled together with the Step 3 card, then plants 36-50 shuffled on ' + - 'the bottom. The starting market has one plant per player and the ' + - 'future market starts empty.', }; diff --git a/engine/src/maps/europe.ts b/engine/src/maps/europe.ts index e84d330..9c449b0 100644 --- a/engine/src/maps/europe.ts +++ b/engine/src/maps/europe.ts @@ -432,6 +432,4 @@ export const map: GameMap = { }, mapSpecificRules: 'When Step 2 begins, remove the lowest-numbered plant from the current market from the game once and do not replace it; the future market then has 4 plants instead of 5.\n', - deckBuild: - 'Europe uses the New Power Plants Set 2 deck (cards with a plug on the back). The power plant market starts as 4 current + 5 future power plants (9 total), all drawn from the plug plants; the top card of the draw deck is never a plug plant.', }; diff --git a/engine/src/maps/france.ts b/engine/src/maps/france.ts index 8b8e8aa..f7e0490 100644 --- a/engine/src/maps/france.ts +++ b/engine/src/maps/france.ts @@ -5,7 +5,7 @@ import { defaultSetupDeck } from '../engine'; import { PowerPlantDeck } from '../gamestate'; import { shuffle } from '../utils'; import { GameMap } from './../maps'; -import { lastPlugPlant, plantCatalogue } from './../powerPlants'; +import { dealtCatalogue, isPlugPlant } from './../powerPlants'; export enum Regions { Brown = 'brown', @@ -237,23 +237,34 @@ export const map: GameMap = { ], // Recharged rulebook: coal 1–8, oil 3–8, garbage 6–8, uranium 5–16. startingResources: { original: [24, 18, 6, 8], recharged: [24, 18, 9, 8] }, - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard') { + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { // Original: an ecological plant leaves the game and the nuclear plant goes on // top (13 and 11 in the standard deck), as deckChanges.ts lists per deck. if (variant == 'original') { - return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'France'); + return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'France', 0, sampleShuffled); } // Recharged: the ecological plant leaves the game and the nuclear plant (11 in // the standard deck) always opens the market, with seven more plug cards. const removed = removedPlants('France', deck, numPlayers, variant); - let powerPlantsDeck = cloneDeep(plantCatalogue('France', deck)).filter((p) => !removed.includes(p.number)); + let powerPlantsDeck = cloneDeep(dealtCatalogue('France', deck, rng, sampleShuffled)).filter( + (p) => !removed.includes(p.number) + ); + // The shuffled decks force every dealt copy of their decks' plants into the market. const marketPlants = rechargedMarketPlants('France', deck); const powerPlant11 = powerPlantsDeck.filter((p) => marketPlants.includes(p.number)); powerPlantsDeck = powerPlantsDeck.filter((p) => !marketPlants.includes(p.number)); - const plugCount = powerPlantsDeck.filter((p) => p.number <= lastPlugPlant(deck)).length; + const plugPlants = powerPlantsDeck.filter((p) => isPlugPlant(p, deck)); + powerPlantsDeck = powerPlantsDeck.filter((p) => !isPlugPlant(p, deck)); - let initialPowerPlants = shuffle(powerPlantsDeck.splice(0, plugCount), rng() + ''); + let initialPowerPlants = shuffle(plugPlants, rng() + ''); let initialPlantMarket = initialPowerPlants.splice(0, 8 - powerPlant11.length); initialPlantMarket.push(...powerPlant11); initialPlantMarket = initialPlantMarket.sort((a, b) => a.number - b.number); @@ -280,13 +291,4 @@ export const map: GameMap = { return { actualMarket, futureMarket, powerPlantsDeck }; }, - deckBuild: { - recharged: - 'power plant 13 is removed from the game and ' + - 'power plant 11 always starts in the market. Removal by player count: ' + - '2 players remove 6 higher plants, 3 players remove 1 low and 6 higher, ' + - '4 players remove 3 higher.', - original: - 'power plant 13 is removed from the game; power ' + 'plant 11 is placed on top of the deck in its place.', - }, }; diff --git a/engine/src/maps/indian.ts b/engine/src/maps/indian.ts index 8cafbdd..8e9c71e 100644 --- a/engine/src/maps/indian.ts +++ b/engine/src/maps/indian.ts @@ -228,12 +228,16 @@ export const map: GameMap = { garbagePrices: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6], uraniumPrices: [1, 2, 3, 4, 5, 6, 7, 8], - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard') { - return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'India'); + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { + return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'India', 0, sampleShuffled); }, mapSpecificRules: 'The power grid will suffer a power outage if the number of cities built in one round is more than twice the number of players — 9 or more cities in a 4-player game. Every player is then penalized $3 for each city they own, though income for the round never falls below $0.\nPlayers take turns buying one resource at a time. The resource market is limited by step: only resources costing $3 or less may be bought in step 1, $5 or less in step 2, and the whole market is open from step 3.\nGarbage plants are less efficient. Their cost is one higher, but their storage capacity is not changed.\nPlayers must power as many cities as possible in each round.', - deckBuild: - 'power plant 11 is removed from the game; otherwise standard setup for ' + - 'both variants (original: plant 13 on top of the deck).', }; diff --git a/engine/src/maps/manhattan.ts b/engine/src/maps/manhattan.ts index b4cf993..49bed74 100644 --- a/engine/src/maps/manhattan.ts +++ b/engine/src/maps/manhattan.ts @@ -5,7 +5,7 @@ import { removedPlants } from '../deckChanges'; import { PowerPlantDeck } from '../gamestate'; import { shuffle } from '../utils'; import { City, Connection, GameMap } from './../maps'; -import { lastPlugPlant, plantCatalogue } from './../powerPlants'; +import { dealtCatalogue, isPlugPlant } from './../powerPlants'; // Manhattan (RIO 686 Bremen/Manhattan expansion) is unlike every other board: // • A SINGLE region. Every building space holds exactly ONE house, at its printed @@ -338,20 +338,28 @@ export const map: GameMap = { // ≤ 15): box 4, keep 9 on top of the stack; the opening 8-card market is drawn // from them. "Socket" cards (> 15) form the rest of the stack. The deck-depletion // market lifecycle (separate-pile reshuffle → all-buyable → shrink) is Session 2. - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, powerPlantDeck: PowerPlantDeck = 'standard') { + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + powerPlantDeck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { const boxed = new Set(removedPlants('Manhattan', powerPlantDeck, numPlayers, variant)); - const deck = cloneDeep(plantCatalogue('Manhattan', powerPlantDeck)).filter((pp) => !boxed.has(pp.number)); + const deck = cloneDeep(dealtCatalogue('Manhattan', powerPlantDeck, rng, sampleShuffled)).filter( + (pp) => !boxed.has(pp.number) + ); // Last entry of the master list is the Step 3 card → boxed (dropped), so the // game can never advance out of Step 1. deck.pop(); - const lastPlug = lastPlugPlant(powerPlantDeck); const plug = shuffle( - deck.filter((pp) => pp.number <= lastPlug), + deck.filter((pp) => isPlugPlant(pp, powerPlantDeck)), rng() + '' ); const socket = shuffle( - deck.filter((pp) => pp.number > lastPlug), + deck.filter((pp) => !isPlugPlant(pp, powerPlantDeck)), rng() + '' ); plug.splice(0, plug.length - 9); // plug cards to the box, leaving nine (four in the standard deck) @@ -413,10 +421,4 @@ export const map: GameMap = { 'plant is removed from the game. If the market is completely empty, no ' + 'more power plants can be bought. The game ends when a player has ' + 'connected 18 spaces (17 for 3–4 players, 15 for 5, 14 for 6).\n', - deckBuild: - 'at the start of the game, 4 random plug plants are ' + - 'removed. Of the other 9, 8 are in the starting market and 1 is on ' + - 'the top of the deck. The rest of the deck is random with no plug ' + - 'plants. The Step 3 card is removed from the game. For 2-3 players: ' + - 'also place power plants 20, 22, and 37 into the game box.', }; diff --git a/engine/src/maps/northerneurope.ts b/engine/src/maps/northerneurope.ts index 93e6148..b777da2 100644 --- a/engine/src/maps/northerneurope.ts +++ b/engine/src/maps/northerneurope.ts @@ -188,10 +188,6 @@ export const map: GameMap = { 'Nuclear plants may only be purchased by players with at least one city in Sweden, Finland, or the Baltic States. ' + 'Players with cities only in Norway or Denmark may not bid on or buy nuclear plants. ' + 'Resources start at: coal 3 Elektro, oil 3 Elektro, garbage 5 Elektro, uranium 7 Elektro.\n', - deckBuild: - 'standard setup; the regions in play swap in regional ' + - 'versions of certain power plants (same numbers, different fuel or ' + - 'output).', connections: [ { nodes: [Cities.Bood, Cities.Tromso], cost: 17 }, { nodes: [Cities.Tromso, Cities.Oulu], cost: 25 }, diff --git a/engine/src/maps/quebec.ts b/engine/src/maps/quebec.ts index 3a99390..32b88ea 100644 --- a/engine/src/maps/quebec.ts +++ b/engine/src/maps/quebec.ts @@ -1,7 +1,7 @@ import { cloneDeep } from 'lodash'; import { originalTopPlants, QUEBEC_RECHARGED_TOP_PLANTS, rechargedMarketPlants } from '../deckChanges'; import { PowerPlant, PowerPlantDeck } from '../gamestate'; -import { isEcological, lastPlugPlant, plantCatalogue } from '../powerPlants'; +import { dealtCatalogue, isEcological, isPlugPlant, lastPlugPlant, plantCatalogue } from '../powerPlants'; import { shuffle } from '../utils'; import { GameMap } from './../maps'; @@ -59,6 +59,66 @@ export enum Cities { Hull = 'Hull', } +// The shuffled decks, where the three decks' Québec rules disagree, follow the rule's +// purpose: one plug card on top of the deck, then the two smallest ecological plants +// dealt that aren't in the market. The Recharged market is drawn from the plug cards; +// the Original market is the eight smallest plants, and its plug card the standard +// deck's top plant (13) if dealt, otherwise the smallest plug card left. Ecological +// plants are never removed. +function shuffledSetup( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck, + ecological: (pp: PowerPlant) => boolean, + sampleShuffled: boolean +) { + const plants = cloneDeep(dealtCatalogue('Quebec', deck, rng, sampleShuffled)); + const step3 = plants.pop()!; + const isPlug = (pp: PowerPlant) => isPlugPlant(pp, deck); + let market: PowerPlant[]; + let top: PowerPlant | undefined; + let rest: PowerPlant[]; + if (variant == 'original') { + market = plants.slice(0, 8); + rest = plants.slice(8); + const topNumber = originalTopPlants('Quebec', deck)[0]; + top = rest.find((pp) => pp.number == topNumber) ?? rest.find(isPlug); + } else { + const plugs = shuffle(plants.filter(isPlug), rng() + ''); + market = plugs.splice(0, 8).sort((a, b) => a.number - b.number); + top = plugs.shift(); + rest = plugs.concat(plants.filter((pp) => !isPlug(pp))); + } + rest = rest.filter((pp) => pp != top); + const winds = rest + .filter(ecological) + .sort((a, b) => a.number - b.number) + .slice(0, 2); + rest = rest.filter((pp) => !winds.includes(pp)); + + // Player-count removal, skipping ecological plants. + const removable = (pool: PowerPlant[], count: number) => { + const removed = shuffle(pool, rng() + '') + .filter((pp) => !ecological(pp)) + .slice(0, count); + return pool.filter((pp) => !removed.includes(pp)); + }; + if (variant == 'original') { + rest = removable(rest, [8, 8, 4][numPlayers - 2] ?? 0); + } else { + rest = removable(rest.filter(isPlug), [1, 2, 1][numPlayers - 2] ?? 0).concat( + removable( + rest.filter((pp) => !isPlug(pp)), + [5, 6, 3][numPlayers - 2] ?? 0 + ) + ); + } + + const powerPlantsDeck = (top ? [top] : []).concat(winds, shuffle(rest, rng() + ''), step3); + return { actualMarket: market.slice(0, 4), futureMarket: market.slice(4), powerPlantsDeck }; +} + export const map: GameMap = { name: 'Quebec', cities: [ @@ -211,9 +271,13 @@ export const map: GameMap = { variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard', - fusionEcological?: boolean + fusionEcological?: boolean, + sampleShuffled = false ) { const ecological = (pp: PowerPlant) => isEcological(pp, fusionEcological); + if (deck == 'shuffled' || deck == 'shuffledUnique') { + return shuffledSetup(numPlayers, variant, rng, deck, ecological, sampleShuffled); + } let powerPlantsDeck = cloneDeep(plantCatalogue('Quebec', deck)); let actualMarket: PowerPlant[]; let futureMarket: PowerPlant[]; @@ -332,15 +396,4 @@ export const map: GameMap = { return { actualMarket, futureMarket, powerPlantsDeck }; }, mapSpecificRules: 'Ecological power plants will never be put on the bottom of the deck.\n', - deckBuild: { - recharged: - 'the starting market is drawn from the low ' + - 'plants (including 13); one more low plant goes on top of the deck, ' + - 'with 18 and 22 placed directly beneath it. Ecological plants are ' + - 'never removed during setup.', - original: - 'power plants 13, 18, 22 are set aside and ' + - 'placed on top of the deck (13 topmost); ecological plants are ' + - 'excluded from the player-count removal.', - }, }; diff --git a/engine/src/maps/russia.ts b/engine/src/maps/russia.ts index 977ddfc..d0ecdc2 100644 --- a/engine/src/maps/russia.ts +++ b/engine/src/maps/russia.ts @@ -1,7 +1,7 @@ import { cloneDeep } from 'lodash'; import { originalTopPlants, removedPlants, RUSSIA_ORIGINAL_NEXT_PLANTS } from '../deckChanges'; import { PowerPlant, PowerPlantDeck } from '../gamestate'; -import { lastPlugPlant, plantCatalogue } from '../powerPlants'; +import { dealtCatalogue, isPlugPlant } from '../powerPlants'; import { shuffle } from '../utils'; import { GameMap } from './../maps'; @@ -230,10 +230,19 @@ export const map: GameMap = { ], ], startingResources: [18, 24, 0, 7], - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard') { + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { // Two plants leave the game: 06 and 14 in the standard deck. const removed = removedPlants('Russia', deck, numPlayers, variant); - let powerPlantsDeck = cloneDeep(plantCatalogue('Russia', deck)).filter((p) => !removed.includes(p.number)); + let powerPlantsDeck = cloneDeep(dealtCatalogue('Russia', deck, rng, sampleShuffled)).filter( + (p) => !removed.includes(p.number) + ); let actualMarket: PowerPlant[] = []; let futureMarket: PowerPlant[] = []; const step3 = powerPlantsDeck.pop()!; @@ -244,9 +253,14 @@ export const map: GameMap = { futureMarket = powerPlantsDeck.slice(3, 6); // Set aside the top plant (13) and the next two plants after the market (10, 11). + // The shuffled decks: the standard deck's 13 if it was dealt, and the 7th and + // 8th smallest plants dealt. const rest = powerPlantsDeck.slice(6); - const plant13 = rest.find((p) => p.number == originalTopPlants('Russia', deck)[0])!; - const [plant10, plant11] = RUSSIA_ORIGINAL_NEXT_PLANTS[deck].map((n) => rest.find((p) => p.number == n)!); + const plant13 = rest.find((p) => p.number == originalTopPlants('Russia', deck)[0]); + const [plant10, plant11] = + deck == 'shuffled' || deck == 'shuffledUnique' + ? rest.filter((p) => p != plant13).slice(0, 2) + : RUSSIA_ORIGINAL_NEXT_PLANTS[deck].map((n) => rest.find((p) => p.number == n)!); // Shuffle the rest of the plants. const mainPlants = rest.filter((p) => p != plant13 && p != plant10 && p != plant11); @@ -264,12 +278,12 @@ export const map: GameMap = { topPlants = shuffle(topPlants, rng() + ''); // Place plant 13 on top of deck, shuffled cards with 10 and 11 next, then the rest of the deck, then the step 3 card. - powerPlantsDeck = [plant13].concat(topPlants, mainPlantsShuffled.slice(3), step3); + powerPlantsDeck = (plant13 ? [plant13] : []).concat(topPlants, mainPlantsShuffled.slice(3), step3); } else { - const initialPlants = powerPlantsDeck.filter((p) => p.number <= lastPlugPlant(deck)); + const initialPlants = powerPlantsDeck.filter((p) => isPlugPlant(p, deck)); const initialPlantsShuffled = shuffle(initialPlants, rng() + ''); - const mainPlants = powerPlantsDeck.filter((p) => p.number > lastPlugPlant(deck)); + const mainPlants = powerPlantsDeck.filter((p) => !isPlugPlant(p, deck)); let mainPlantsShuffled = shuffle(mainPlants, rng() + ''); if (numPlayers == 2) { @@ -291,17 +305,4 @@ export const map: GameMap = { return { actualMarket, futureMarket, powerPlantsDeck }; }, mapSpecificRules: 'The power plant market is restricted, and the rules for removing old ' + 'plants are changed.\n', - deckBuild: { - recharged: - 'plants 6 and 14 are removed from the game. The ' + - 'market has 6 plants (3 current, 3 future) drawn at random from the ' + - 'low plants; the six undrawn low plants sit shuffled on top of the ' + - 'deck. Removal by player count (higher plants only): 2 players remove ' + - '6, 3 players remove 8, 4 players remove 4.', - original: - 'plants 6 and 14 are removed from the game; the ' + - 'market is 3, 4, 5 / 7, 8, 9. Plant 13 goes on top of the deck, then ' + - 'five shuffled cards (plants 10, 11 and the top three of the deck), ' + - 'then the rest, with the Step 3 card on the bottom.', - }, }; diff --git a/engine/src/maps/southafrica.ts b/engine/src/maps/southafrica.ts index 741945b..097200d 100644 --- a/engine/src/maps/southafrica.ts +++ b/engine/src/maps/southafrica.ts @@ -212,8 +212,15 @@ export const map: GameMap = { // recharged/original deck setup. With 07 gone the "starter pool" is one // plant shorter (12 instead of 13 for recharged; future market shifts to // 8/9/10/11 instead of 7/8/9/10 for original). - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard') { - return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'South Africa'); + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { + return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'South Africa', 0, sampleShuffled); }, mapSpecificRules: 'Coal storage: there is a separate storage space below the resource market, ' + @@ -228,8 +235,4 @@ export const map: GameMap = { 'available from the start of the game. The 30 Elektro is the complete cost ' + '— no house-base cost is added on top. Only a single player can build on ' + 'each cross-border space (cap of 1 instead of the standard 3).\n', - deckBuild: - 'power plant 07 is removed from the game; otherwise ' + - 'standard setup for both variants (in the original variant the future ' + - 'market becomes 8, 9, 10, 11).', }; diff --git a/engine/src/maps/spainportugal.ts b/engine/src/maps/spainportugal.ts index bc35cbd..546c557 100644 --- a/engine/src/maps/spainportugal.ts +++ b/engine/src/maps/spainportugal.ts @@ -238,12 +238,15 @@ export const map: GameMap = { ], ], startingResources: [24, 18, 9, 8], - setupDeck(numPlayers: number, variant: string, rng: seedrandom.prng, deck: PowerPlantDeck = 'standard') { - return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'Spain & Portugal'); + setupDeck( + numPlayers: number, + variant: string, + rng: seedrandom.prng, + deck: PowerPlantDeck = 'standard', + _fusionEcological?: boolean, + sampleShuffled = false + ) { + return defaultSetupDeck(numPlayers, variant, rng, true, deck, 'Spain & Portugal', 0, sampleShuffled); }, mapSpecificRules: 'You cannot buy a nuclear power plant if you only have cities in Portugal.\n', - deckBuild: - 'power plants 18, 22 and 27 are set aside at setup; when ' + - 'Step 2 begins they are placed on top of the deck (18 topmost, then ' + - '22, then 27).', }; diff --git a/engine/src/maps/ukireland.ts b/engine/src/maps/ukireland.ts index 70d0f89..42dc7d5 100644 --- a/engine/src/maps/ukireland.ts +++ b/engine/src/maps/ukireland.ts @@ -260,7 +260,4 @@ export const map: GameMap = { 'Early Step 3: the Step 3 card is placed 3rd from last in the deck (two ' + 'plants below it). Step 2 begins when a player connects their 7th city ' + '(6th for 6 players).\n', - deckBuild: - 'standard setup for both variants, except the Step 3 card ' + - 'is placed third from the bottom of the deck (two plants below it).', }; diff --git a/engine/src/powerPlants.ts b/engine/src/powerPlants.ts index ecbf753..86e898c 100644 --- a/engine/src/powerPlants.ts +++ b/engine/src/powerPlants.ts @@ -156,8 +156,8 @@ function usesAlternateDeck(mapName: string, alternate: boolean | undefined): boo // India's version of a deck: one plant leaves the game, and garbage plants cost one // more garbage to run but have no additional storage. -function indiaCatalogue(deck: PowerPlant[], removed: number): PowerPlant[] { - const plants = cloneDeep(deck).filter((pp) => pp.number != removed); +function indiaCatalogue(deck: PowerPlant[], removed: number[]): PowerPlant[] { + const plants = cloneDeep(deck).filter((pp) => !removed.includes(pp.number)); plants.forEach((pp) => { if (pp.type == PowerPlantType.Garbage) { pp.storage = 2 * pp.cost; @@ -167,11 +167,11 @@ function indiaCatalogue(deck: PowerPlant[], removed: number): PowerPlant[] { return plants; } -const indiaPowerPlants = indiaCatalogue(powerPlants, 11); +const indiaPowerPlants = indiaCatalogue(powerPlants, [11]); const indiaCatalogues: Record = { standard: indiaPowerPlants, - deck1: indiaCatalogue(deck1PowerPlants, 8), - deck2: indiaCatalogue(alternatePowerPlants, 13), + deck1: indiaCatalogue(deck1PowerPlants, [8]), + deck2: indiaCatalogue(alternatePowerPlants, [13]), }; // The shuffled decks hold copies of the same number. The standard deck's copy keeps @@ -190,6 +190,9 @@ const shuffledPowerPlants: PowerPlant[] = [ .sort((a, b) => a.number - b.number) .concat(powerPlants.filter((pp) => pp.type == PowerPlantType.Step3)); +// India's shuffled decks: the removed plants leave once dealt (see removedPlants). +const indiaShuffledPowerPlants = indiaCatalogue(shuffledPowerPlants, []); + // Which deck a plant's copy came from in the shuffled decks: 0 standard, 1, or 2. function plantCopy(number: number): number { return Math.round((number - Math.floor(number)) * 10); @@ -209,28 +212,12 @@ function labelledPlant(printed: string, copy: string | undefined): number { return Number(printed) + (copy ? Number(copy) / 10 : 0); } -// Maps whose setup or rules name plant numbers: the shuffled decks, which have no -// official changes for them, aren't offered there. -const NUMBERED_SETUP_MAPS: string[] = [ - 'Australia', - 'Brazil', - 'Bremen', - 'China', - 'France', - 'India', - 'Manhattan', - 'Middle East', - 'Northern Europe', - 'Quebec', - 'Russia', - 'South Africa', - 'Spain & Portugal', -]; - -// The decks a map can be played with: every map takes every single deck. -function availableDecks(mapName: string): PowerPlantDeck[] { - const singleDecks: PowerPlantDeck[] = ['standard', 'deck1', 'deck2']; - return NUMBERED_SETUP_MAPS.includes(mapName) ? singleDecks : [...singleDecks, 'shuffled', 'shuffledUnique']; +// The decks a map can be played with: every map takes every deck. The shuffled decks +// follow every deck's map rules at once (see deckChanges.ts); where those clash, the +// map's setup states the rule by its purpose (Northern Europe's regional cards in +// applyRegionalPowerPlants, Québec's top of the deck, Original Russia's opening). +function availableDecks(): PowerPlantDeck[] { + return ['standard', 'deck1', 'deck2', 'shuffled', 'shuffledUnique']; } // The deck a game plays with. Games from before powerPlantDeck may carry the @@ -245,7 +232,7 @@ function gameDeck(options: GameOptions): PowerPlantDeck { // a subset of it (see dealtCatalogue), so lookups by number still work. function plantCatalogue(mapName: string, deck: PowerPlantDeck = 'standard'): PowerPlant[] { if (deck == 'shuffled' || deck == 'shuffledUnique') { - return shuffledPowerPlants; + return mapName == 'India' ? indiaShuffledPowerPlants : shuffledPowerPlants; } if (mapName == 'India') { return indiaCatalogues[deck]; @@ -345,7 +332,6 @@ export { isPlugPlant, PHASE_OUT_PLANT, phaseOutPlants, - NUMBERED_SETUP_MAPS, FUSION_IS_ECOLOGICAL, ECOLOGICAL_RULE_MAPS, isEcological, diff --git a/viewer/src/components/Game.vue b/viewer/src/components/Game.vue index 7b40639..b5a256e 100644 --- a/viewer/src/components/Game.vue +++ b/viewer/src/components/Game.vue @@ -856,6 +856,10 @@ slots filled), even if no player reached {{ G.citiesToStep2 }} +
  • + When it starts, the smallest power plant leaves the market and a new one is + drawn +
  • Two players per city
  • Resource Resupply: {{ G.resourceResupply[1] }} @@ -875,6 +879,14 @@ Step 3:
    • Starts after the "Step 3" card is drawn from the deck
    • +
    • + When it starts, the Step 3 card and the smallest power plant leave the market, + and the draw pile is shuffled +
    • +
    • + If the Step 3 card is drawn before Step 2 has begun, Step 2 begins first, with + its own setup, and Step 3 follows straight after +
    • Three players per city
    • Resource Resupply: {{ G.resourceResupply[2] }} @@ -898,21 +910,30 @@ The winner is the player that can power the most cities. Money and number of cities built are tiebreakers. -