506 lines
27 KiB
JavaScript
506 lines
27 KiB
JavaScript
#!/usr/bin/env node
|
||
// verifyMonopoly.js — headless checks for Monopoly ("The Boardwalk Hotel"):
|
||
// • rules fixes: no salary for leaving GO, GO salary / doubleGo, Get Out of
|
||
// Jail Free cards leave the deck while held, the debt queue for every kind
|
||
// of payment, settle / bankruptcy legality, bankruptcy to a player (buildings
|
||
// at half, mortgages carried + 10% interest) and to the bank (auctions),
|
||
// building / even-selling / housing-shortage rules, mortgage interest on
|
||
// trades, auctions (everyone gets a say), jail's third try, Free Parking
|
||
// jackpot, short game (deal, 3-house hotels, end at first bankruptcy),
|
||
// round limit
|
||
// • threat map odds
|
||
// • AI soak across classic / short / house-rule mixes and skills 1–5:
|
||
// games finish, money moves only through fx events, supplies, even
|
||
// building, card conservation, nobody ever below $0
|
||
// • save round-trip (JSON) of a mid-game state
|
||
// • layout: HUD furniture inside the screen and never overlapping
|
||
// Usage: node tools/verifyMonopoly.js [--quick]
|
||
|
||
import * as L from '../src/games/monopoly/MonopolyLogic.js';
|
||
import * as AI from '../src/games/monopoly/MonopolyAI.js';
|
||
import * as D from '../src/games/monopoly/MonopolyData.js';
|
||
|
||
const QUICK = process.argv.includes('--quick');
|
||
let pass = 0, fail = 0;
|
||
function ok(label, cond, detail = '') {
|
||
if (cond) pass++;
|
||
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
|
||
}
|
||
const section = (n) => console.log(`\n${n}`);
|
||
const { SPACES, PURCHASABLE, GROUPS } = D;
|
||
|
||
const fresh = (n = 2, rules = {}, seed = 7) => L.createInitialState({ playerCount: n, names: ['A', 'B', 'C', 'D'].slice(0, n), seed, rules });
|
||
const own = (s, seat, ...idxs) => { for (const i of idxs) s.board[i].owner = seat; return s; };
|
||
const withCash = (s, ...cash) => { cash.forEach((c, i) => { s.players[i].cash = c; }); return s; };
|
||
const money = (s) => s.players.reduce((a, p) => a + p.cash, 0) + s.freeParkingPot;
|
||
|
||
section('Movement & GO');
|
||
{
|
||
let s = fresh();
|
||
s = L.rollDice(s, 0, 2, 3);
|
||
ok('leaving GO pays nothing', s.players[0].cash === 1500, `cash ${s.players[0].cash}`);
|
||
ok('pawn moves the dice total', s.players[0].position === 5);
|
||
|
||
s = fresh(); s.players[0].position = 38;
|
||
s = L.rollDice(s, 0, 1, 3);
|
||
ok('passing GO pays $200', s.players[0].cash === 1700 && s.players[0].position === 2);
|
||
|
||
s = fresh(2, { doubleGo: true }); s.players[0].position = 36;
|
||
s = L.rollDice(s, 0, 1, 3);
|
||
ok('doubleGo: landing exactly on GO pays $400', s.players[0].cash === 1900, `cash ${s.players[0].cash}`);
|
||
s = fresh(2, { doubleGo: true }); s.players[0].position = 38;
|
||
s = L.rollDice(s, 0, 1, 3);
|
||
ok('doubleGo: passing GO still pays $200', s.players[0].cash === 1700);
|
||
|
||
s = fresh();
|
||
s = L.rollDice(s, 0, 1, 1); s.phase = 'preroll';
|
||
s = L.rollDice(s, 0, 2, 2); s.phase = 'preroll';
|
||
s = L.rollDice(s, 0, 3, 3);
|
||
ok('three doubles → Jail', s.players[0].jailed && s.players[0].position === 10 && s.phase === 'endturn');
|
||
s = L.endTurn(s);
|
||
ok('…and the turn passes', s.current === 1);
|
||
|
||
s = fresh(); s = L.rollDice(s, 0, 2, 2);
|
||
if (s.phase === 'buy') s = L.buyProperty(s, 0);
|
||
s = L.endTurn(s);
|
||
ok('doubles: same player rolls again', s.current === 0 && s.phase === 'preroll');
|
||
}
|
||
|
||
section('Get Out of Jail Free');
|
||
{
|
||
let s = fresh();
|
||
// Put the Chance GOOJF card on top and land on Chance (7).
|
||
s.chanceDeck = [D.GOOJF_CARD.chance, ...s.chanceDeck.filter(i => i !== D.GOOJF_CARD.chance)];
|
||
s.players[0].position = 4;
|
||
s = L.rollDice(s, 0, 1, 2);
|
||
ok('drew the card', s.phase === 'card' && s.pendingCard.effect.effect === 'goojf');
|
||
s = L.applyCardEffect(s, 0);
|
||
ok('the player keeps it', s.players[0].getOutOfJailFree === 1 && s.players[0].jailCards.length === 1);
|
||
ok('it is no longer in the Chance deck', !s.chanceDeck.includes(D.GOOJF_CARD.chance) && s.chanceDeck.length === 15);
|
||
// Cycle the whole deck: it must never come up.
|
||
let seen = 0;
|
||
for (let k = 0; k < 40; k++) {
|
||
s.phase = 'preroll'; s.players[0].position = 4; s.players[0].jailed = false; s.current = 0;
|
||
s = L.rollDice(s, 0, 1, 2);
|
||
if (s.pendingCard?.effect.effect === 'goojf') seen++;
|
||
s.pendingCard = null; s.pendingBuy = null; s.pendingRent = null; s.debts = []; s.phase = 'endturn';
|
||
}
|
||
ok('a held card is never drawn again', seen === 0);
|
||
s = fresh(); s.players[0].jailed = true; s.players[0].position = 10;
|
||
s.players[0].jailCards = [{ deck: 'chance', idx: D.GOOJF_CARD.chance }]; s.players[0].getOutOfJailFree = 1;
|
||
s.chanceDeck = s.chanceDeck.filter(i => i !== D.GOOJF_CARD.chance);
|
||
s = L.useJailCard(s, 0);
|
||
ok('using it frees the player', !s.players[0].jailed && s.phase === 'preroll');
|
||
ok('…and returns it to the bottom of the deck', s.chanceDeck[s.chanceDeck.length - 1] === D.GOOJF_CARD.chance && s.chanceDeck.length === 16);
|
||
}
|
||
|
||
section('Jail');
|
||
{
|
||
let s = fresh(); s.players[0].jailed = true; s.players[0].position = 10;
|
||
s = L.rollDice(s, 0, 1, 2);
|
||
ok('a miss stays in Jail', s.players[0].jailed && s.players[0].jailTurns === 1 && s.phase === 'endturn');
|
||
s.phase = 'preroll'; s = L.rollDice(s, 0, 1, 2); s.phase = 'preroll';
|
||
const before = s.players[0].cash;
|
||
s = L.rollDice(s, 0, 1, 2);
|
||
ok('third miss: pay $50 and move', !s.players[0].jailed && s.players[0].cash === before - 50 && s.players[0].position === 13, `pos ${s.players[0].position} cash ${s.players[0].cash}`);
|
||
|
||
s = fresh(); s.players[0].jailed = true; s.players[0].position = 10;
|
||
s = L.rollDice(s, 0, 3, 3);
|
||
ok('doubles walk out of Jail', !s.players[0].jailed && s.players[0].position === 16);
|
||
if (s.phase === 'buy') s = L.declineProperty(s, 0);
|
||
while (s.phase === 'auction') s = L.passAuction(s, L.auctionBidder(s));
|
||
s = L.endTurn(s);
|
||
ok('…without an extra roll', s.current === 1);
|
||
|
||
s = fresh(); s.players[0].jailed = true; s.players[0].position = 10; s.players[0].jailTurns = 2; s.players[0].cash = 20;
|
||
own(s, 0, 1, 3);
|
||
s = L.rollDice(s, 0, 1, 2);
|
||
ok('broke on the third try: debt for the fine', s.phase === 'debt' && s.debts[0].amount === 50 && s.players[0].position === 10);
|
||
s = L.mortgageProperty(s, 0, 1);
|
||
s = L.settleDebt(s);
|
||
ok('after settling, the pawn moves on', s.players[0].position === 13 && s.phase !== 'debt', `pos ${s.players[0].position} ${s.phase}`);
|
||
|
||
s = fresh(2, { freeParkingJackpot: true }); s.players[0].jailed = true; s.players[0].position = 10;
|
||
s = L.payJailFine(s, 0);
|
||
ok('jackpot rule: the fine goes to the pot', s.freeParkingPot === 50 && s.players[0].cash === 1450);
|
||
}
|
||
|
||
section('Rent, debts and settling');
|
||
{
|
||
let s = fresh(); own(s, 1, 39); s.players[0].position = 35;
|
||
s = L.rollDice(s, 0, 2, 2);
|
||
ok('landing on an owned deed → rent phase', s.phase === 'rent' && s.pendingRent.amount === 50);
|
||
s = L.applyRent(s);
|
||
ok('rent paid', s.players[0].cash === 1450 && s.players[1].cash === 1550 && s.phase === 'endturn');
|
||
ok('stats track rent', s.stats.rentPaid[0] === 50 && s.stats.rentCollected[1] === 50);
|
||
|
||
s = fresh(); own(s, 1, 37, 39); s.board[39].hotel = true; s.players[0].position = 35; s.players[0].cash = 300;
|
||
own(s, 0, 1, 3, 5);
|
||
s = L.rollDice(s, 0, 2, 2); s = L.applyRent(s);
|
||
ok('short of cash → debt, cash untouched', s.phase === 'debt' && s.players[0].cash === 300 && s.debts[0].amount === 2000);
|
||
ok('debtor is the acting seat', L.actingSeat(s) === 0);
|
||
ok('cannot settle yet', !L.canSettleDebt(s));
|
||
ok('bankruptcy legal (300 + 160 of mortgages < 2000)', L.mustGoBankrupt(s));
|
||
const same = L.settleDebt(s);
|
||
ok('settle refused while short', same === s);
|
||
|
||
s = fresh(); own(s, 1, 39); s.players[0].position = 35; s.players[0].cash = 30;
|
||
own(s, 0, 1, 3);
|
||
s = L.rollDice(s, 0, 2, 2); s = L.applyRent(s);
|
||
ok('debt $50 with $30 cash and two $30 mortgages', s.phase === 'debt' && !L.mustGoBankrupt(s));
|
||
const nope = L.declareBankruptcy(s);
|
||
ok('bankruptcy refused when funds can be raised', nope === s);
|
||
s = L.mortgageProperty(s, 0, 1);
|
||
ok('mortgage raises $30', s.players[0].cash === 60);
|
||
s = L.settleDebt(s);
|
||
ok('settled: creditor paid, turn resumes', s.players[1].cash === 1550 && s.players[0].cash === 10 && s.phase === 'endturn');
|
||
}
|
||
|
||
section('Cards that charge everyone');
|
||
{
|
||
let s = fresh(3); s.players[0].cash = 60;
|
||
s.pendingCard = { cardType: 'chance', cardIdx: 14, text: '', effect: D.CHANCE_CARDS[14] }; s.phase = 'card';
|
||
s = L.applyCardEffect(s, 0);
|
||
ok('"pay each player $50" with $60: first paid, second queued', s.players[1].cash === 1550 && s.debts.length === 1 && s.debts[0].creditor === 2 && s.phase === 'debt');
|
||
|
||
s = fresh(3); s.players[1].cash = 5; s.players[2].cash = 500;
|
||
s.pendingCard = { cardType: 'community_chest', cardIdx: 6, text: '', effect: D.CC_CARDS[6] }; s.phase = 'card';
|
||
s = L.applyCardEffect(s, 0);
|
||
ok('"collect $50 from every player": short opponent gets a debt', s.players[0].cash === 1550 && s.debts.length === 1 && s.debts[0].debtor === 1);
|
||
ok('the debtor (not the current player) acts', L.actingSeat(s) === 1);
|
||
s = L.declareBankruptcy(s);
|
||
ok('broke opponent goes bankrupt to the collector', s.players[1].bankrupt && s.players[0].cash === 1555, `cash ${s.players[0].cash}`);
|
||
ok('the current player carries on', s.current === 0 && s.phase === 'endturn');
|
||
}
|
||
|
||
section('Bankruptcy');
|
||
{
|
||
// To a player: buildings sold at half, cash + deeds (mortgages kept) to the creditor, 10% interest.
|
||
let s = fresh(3);
|
||
own(s, 0, 1, 3, 5); s.board[1].houses = 2; s.board[3].houses = 2; s.houseSupply -= 4; s.board[5].mortgaged = true;
|
||
s.players[0].cash = 10;
|
||
s.debts = [{ debtor: 0, creditor: 1, amount: 5000, why: 'rent' }]; s.phase = 'debt';
|
||
const c0 = s.players[1].cash;
|
||
s = L.declareBankruptcy(s);
|
||
ok('debtor out', s.players[0].bankrupt && !s.players[0].active);
|
||
ok('houses back in the bank', s.houseSupply === 32 && s.board[1].houses === 0);
|
||
ok('creditor gets cash + half the building cost, less 10% interest', s.players[1].cash === c0 + 10 + 4 * 25 - 10, `cash ${s.players[1].cash - c0}`);
|
||
ok('deeds transferred with the mortgage kept', s.board[1].owner === 1 && s.board[5].owner === 1 && s.board[5].mortgaged && !s.board[1].mortgaged);
|
||
ok('turn passes on from the bankrupt player', s.current === 1 && s.phase === 'preroll');
|
||
|
||
// To the bank: deeds unmortgaged and auctioned in turn.
|
||
s = fresh(3); own(s, 0, 1, 3); s.board[3].mortgaged = true; s.players[0].cash = 0;
|
||
s.players[0].jailCards = [{ deck: 'community_chest', idx: D.GOOJF_CARD.community_chest }]; s.players[0].getOutOfJailFree = 1;
|
||
s.ccDeck = s.ccDeck.filter(i => i !== D.GOOJF_CARD.community_chest);
|
||
s.debts = [{ debtor: 0, creditor: 'bank', amount: 200, why: 'tax' }]; s.phase = 'debt'; s.current = 0;
|
||
s = L.declareBankruptcy(s);
|
||
ok('bankrupt to the bank → auction of the first deed', s.phase === 'auction' && s.pendingAuction.spaceIdx === 1 && s.auctionQueue.length === 1);
|
||
ok('deeds unmortgaged and ownerless', s.board[3].owner === null && !s.board[3].mortgaged);
|
||
ok('jail card back in its deck', s.ccDeck.includes(D.GOOJF_CARD.community_chest));
|
||
ok('bankrupt player not among bidders', !s.pendingAuction.bidders.includes(0));
|
||
s = L.placeBid(s, L.auctionBidder(s), 40);
|
||
while (s.phase === 'auction' && s.pendingAuction.spaceIdx === 1) s = L.passAuction(s, L.auctionBidder(s));
|
||
ok('second deed auctioned next', s.phase === 'auction' && s.pendingAuction.spaceIdx === 3);
|
||
while (s.phase === 'auction') s = L.passAuction(s, L.auctionBidder(s));
|
||
ok('then play passes on', s.phase === 'preroll' && s.current === 1 && s.board[1].owner !== null, `phase ${s.phase} cur ${s.current}`);
|
||
|
||
s = fresh(2); s.debts = [{ debtor: 0, creditor: 1, amount: 5000, why: 'rent' }]; s.phase = 'debt'; s.players[0].cash = 0;
|
||
s = L.declareBankruptcy(s);
|
||
ok('last player standing wins', s.phase === 'gameover' && s.winner === 1 && s.endReason === 'last');
|
||
}
|
||
|
||
section('Building');
|
||
{
|
||
let s = fresh(); own(s, 0, 6, 8, 9);
|
||
ok('can build with the set', L.canBuildHouse(s, 0, 6));
|
||
s.board[9].mortgaged = true;
|
||
ok('cannot build while one of the set is mortgaged', !L.canBuildHouse(s, 0, 6));
|
||
s.board[9].mortgaged = false;
|
||
s = L.buildHouse(s, 0, 6);
|
||
ok('even building: not a 2nd house on the same lot', !L.canBuildHouse(s, 0, 6) && L.canBuildHouse(s, 0, 8));
|
||
s = L.buildHouse(s, 0, 8); s = L.buildHouse(s, 0, 9); s = L.buildHouse(s, 0, 6);
|
||
ok('even selling: only from the most-built lot', L.canSellHouse(s, 0, 6) && !L.canSellHouse(s, 0, 8));
|
||
ok('cannot mortgage while the group has buildings', !L.canMortgage(s, 0, 9));
|
||
ok('cannot build without the cash', (() => { const t = JSON.parse(JSON.stringify(s)); t.players[0].cash = 10; return !L.canBuildHouse(t, 0, 8); })());
|
||
|
||
s = fresh(); own(s, 0, 37, 39); s.players[0].cash = 5000;
|
||
for (let k = 0; k < 4; k++) { s = L.buildHouse(s, 0, 37); s = L.buildHouse(s, 0, 39); }
|
||
ok('4 houses each', s.board[37].houses === 4 && s.board[39].houses === 4 && s.houseSupply === 24);
|
||
s = L.buildHotel(s, 0, 39);
|
||
ok('hotel returns 4 houses', s.board[39].hotel && s.houseSupply === 28 && s.hotelSupply === 11);
|
||
ok('cannot sell a house off the 4-house lot while the other has a hotel', !L.canSellHouse(s, 0, 37));
|
||
let c = s.players[0].cash;
|
||
s = L.sellHotel(s, 0, 39);
|
||
ok('selling the hotel breaks it back into 4 houses', s.board[39].houses === 4 && !s.board[39].hotel && s.houseSupply === 24 && s.players[0].cash === c + 100);
|
||
s = L.buildHotel(s, 0, 39);
|
||
s.houseSupply = 2; c = s.players[0].cash;
|
||
s = L.sellHotel(s, 0, 39);
|
||
ok('housing shortage: hotel sold down to bare land', s.board[39].houses === 0 && s.players[0].cash === c + 500 && s.houseSupply === 2);
|
||
|
||
s = fresh(); own(s, 0, 1, 3); s.houseSupply = 0;
|
||
ok('no houses in the bank → no building', !L.canBuildHouse(s, 0, 1));
|
||
|
||
s = fresh(2, {}); own(s, 0, 21, 23, 24);
|
||
const plan = L.planEvenBuild(s, 0, 'red', 900);
|
||
ok('even-build plan spreads houses', plan.length === 6 && new Set(plan.slice(0, 3).map(p => p.idx)).size === 3, JSON.stringify(plan));
|
||
}
|
||
|
||
section('Mortgages & trades');
|
||
{
|
||
let s = fresh(); own(s, 0, 39);
|
||
s = L.mortgageProperty(s, 0, 39);
|
||
ok('mortgage pays half', s.players[0].cash === 1700 && s.board[39].mortgaged);
|
||
s = L.unmortgageProperty(s, 0, 39);
|
||
ok('lifting costs +10%', s.players[0].cash === 1480 && !s.board[39].mortgaged);
|
||
|
||
s = fresh(); own(s, 0, 39); s.board[39].mortgaged = true;
|
||
const offer = { fromSeat: 0, toSeat: 1, giveProps: [39], getProps: [], giveCash: 0, getCash: 100 };
|
||
ok('trade valid', L.validateTrade(s, offer).ok);
|
||
const t = L.applyTrade(s, offer);
|
||
ok('receiver of a mortgaged deed pays 10% interest', t.players[1].cash === 1500 - 100 - 20 && t.board[39].owner === 1 && t.board[39].mortgaged);
|
||
s.players[1].cash = 110;
|
||
ok('trade refused if the receiver cannot cover the interest', !L.validateTrade(s, offer).ok);
|
||
|
||
s = fresh(2, { mode: 'short' }); const idx = L.ownedBy(s, 0)[0];
|
||
s = L.mortgageProperty(s, 0, idx); const c = s.players[0].cash;
|
||
s = L.unmortgageProperty(s, 0, idx);
|
||
ok('short game: no interest when lifting a mortgage', s.players[0].cash === c - SPACES[idx].mortgage);
|
||
}
|
||
|
||
section('Auctions');
|
||
{
|
||
let s = fresh(2); s.players[0].position = 1; s.pendingBuy = { spaceIdx: 1 }; s.phase = 'buy';
|
||
s = L.declineProperty(s, 0);
|
||
ok('declining starts an auction with everyone', s.phase === 'auction' && s.pendingAuction.bidders.length === 2);
|
||
s = L.passAuction(s, 0);
|
||
ok('the last bidder still gets a say', s.phase === 'auction' && L.auctionBidder(s) === 1);
|
||
s = L.placeBid(s, 1, 10);
|
||
ok('a lone bid wins', s.board[1].owner === 1 && s.players[1].cash === 1490 && s.phase === 'endturn');
|
||
|
||
s = fresh(3); s.pendingBuy = { spaceIdx: 39 }; s.phase = 'buy';
|
||
s = L.declineProperty(s, 0);
|
||
s = L.placeBid(s, 0, 100); s = L.placeBid(s, 1, 150); s = L.passAuction(s, 2);
|
||
ok('bidding goes round, skipping the high bidder', L.auctionBidder(s) === 0);
|
||
s = L.placeBid(s, 0, 200); s = L.passAuction(s, 1);
|
||
ok('auction ends when only the high bidder is left', s.board[39].owner === 0 && s.players[0].cash === 1300);
|
||
|
||
s = fresh(2, { auctions: false }); s.pendingBuy = { spaceIdx: 1 }; s.phase = 'buy';
|
||
s = L.declineProperty(s, 0);
|
||
ok('auctions off: declined deed stays with the bank', s.phase === 'endturn' && s.board[1].owner === null);
|
||
}
|
||
|
||
section('House rules & modes');
|
||
{
|
||
let s = fresh(2, { freeParkingJackpot: true }); s.players[0].position = 1;
|
||
s = L.rollDice(s, 0, 1, 2);
|
||
ok('jackpot: tax goes to the pot', s.freeParkingPot === 200 && s.players[0].cash === 1300);
|
||
s = L.endTurn(s); s.players[1].position = 17;
|
||
s = L.rollDice(s, 1, 1, 2);
|
||
ok('landing on Free Parking collects the pot', s.players[1].cash === 1700 && s.freeParkingPot === 0);
|
||
|
||
s = fresh(3, { startingCash: 2500 });
|
||
ok('starting cash option', s.players.every(p => p.cash === 2500));
|
||
|
||
s = fresh(4, { mode: 'short' }, 11);
|
||
const owned = PURCHASABLE.filter(i => s.board[i].owner !== null);
|
||
ok('short game deals 2 deeds each', owned.length === 8 && s.players.every(p => L.ownedBy(s, p.seat).length === 2));
|
||
ok('…and players paid for them', s.players.every(p => p.cash === 1500 - L.ownedBy(s, p.seat).reduce((a, i) => a + SPACES[i].price, 0)));
|
||
s = fresh(2, { mode: 'short' }); for (const i of PURCHASABLE) s.board[i].owner = null; own(s, 0, 37, 39); s.players[0].cash = 5000;
|
||
for (let k = 0; k < 3; k++) { s = L.buildHouse(s, 0, 37); s = L.buildHouse(s, 0, 39); }
|
||
ok('short game: hotel after 3 houses', L.canBuildHotel(s, 0, 39) && !L.canBuildHouse(s, 0, 39));
|
||
s = L.buildHotel(s, 0, 39);
|
||
ok('…which returns 3 houses', s.houseSupply === 32 - 6 + 3);
|
||
s = fresh(3, { mode: 'short' }); s.debts = [{ debtor: 2, creditor: 'bank', amount: 99999, why: 'tax' }]; s.phase = 'debt'; s.players[2].cash = 0;
|
||
for (const i of L.ownedBy(s, 2)) s.board[i].owner = null;
|
||
s.players[1].cash = 5000;
|
||
s = L.declareBankruptcy(s);
|
||
ok('short game ends at the first bankruptcy; richest wins', s.phase === 'gameover' && s.endReason === 'short' && s.winner === 1);
|
||
|
||
s = fresh(2, { roundLimit: 2 });
|
||
for (let k = 0; k < 4 && s.phase !== 'gameover'; k++) { s.phase = 'endturn'; s.doublesCount = 0; s = L.endTurn(s); }
|
||
ok('round limit ends the game', s.phase === 'gameover' && s.endReason === 'rounds', `${s.phase} r${s.round}`);
|
||
}
|
||
|
||
section('Threat map');
|
||
{
|
||
let s = fresh(); own(s, 1, 6, 8, 9); s.board[8].houses = 1; s.board[6].houses = 1; s.board[9].houses = 1; s.houseSupply -= 3;
|
||
const tm = L.threatMap(s, 0);
|
||
const total = tm.cells.reduce((a, c) => a + c.prob, 0);
|
||
ok('probabilities sum to 1', Math.abs(total - 1) < 1e-9, total);
|
||
ok('rent cells priced', tm.cells.find(c => c.idx === 8)?.cost === 30 && tm.cells.find(c => c.idx === 4)?.kind === 'tax');
|
||
ok('P(pay anything) counts rent and tax', Math.abs(tm.pAny - (D.DICE_P[4] + D.DICE_P[6] + D.DICE_P[8] + D.DICE_P[9])) < 1e-9, tm.pAny);
|
||
s.players[0].jailed = true; s.players[0].position = 10;
|
||
const tj = L.threatMap(s, 0);
|
||
ok('jailed: only doubles move', Math.abs(tj.cells.reduce((a, c) => a + c.prob, 0) - 6 / 36) < 1e-9);
|
||
}
|
||
|
||
// ── AI soak ───────────────────────────────────────────────────────────────────
|
||
function aiTrades(s, seat, skills) {
|
||
let done = 0;
|
||
for (const t of s.players) {
|
||
if (done >= 2) break;
|
||
if (t.seat === seat || !t.active) continue;
|
||
const offer = AI.buildAiTradeOffer(s, seat, t.seat, skills[seat], { targetSkill: skills[t.seat] });
|
||
if (!offer || !L.validateTrade(s, offer).ok) continue;
|
||
if (!AI.evaluateTrade(s, t.seat, offer, skills[t.seat]).accept) continue;
|
||
s = L.applyTrade(s, offer); done++;
|
||
}
|
||
return s;
|
||
}
|
||
|
||
function aiStep(s, skills, rng, ctx) {
|
||
const seat = L.actingSeat(s);
|
||
const skill = skills[seat];
|
||
const die = () => 1 + Math.floor(rng() * 6);
|
||
switch (s.phase) {
|
||
case 'auction': {
|
||
const bid = AI.chooseBid(s, seat, skill);
|
||
return bid !== null ? L.placeBid(s, seat, bid) : L.passAuction(s, seat);
|
||
}
|
||
case 'debt': {
|
||
const a = AI.chooseDebtAction(s, seat, skill);
|
||
if (a.action === 'settle') return L.settleDebt(s);
|
||
if (a.action === 'bankrupt') return L.declareBankruptcy(s);
|
||
if (a.action === 'mortgage') return L.mortgageProperty(s, seat, a.spaceIdx);
|
||
if (a.action === 'sellHouse') return L.sellHouse(s, seat, a.spaceIdx);
|
||
if (a.action === 'sellHotel') return L.sellHotel(s, seat, a.spaceIdx);
|
||
throw new Error('bad debt action ' + JSON.stringify(a));
|
||
}
|
||
case 'preroll': {
|
||
if (ctx.manage++ < 30) {
|
||
const m = AI.chooseManage(s, seat, skill);
|
||
if (m) {
|
||
const n = m.action === 'hotel' ? L.buildHotel(s, seat, m.spaceIdx)
|
||
: m.action === 'house' ? L.buildHouse(s, seat, m.spaceIdx) : L.unmortgageProperty(s, seat, m.spaceIdx);
|
||
if (n !== s) return n;
|
||
}
|
||
}
|
||
ctx.manage = 0;
|
||
if (s.players[seat].jailed) {
|
||
const ja = AI.chooseJailAction(s, seat, skill);
|
||
if (ja === 'card' && s.players[seat].getOutOfJailFree > 0) return L.useJailCard(s, seat);
|
||
if (ja === 'pay' && s.players[seat].cash >= 50) return L.payJailFine(s, seat);
|
||
}
|
||
return L.rollDice(s, seat, die(), die());
|
||
}
|
||
case 'buy': return AI.chooseBuy(s, seat, skill) ? L.buyProperty(s, seat) : L.declineProperty(s, seat);
|
||
case 'card': return L.applyCardEffect(s, seat, { dice: [die(), die()] });
|
||
case 'rent': return L.applyRent(s);
|
||
case 'endturn': {
|
||
if (!ctx.traded) { ctx.traded = true; if (rng() < 0.5) return aiTrades(s, seat, skills); }
|
||
ctx.traded = false;
|
||
return L.endTurn(s);
|
||
}
|
||
default: throw new Error('unknown phase ' + s.phase);
|
||
}
|
||
}
|
||
|
||
function invariants(s, prev, label, errs) {
|
||
const err = (m) => { if (errs.length < 6) errs.push(`${label}: ${m}`); };
|
||
for (const p of s.players) if (p.cash < 0) err(`${p.name} cash ${p.cash}`);
|
||
if (s.freeParkingPot < 0) err('pot negative');
|
||
let houses = 0, hotels = 0;
|
||
for (const i of PURCHASABLE) { houses += s.board[i].houses; hotels += s.board[i].hotel ? 1 : 0; }
|
||
if (houses + s.houseSupply !== 32) err(`houses ${houses}+${s.houseSupply}`);
|
||
if (hotels + s.hotelSupply !== 12) err(`hotels ${hotels}+${s.hotelSupply}`);
|
||
for (const [g, idxs] of Object.entries(GROUPS)) {
|
||
const lv = idxs.map(i => L.level(s, i));
|
||
const built = lv.some(v => v > 0);
|
||
if (built && idxs.some(i => s.board[i].mortgaged)) err(`${g} built with a mortgage`);
|
||
if (built && !L.ownsGroup(s, s.board[idxs[0]].owner, g)) err(`${g} built without the set`);
|
||
if (Math.max(...lv) - Math.min(...lv) > 1 && s.houseSupply > 4) err(`${g} uneven ${lv}`);
|
||
}
|
||
for (const i of PURCHASABLE) { const o = s.board[i].owner; if (o !== null && !s.players[o].active) err(`deed ${i} owned by bankrupt`); }
|
||
const held = { chance: 0, community_chest: 0 };
|
||
if (s.pendingCard?.effect?.effect === 'goojf') held[s.pendingCard.cardType]++;
|
||
for (const p of s.players) { for (const c of p.jailCards) held[c.deck]++; if (p.getOutOfJailFree !== p.jailCards.length) err('jail card count'); }
|
||
if (s.chanceDeck.length + held.chance !== 16) err(`chance cards ${s.chanceDeck.length}+${held.chance}`);
|
||
if (s.ccDeck.length + held.community_chest !== 16) err(`cc cards ${s.ccDeck.length}+${held.community_chest}`);
|
||
if (s.phase !== 'gameover' && !s.players[L.actingSeat(s)]?.active) err(`acting seat ${L.actingSeat(s)} inactive (${s.phase})`);
|
||
// Money moves only through fx events (so every change can be animated).
|
||
const fresh = s.fx.filter(e => e.id > prev.fxSeq);
|
||
if (s.fxSeq - prev.fxSeq > 48) return;
|
||
let flow = 0;
|
||
for (const e of fresh) if (e.type === 'pay') {
|
||
if (e.from === 'bank') flow += e.amount;
|
||
if (e.to === 'bank') flow -= e.amount;
|
||
}
|
||
if (money(s) - money(prev) !== flow) err(`money ${money(prev)}→${money(s)} but fx flow ${flow} (${prev.phase}→${s.phase})`);
|
||
}
|
||
|
||
section('AI soak');
|
||
{
|
||
const configs = [
|
||
{ n: 4, rules: {} }, { n: 3, rules: {} }, { n: 2, rules: {} },
|
||
{ n: 4, rules: { mode: 'short' } }, { n: 3, rules: { freeParkingJackpot: true, doubleGo: true } },
|
||
{ n: 4, rules: { auctions: false, startingCash: 1000 } }, { n: 3, rules: { roundLimit: 30 } },
|
||
{ n: 2, rules: { mode: 'short', startingCash: 2500 } },
|
||
];
|
||
const GAMES = QUICK ? 24 : 160;
|
||
const STEP_CAP = 60000;
|
||
const errs = [];
|
||
let finished = 0, capped = 0, totalRounds = 0, steps = 0, bankrupts = 0, debtsSeen = 0, auctions = 0, saveOk = true;
|
||
const reasons = {};
|
||
for (let g = 0; g < GAMES; g++) {
|
||
const cfg = configs[g % configs.length];
|
||
const rng = L.rngFrom(1000 + g);
|
||
const skills = Array.from({ length: cfg.n }, (_, i) => 1 + ((g + i) % 5));
|
||
let s = L.createInitialState({ playerCount: cfg.n, names: ['A', 'B', 'C', 'D'], seed: 500 + g, rules: cfg.rules });
|
||
const ctx = { manage: 0, traded: false };
|
||
let k = 0;
|
||
for (; k < STEP_CAP && s.phase !== 'gameover'; k++) {
|
||
const prev = s;
|
||
s = aiStep(s, skills, rng, ctx);
|
||
if (s.phase === 'debt' && prev.phase !== 'debt') debtsSeen++;
|
||
if (s.phase === 'auction' && prev.phase !== 'auction') auctions++;
|
||
invariants(s, prev, `game ${g} step ${k}`, errs);
|
||
if (k === 400) {
|
||
const r = JSON.parse(JSON.stringify(s));
|
||
if (JSON.stringify(r) !== JSON.stringify(s)) saveOk = false;
|
||
}
|
||
if (s.round > 1500) break;
|
||
}
|
||
steps += k;
|
||
if (s.phase === 'gameover') { finished++; reasons[s.endReason] = (reasons[s.endReason] ?? 0) + 1; totalRounds += s.round; }
|
||
else capped++;
|
||
bankrupts += s.players.filter(p => p.bankrupt).length;
|
||
if (s.phase === 'gameover') {
|
||
if (s.standings?.length !== cfg.n) errs.push(`game ${g}: standings ${s.standings}`);
|
||
if (s.winner !== s.standings[0]) errs.push(`game ${g}: winner mismatch`);
|
||
}
|
||
}
|
||
console.log(` ${GAMES} games: ${finished} finished (${Object.entries(reasons).map(([k, v]) => `${k} ${v}`).join(', ')}), ${capped} capped; avg ${Math.round(totalRounds / Math.max(1, finished))} rounds, ${steps} steps, ${bankrupts} bankruptcies, ${debtsSeen} debts, ${auctions} auctions`);
|
||
ok('soak invariants hold', errs.length === 0, '\n ' + errs.join('\n '));
|
||
ok('most games finish', finished >= GAMES * 0.9, `${finished}/${GAMES}`);
|
||
ok('debts and auctions were exercised', debtsSeen > 0 && auctions > 0);
|
||
ok('mid-game state survives a JSON save round-trip', saveOk);
|
||
}
|
||
|
||
// ── Layout ────────────────────────────────────────────────────────────────────
|
||
section('Layout');
|
||
try {
|
||
const Lay = await import('../src/games/monopoly/MonopolyLayout.js');
|
||
const F = Lay.hudFurniture();
|
||
const inScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= 1920 && r.y + r.h <= 1080;
|
||
for (const [k, r] of Object.entries(F)) ok(`${k} on screen`, inScreen(r), JSON.stringify(r));
|
||
const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
|
||
const keys = Object.keys(F);
|
||
const ov = [];
|
||
for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) if (overlap(F[keys[i]], F[keys[j]])) ov.push(`${keys[i]}×${keys[j]}`);
|
||
ok('HUD furniture never overlaps', ov.length === 0, ov.join(', '));
|
||
for (let i = 0; i < 40; i++) {
|
||
const r = Lay.spaceRect(i);
|
||
if (!(r.x >= Lay.BOARD.x - 0.5 && r.y >= Lay.BOARD.y - 0.5 && r.x + r.w <= Lay.BOARD.x + Lay.BOARD.w + 0.5 && r.y + r.h <= Lay.BOARD.y + Lay.BOARD.h + 0.5)) ok(`space ${i} inside the board`, false);
|
||
}
|
||
ok('spaces tile the board edge', (() => {
|
||
let area = 0; for (let i = 0; i < 40; i++) { const r = Lay.spaceRect(i); area += r.w * r.h; }
|
||
const B = Lay.BOARD, inner = B.w - 2 * D.CORNER_SIZE;
|
||
return Math.abs(area - (B.w * B.h - inner * inner)) < 1;
|
||
})());
|
||
} catch (e) {
|
||
ok('layout module loads', false, e.message);
|
||
}
|
||
|
||
console.log(`\n${pass} passed, ${fail} failed`);
|
||
process.exit(fail ? 1 : 0);
|