Pie in the Sky: a full constellation pays back in about seven years

Rule O7's payback half is now played through the game loop
(tests/pie-balance.test.js): the big-network save runs a full lasered
Shortcrust by a sensible policy until its books balance, in 5 to 10 years
(6.3 on seed 7; 7.4 and 6.9 on seeds 11 and 3). The static formula is gone.

Retune: pies $0.5M (+$0.25M lasers), from $1M (+$0.5M); landing rights
$12,000 per eyeball up to $100M a year, from $28,000 up to $200M; orbit
rates x1.25 (pizza 25k, flywifi 36k, boat 27.5k, marsorb 44k); PIE_SELL
0.25 -> 0.4; PIE_OFFER_RATE 1/6 -> 1/3.
This commit is contained in:
Frederic Jung 2026-11-04 10:20:56 +01:00
parent 46ba4e04d2
commit 1de0723c35
No known key found for this signature in database
9 changed files with 103 additions and 45 deletions

View file

@ -11,6 +11,8 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
## Procedure
1. Changing anything above? Run `npm test -- tests/gameplay-rules.test.js` (under a minute) before committing.
Changing orbit prices, crusts, incidents or orbit customers? Also run `npm test -- tests/pie-balance.test.js` (O7's
game-loop half, about a minute).
2. A failure names what breaks the rule and how to fix it. Fix the data or the code.
3. Only when real life really is different, add an entry to `EXCEPTIONS` in the test (keyed by rule id, sorted, with
its reason in plain words). Never delete or loosen a check to make it pass. A stale exception fails too.
@ -88,5 +90,5 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
| O3 | A cut-off pie dish (its POP on an island the backbone does not reach) carries only its own POP's traffic (backhaul, to a landing dish on the backbone) and local terminals, never transit between other cities: no POP on the backbone routes through it. Backhaul is small (the dish's antennas, the landing dish's and the crust's room) and pays the orbit's latency. | Orbit extends your network to a town no cable reaches; it does not replace building one, and laying fiber stays the real fix. |
| O4 | Through space with lasers, light travels at c in vacuum (about 1.47 times glass), up and down at the shell's height; orbit never carries traffic between cities under 3,000 km apart and only latency-routed circuits fly: IP traffic, bulk and scenic circuits stay on fiber. | Real constellations win only on long routes, and their capacity is small. |
| O5 | Launches fail only with chaos on (`rule('chaos')`), and never in the first 90 days after the unlock; heavy test flights explode by design, not by chance. Orbit incidents and geopolitical spats (`pieChaos()`) follow the same rule. | Like F1: learn the thing before it punishes you. |
| O7 | A fresh Tier 1 cannot afford a full Shortcrust from its first year's money: even a big network's yearly profit plus the largest loan a bank would offer stays below the cheapest full build (`pieFullCost('short')`). And a full crust never pays back in under 5 years, even with every Gbps the sky can sell sold at the dearest prices; on the big-network save, a full lasered Shortcrust with the customers the market offers pays back in 5 to 10. | Obscenely expensive is the joke and the goal; a constellation in year one would be a cheat code. |
| O7 | A fresh Tier 1 cannot afford a full Shortcrust from its first year's money: even a big network's yearly profit plus the largest loan a bank would offer stays below the cheapest full build (`pieFullCost('short')`). And a full lasered Shortcrust, played through the game loop on the big-network save by a sensible policy (reusable rockets, two pads, no launches past the crust's size except replacements, safe mode in storms, dishes grown with demand at well-served POPs, every orbit offer signed), pays back on its own books (`S.pie.book`: every launch, replacement, dish, licence and running cost against orbit income) in 5 to 10 years, never sooner (`tests/pie-balance.test.js`; `PIE_BALANCE_YEARS=10` prints the long run). | Obscenely expensive is the joke and the goal; a constellation in year one would be a cheat code. |

View file

@ -18,6 +18,7 @@ All notable changes to this project are documented here. The project follows
- A town with no cable can now reach your network through your satellites: a pie dish at a POP your fiber does not reach sends all of that town's traffic up to a baked crust and down at one of your dishes on the backbone, nearby or, with laser links, anywhere. The pipe is small (the dishes' antennas and the crust's room) and adds the orbit's delay, so a big town fills it quickly and laying fiber stays the real fix; it never carries traffic between your other cities. Pie Control's Traffic tab shows each backhaul, how full it is, where it lands and how many ms it adds, or why it is missing, the globe draws it, and the traceroute shows its hops through space.
- The globe in Pie Control now replays your last few launches: a good one climbs and spills its pies into orbit (and a reusable booster flies home), a failed one goes up in a fireball with debris raining down.
- A bad week in orbit now hurts without emptying the sky: a half-baked crust carries part of its traffic from 40% (all of it from 60%) instead of nothing until 60%, satellites wear out a few at a time near the end of their life instead of a whole launch month on one day, no storm or food fight takes more than a tenth of a crust, and orbit customers put up with about a month without service before they cancel.
- A full satellite constellation now pays for itself in about seven years if you run it well, instead of practically never: pies cost half as much to build, landing rights cost less (at most $100M a year a country), orbit customers pay about a quarter more, the sky sells 40% of a crust's capacity instead of 25%, and orbit customers call twice as often. Terminal customers also land on the nearest pie dish with room for all of their traffic, instead of squeezing into a nearly full one.
- Your own subsea cables now land right on the city's dot, also in Fujairah, Dubai, Karachi, Barcelona, Osaka and other cities the map shifts slightly so they do not overlap (#305).
- Starting a new network no longer leaves the last one's "New POP!" and money pop-ups frozen all over the map until a reload.

View file

@ -38,14 +38,14 @@ Pies are cohorts, never one object per satellite. `sanitize()` clamps all of it.
| --- | --- | --- |
| Found company | $250M | $5M/mo |
| Pie factory | $1B | $8M/mo, 120 pies/mo |
| Pie | $1M (+$0.5M lasers) | - |
| Pie | $0.5M (+$0.25M lasers) | - |
| Launch pad (coastal/beach city with a POP) | $400M | $2M/mo, equatorial -15% per launch |
| Falcon Punch launch | $60M, 20 pies | - |
| Reuse R&D (Falcon Punch Again) | $500M; launch $30M; booster lost $40M | - |
| Heavy R&D (Starshipping & Handling) | $3B; $100M/launch, 100 pies, first 3 test flights explode | - |
| Insurance | 8% of launch, optional | - |
| Pie dish (city with a POP) | $25M + $2M per antenna | $300k/mo |
| Landing rights | $10M-$200M per country by market size | yearly |
| Landing rights | $10M-$100M per country by market size | yearly |
| LEO-IX port | $50M | $1M/mo |
| Founder launch party | $2M per launch, automatic | - |

View file

@ -4,10 +4,10 @@
of the game. The economy and the daily tick are in 60-features/99-pie-in-the-sky.js. */
const PIE_MUL=1;
const PIE_CO=250e6,PIE_CO_MO=5e6,PIE_FAC=1e9,PIE_FAC_MO=8e6,PIE_FAC_MONTH=120,PIE_STOCK_MAX=480,
PIE_PIE=1e6,PIE_LAS=0.5e6,PIE_PAD=400e6,PIE_PAD_MO=2e6,PIE_PAD_MAX=6,PIE_EQ=0.15,
PIE_PIE=0.5e6,PIE_LAS=0.25e6,PIE_PAD=400e6,PIE_PAD_MO=2e6,PIE_PAD_MAX=6,PIE_EQ=0.15,
PIE_REUSE=500e6,PIE_HEAVY=3e9,PIE_HEAVY_TESTS=3,PIE_BOOST=40e6,PIE_BOOST_MAX=20,PIE_BOOSTERS=6,PIE_INS=0.08,
PIE_DISH=25e6,PIE_ANT=2e6,PIE_ANT_MAX=16,PIE_ANT_G=20,PIE_DISH_MO=3e5,PIE_DISH_MAX=200,
PIE_LIC_MIN=10e6,PIE_LIC_MAX=200e6,PIE_LIC_DAYS=360,PIE_LEOIX=50e6,PIE_LEOIX_MO=1e6,PIE_PARTY=2e6,
PIE_LIC_MIN=10e6,PIE_LIC_MAX=100e6,PIE_LIC_P=12000,PIE_LIC_DAYS=360,PIE_LEOIX=50e6,PIE_LEOIX_MO=1e6,PIE_PARTY=2e6,
PIE_QUIET=90,PIE_PREP=7,PIE_Q_MAX=40,PIE_COHORTS=240,PIE_POSTS=20,PIE_RAW=0.4,PIE_BAKED=0.6,PIE_SPARE=1.1,PIE_WEAR=0.3;
// In generation order. fail: chance a launch is lost (x chaos); land: chance a reused booster does not come back.
const ROCKETS={
@ -63,7 +63,7 @@ function pieCoast(c){if(!isCity(c))return false;if(PIE_COAST.has(c))return PIE_C
// Launching nearer the equator saves fuel: up to 15% off a launch, nothing above 45 degrees.
const pieEq=c=>PIE_EQ*clamp((45-Math.abs(CITY[c].lat))/35,0,1);
// Landing rights by market size: the eyeballs of every city in the country.
const pieLicPrice=cc=>Math.round(clamp(PIE_LIC_MIN+CITIES.reduce((a,c)=>a+(c.cc===cc?c.P:0),0)*28000,PIE_LIC_MIN,PIE_LIC_MAX)/1e6)*1e6;
const pieLicPrice=cc=>Math.round(clamp(PIE_LIC_MIN+CITIES.reduce((a,c)=>a+(c.cc===cc?c.P:0),0)*PIE_LIC_P,PIE_LIC_MIN,PIE_LIC_MAX)/1e6)*1e6;
// The feature is here: unlocked by becoming Tier 1 in a save of this version, or open gates (sandbox). Never in puzzles,
// the Architect or scenarios.
function pieOn(){return !!S&&!S.scn&&S.mode!=='puzzle'&&(!!S.pie||gatesOpen());}

View file

@ -34,10 +34,10 @@ const BIZ_T={
// satellite operator oversubscribes two hundredfold (two hundred homes at $100 a month share one Gbps). The prices set
// the payback of a full crust (rule O7: never under 5 years, 6 to 10 for a strong network).
// share: the most of the sky's market (pieMarket()) that kind may hold; there are only so many airlines.
pizza:{l:tr('businesses.pizza_homes_and_boats_on_orbit'),opts:[50,100,200,400],rate:20000,orbit:true,lv:1,names:['Deep Dish Rural Broadband','Crust Mile Connect','Topping Off Telecom','Extra Cheese Islands Net','Slice of Life Homesteads','Calzone Ranch Wi-Fi','Thin Crust Tundra Net','Margherita Marina Moorings','Anchovy Atoll Online','Stuffed Crust Station Hands']},
flywifi:{l:tr('businesses.flywifi_airline_wi_fi'),opts:[20,50,100,200],rate:29000,orbit:true,las:true,share:0.2,lv:1,names:['Jet Lag Wi-Fi','Wi-Fly Away','Seatback Streaming Co.','Tray Table Upright Telecom','Cabin Pressure Networks','Mile High Megabits','Overhead Bin Broadband','Turbulence Tolerant Transit']},
boat:{l:tr('businesses.cruise_ship_connectivity'),opts:[100,200,400,800],rate:22000,orbit:true,lv:1,names:['Buffet Overboard Cruises','The Love Bandwidth','Poop Deck Packets','Midnight Buffet Mbps','Shuffleboard Shipping Lines','All-You-Can-Stream Cruises','Iceberg Ahead Voyages']},
marsorb:{l:tr('businesses.mars_mission_over_your_pies'),opts:[50,100,200],rate:35000,orbit:true,las:true,share:0.05,lv:13,names:['Red Planet Relay (Orbital)','Olympus Mons Uplink (Orbital)','Light-Minute Logistics (Orbital)','Interplanetary Ping Society (Orbital)','Rover Over Pies']},
pizza:{l:tr('businesses.pizza_homes_and_boats_on_orbit'),opts:[50,100,200,400],rate:25000,orbit:true,lv:1,names:['Deep Dish Rural Broadband','Crust Mile Connect','Topping Off Telecom','Extra Cheese Islands Net','Slice of Life Homesteads','Calzone Ranch Wi-Fi','Thin Crust Tundra Net','Margherita Marina Moorings','Anchovy Atoll Online','Stuffed Crust Station Hands']},
flywifi:{l:tr('businesses.flywifi_airline_wi_fi'),opts:[20,50,100,200],rate:36000,orbit:true,las:true,share:0.2,lv:1,names:['Jet Lag Wi-Fi','Wi-Fly Away','Seatback Streaming Co.','Tray Table Upright Telecom','Cabin Pressure Networks','Mile High Megabits','Overhead Bin Broadband','Turbulence Tolerant Transit']},
boat:{l:tr('businesses.cruise_ship_connectivity'),opts:[100,200,400,800],rate:27500,orbit:true,lv:1,names:['Buffet Overboard Cruises','The Love Bandwidth','Poop Deck Packets','Midnight Buffet Mbps','Shuffleboard Shipping Lines','All-You-Can-Stream Cruises','Iceberg Ahead Voyages']},
marsorb:{l:tr('businesses.mars_mission_over_your_pies'),opts:[50,100,200],rate:44000,orbit:true,las:true,share:0.05,lv:13,names:['Red Planet Relay (Orbital)','Olympus Mons Uplink (Orbital)','Light-Minute Logistics (Orbital)','Interplanetary Ping Society (Orbital)','Rover Over Pies']},
provedor:{l:tr('businesses.provedor_small_regional_isp'),opts:[5,10,20,40],rate:20,br:true,names:['Provedor Capivara Net','Fibra do Sertão','Rapidinho Telecom','Net Jabuticaba','Caipirinha Online','Wi-Fi do Zé','Pão de Queijo Fibra','Açaí Net','Tucano Telecom','Forró Fibra','Saci Net','Brigadeiro Banda Larga','Mandioca Online','Churrasco Connect']},
};
const LEVELS=[

View file

@ -5,7 +5,7 @@
your crusts can sell (PIE_SELL of their capacity, the rest flies over ocean and empty land) caps what is signed and
on offer, so orbit income cannot outgrow the sky (like F5). Remote towns (no POP of yours, few people) are the first
to call: Pitcairn, the Arctic, the outer islands. */
const PIE_SELL=0.25,PIE_REMOTE=0.6,PIE_OFFER_RATE=1/6,PIE_OFFERS=2;
const PIE_SELL=0.4,PIE_REMOTE=0.6,PIE_OFFER_RATE=1/3,PIE_OFFERS=2;
// Orbit customers know the sky has bad weeks: without service they lose at most PIE_PATIENCE happiness a day (the day tick),
// so they grumble, then fume, and cancel only after about a month of nothing, not in three days like a fiber customer.
const PIE_PATIENCE=4;
@ -27,5 +27,5 @@ function pieSpawn(t){const T=BIZ_T[t],min=T.opts[0],ok=pieCands(t).filter(c=>{if
const left=Math.min(pieRoom(t),pieServe(city,t).left-S.offers.reduce((a,o)=>a+(BIZ_T[o.type].orbit?o.bw:0),0)),opts=T.opts.filter(g=>g<=left),bw=opts.length?pick(opts):0;if(!bw)return;
const list=T.names.filter(n=>!S.usedNames.includes(n)),name=list.length?pick(list):pick(T.names);useName(name);
S.offers.push({id:uid(),city,city2:null,name,type:t,bw,rate:T.rate,reqs:[],exp:S.day+40});}
// Orbit has its own sales desk, so the ground's offers keep their odds: about one call a week, two on the table at most.
// Orbit has its own sales desk, so the ground's offers keep their odds: about one call every three days, two on the table at most.
PIE_ON.day.push(()=>{if(S.offers.filter(o=>BIZ_T[o.type].orbit).length>=PIE_OFFERS)return;const t=pieOfferTypes();if(t.length&&Math.random()<PIE_OFFER_RATE)pieSpawn(pick(t));});

View file

@ -639,38 +639,8 @@ test('O7: a fresh Tier 1 cannot afford a full Shortcrust in its first year', ()
assert.deepEqual(g.errors, []);
});
// Years a full crust takes to pay for itself: the build (company, factory, pad, rockets, lasered pies, the dishes it needs
// and landing rights) over a year's orbit income less running costs, licences and replacing the pies as they age out.
const PAYBACK = `((cr,rev,dishes,lic)=>{const C=CRUSTS[cr],ndish=dishes??Math.ceil(C.g*PIE_SELL/(PIE_ANT_MAX*PIE_ANT_G));
const build=pieFullCost(cr)+C.full*PIE_LAS+ndish*piePrice(PIE_DISH+PIE_ANT*PIE_ANT_MAX)+lic;
const renew=(C.full*(PIE_PIE+PIE_LAS)+Math.ceil(C.full/ROCKETS.heavy.pies)*ROCKETS.heavy.cost)/(C.life/360);
return build/(12*rev-12*(PIE_CO_MO+PIE_FAC_MO+PIE_PAD_MO+ndish*PIE_DISH_MO)-lic-renew);})`;
test('O7: a full constellation never pays back in under 5 years, and a strong network’s pays back in 5 to 10', () => {
const g = load();
// (A negative answer: it never pays back.) The best case for every crust: every Gbps the sky can sell is sold, the capped kinds at their cap, the rest at the
// dearest rate, all served. A dish needs a city of its own (one per POP), so the dishes it takes pay the cheapest
// landing rights any set of that many covered cities in the world could have.
const best = JSON.parse(g.ev(`JSON.stringify(Object.keys(CRUSTS).map(cr=>{const T=Object.values(BIZ_T).filter(t=>t.orbit);let left=1,r=0;
for(const t of T.filter(t=>t.share)){r+=t.share*t.rate;left-=t.share;}r+=left*Math.max(...T.filter(t=>!t.share).map(t=>t.rate));
const nd=Math.ceil(CRUSTS[cr].g*PIE_SELL/(PIE_ANT_MAX*PIE_ANT_G)),n={};for(const c of CITIES)if(pieCovers(cr,c.id))n[c.cc]=(n[c.cc]||0)+1;
let k=0,lic=0;for(const cc of Object.keys(n).sort((a,b)=>pieLicPrice(a)/n[a]-pieLicPrice(b)/n[b])){if(k>=nd)break;k+=n[cc];lic+=pieLicPrice(cc);}
return [cr,${PAYBACK}(cr,CRUSTS[cr].g*PIE_SELL*r,nd,lic)];}))`));
for (const [cr, y] of best) assert.ok(y < 0 || y >= 5, `O7: a full ${cr} pays back in ${y.toFixed(1)} years at best; make orbit dearer or its customers cheaper`);
// The seeded reference: the big-network save, a full lasered Shortcrust, 32 full dishes in the cheapest countries to
// license, and every orbit customer the market offers signed (the real offers, routed by compute()).
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));S.pieV=1;S.nextFail=1e9;S.nextEvent=1e9;__reseed(7);compute()`);
const ref = JSON.parse(g.ev(`(()=>{pieInit();const P=S.pie;P.co={name:PIE_NAMES[0]};P.fac=true;P.pads=[{city:'mia',next:0,boosters:[]}];
const pops=Object.keys(S.pops).filter(c=>pieCovers('short',c)),n={};for(const c of pops)n[CITY[c].cc]=(n[CITY[c].cc]||0)+1;
const top=pops.sort((a,b)=>pieLicPrice(CITY[a].cc)/n[CITY[a].cc]-pieLicPrice(CITY[b].cc)/n[CITY[b].cc]||CITY[b].P-CITY[a].P).slice(0,32);
for(const c of top){P.dishes.push({id:'d'+c,city:c,ant:PIE_ANT_MAX,down:0});P.lic[CITY[c].cc]={state:'ok',until:1e6};}
P.crusts.short.cohorts=[{n:CRUSTS.short.full,day:S.day,las:true}];compute();
for(let i=0;i<4000&&pieSold()<pieMarket()-20;i++){S.offers=S.offers.filter(o=>!BIZ_T[o.type].orbit);const t=pieOfferTypes();if(!t.length)break;pieSpawn(pick(t));const o=S.offers.find(o=>BIZ_T[o.type].orbit);if(o)ACT.accept({id:o.id});}
compute();const lic=Object.keys(P.lic).reduce((a,cc)=>a+pieLicPrice(cc),0);return JSON.stringify({rev:R.pie.rev,y:${PAYBACK}('short',R.pie.rev,top.length,lic)});})()`));
assert.ok(ref.y >= 5 && ref.y <= 10, `O7: the reference Shortcrust pays back in ${ref.y.toFixed(1)} years on ${Math.round(ref.rev / 1e6)}M/mo from orbit; aim for 6 to 10`);
assert.deepEqual(g.errors, []);
});
// O7's other half (a full lasered Shortcrust pays back in 5 to 10 years, never sooner) is played through the game loop
// in tests/pie-balance.test.js, so it counts launches, aging, incidents, churn and every running cost.
test('no page errors while checking the rules', () => {
assert.deepEqual(errors, []);

85
tests/pie-balance.test.js Normal file
View file

@ -0,0 +1,85 @@
// Rule O7, played: the big-network save becomes a rocket company and runs a full lasered Shortcrust through the real
// day tick (pieDay, launches, aging, incidents, spats, offers, moods, orbit income), by a sensible player's policy.
// Seeded. Orbit is judged on its own books (S.pie.book): the fixture's ground network loses money on its own.
// It plays until the books balance (at most 10 years). PIE_BALANCE_YEARS=10 node --test tests/pie-balance.test.js plays
// that many years whatever happens and prints them year by year, PIE_BALANCE_DIAG=1 also monthly with the spending by kind
// and PIE_BALANCE_SEED another seed (for tuning).
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const YEARS = +(process.env.PIE_BALANCE_YEARS || 0);
// The policy, once a day before the tick:
// - a company, a factory, the reuse R&D and two pads, the coastal POPs nearest the equator;
// - lasered Shortcrust on the reusable rocket while the crust is short of full (never past it: replacements only), at most
// two launches per pad in the queue;
// - safe mode while a solar storm is on;
// - the ground grows with the customers: an antenna on the busiest dish when one is over 90% or the healthy dishes (fiber
// there at least 97% up) hold less than 1.3x what is sold, a new dish when every healthy dish has 16, at a well-served
// POP under the crust (fiber at least 98% up), cheapest landing rights first, the first eight spread out;
// - landing rights renewed before they lapse, every orbit offer signed.
// compute() runs every 30 days and whenever what the sky carries changes (coverage in 10% steps, hubs, lasers,
// safe mode, an orbit incident or spat starting or ending); orbit income is booked from the last one, as in the game.
function sim(days, stop = false, seed = 7) {
const g = load({ seed });
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));S.pieV=1;UI.started=true;UI.pitched=true;UI.speed=0;S.nextFail=1e9;S.nextEvent=1e9;
isTier1=()=>true;after=()=>{};pieModal=()=>{};compute();pieInit();UI.pieLas=true;ACT.pieFound();ACT.pieFactory();ACT.pieRd({k:'reuse'});
for(const c of Object.keys(S.pops).filter(c=>pieCoast(c)&&piePadOk(c,'short')).sort((a,b)=>Math.abs(CITY[a].lat)-Math.abs(CITY[b].lat)).slice(0,2))ACT.piePad({city:c});
window.__site=()=>{const ds=S.pie.dishes,lic=c=>pieLicOk(CITY[c].cc)?0:pieLicPrice(CITY[c].cc);
const c=Object.keys(S.pops).filter(c=>pieCovers('short',c)&&!ds.some(x=>x.city===c)&&sfOf(R,c)>=0.98).sort((a,b)=>lic(a)-lic(b)||CITY[b].P-CITY[a].P);
return (ds.length<8&&c.find(x=>ds.every(d=>pieKm(d.city,x)>=1500)))||c[0];};
window.__step=()=>{const P=S.pie,C=CRUSTS.short,rk=P.rd.reuse?'again':'falcon';S.nextFail=1e9;S.nextEvent=1e9;let dirty=false;
while(P.q.length<2*P.pads.length&&pieLive('short')+P.crusts.short.queued+ROCKETS[rk].pies<=C.full){if(!pieQuote(rk,'short',{las:true}).ok)break;ACT.pieLaunch({rk,cr:'short'});}
const storm=S.inc.some(i=>i.type==='piestorm'&&i.until>S.day);if(storm!==P.safe){ACT.pieSafe();dirty=true;}
if(pieUp('short')){const ok=x=>pieLicOk(CITY[x.city].cc)&&sfOf(R,x.city)>=0.97,u=x=>((R.pie&&R.pie.used[x.city])||0)/(x.ant*PIE_ANT_G);
const cap=pieDishes().filter(ok).reduce((a,d)=>a+d.g,0),need=Math.min(pieMarket(),pieSold()*1.3+400);
if(cap<need||P.dishes.some(x=>ok(x)&&u(x)>0.9&&x.ant<PIE_ANT_MAX)){const d=P.dishes.filter(x=>ok(x)&&x.ant<PIE_ANT_MAX).sort((a,b)=>u(b)-u(a))[0];
if(d)ACT.pieAnt({id:d.id});else{const c=__site();if(c){if(!pieLicOk(CITY[c].cc))ACT.pieLic({cc:CITY[c].cc});ACT.pieDish({city:c});}}}}
for(const d of P.dishes){const l=P.lic[CITY[d.city].cc];if(l&&l.state==='ok'&&l.until-S.day<5)ACT.pieLic({cc:CITY[d.city].cc});}
for(const o of S.offers.filter(o=>BIZ_T[o.type].orbit))ACT.accept({id:o.id});
const key=[pieHubs().join(),Math.round(pieCarry('short')*10),Math.round(pieCov('short')*10),pieLased('short'),P.safe,S.inc.filter(i=>PIE_INC.includes(i.type)&&i.until>S.day).map(i=>i.id).join(),Object.keys(P.spat).join()].join('|');if(key!==window.__key)dirty=true;window.__key=key;
const real=compute;compute=()=>{if(dirty||S.day%30===0){window.__nC=(window.__nC||0)+1;real();}};try{dayTick();}finally{compute=real;}};
window.__year=()=>({y:Math.round(S.day/360),spent:S.pie.book.spent,earned:S.pie.book.earned,mo:(R.pie&&R.pie.rev)||0,cov:pieCov('short'),cust:S.biz.filter(b=>BIZ_T[b.type].orbit).length,dishes:S.pie.dishes.length,nC:window.__nC|0});
closeModal()`);
if (process.env.PIE_BALANCE_DIAG) g.ev(`window.__B={};for(const k of ['pieLaunch','pieDish','pieAnt','pieLic','pieRd','pieFound','pieFactory','piePad','fixInc','pieSpatPick']){const f=ACT[k];if(!f)continue;ACT[k]=a=>{const s0=S.pie.book.spent;const r=f(a);__B[k]=(__B[k]||0)+(S.pie.book.spent-s0)/1e6;return r;};}
{const f=pieDay;pieDay=d=>{const s0=S.pie.book.spent;f(d);__B.day=(__B.day||0)+(S.pie.book.spent-s0)/1e6;};}`);
const rows = [];
try {
const d0 = g.ev('S.day');
for (let d = 1; d <= days; d++) {
g.ev('__step()');
if (d % 360 === 0) { rows.push(JSON.parse(g.ev('JSON.stringify(__year())'))); if (stop && rows[rows.length - 1].earned >= rows[rows.length - 1].spent) break; }
if (process.env.PIE_BALANCE_DIAG && d % 30 === 0) console.log(d, g.ev(`JSON.stringify({c:S.biz.filter(b=>BIZ_T[b.type].orbit).length,un:S.biz.filter(b=>BIZ_T[b.type].orbit&&!((R.pie.sf[b.id]||0)>=0.95)).length,mo:Math.round(R.pie.rev/1e6),hubs:pieHubs(),las:pieLased('short'),cov:+pieCov('short').toFixed(2),inc:S.inc.filter(i=>i.type.startsWith('pie')).map(i=>i.type),spat:Object.keys(S.pie.spat),safe:S.pie.safe,B:Object.fromEntries(Object.entries(__B).map(([k,v])=>[k,Math.round(v)]))})`));
}
rows.d0 = d0;
} finally { g.ev('closeModal()'); }
return { rows, errors: g.errors, ev: g.ev };
}
// The year the books balance, within the year it happens. The run stops there (at most 10 years); one that never
// balances is carried on by its last year's net, for the message.
function payback(rows) {
for (let i = 0; i < rows.length; i++) {
const r = rows[i], p = rows[i - 1] || { y: 0, spent: 0, earned: 0 };
if (r.earned >= r.spent) return p.y + (p.spent - p.earned) / ((r.earned - p.earned) - (r.spent - p.spent));
}
const a = rows[rows.length - 2], b = rows[rows.length - 1], net = (b.earned - a.earned) - (b.spent - a.spent);
return net > 0 ? b.y + (b.spent - b.earned) / net : Infinity;
}
test('O7: a full lasered Shortcrust, run sensibly through the game loop, pays back in 5 to 10 years', { timeout: 600000 }, () => {
const years = YEARS || 10;
const { rows, errors } = sim(360 * years, !YEARS, +(process.env.PIE_BALANCE_SEED || 7));
if (YEARS) for (const r of rows) console.log(`year ${r.y}: spent ${(r.spent / 1e9).toFixed(2)}B, earned ${(r.earned / 1e9).toFixed(2)}B, orbit ${(r.mo / 1e6).toFixed(0)}M/mo, ${Math.round(r.cov * 100)}% covered, ${r.cust} customers, ${r.dishes} dishes, ${r.nC} computes`);
const last = rows[rows.length - 1], y = payback(rows);
if (YEARS) console.log(`payback: year ${y.toFixed(1)}`);
assert.ok(last.cov > 0.9, `O7: the crust is full after ${years} years (${Math.round(last.cov * 100)}%)`);
assert.ok(last.cust > 30, `O7: customers stay (${last.cust})`);
assert.ok(y >= 5, `O7: a full Shortcrust pays back in ${y.toFixed(1)} years; make orbit dearer or its customers fewer`);
assert.ok(y <= 10, `O7: a full Shortcrust pays back in ${y.toFixed(1)} years (spent ${(last.spent / 1e9).toFixed(1)}B, earned ${(last.earned / 1e9).toFixed(1)}B by year ${last.y}); make orbit cheaper or its customers more`);
assert.deepEqual(errors, []);
});

View file

@ -81,7 +81,7 @@ test('actions cost what they should', () => {
assert.equal(step(`ACT.pieAnt({id:'${id}'})`), ev('piePrice(PIE_ANT)'));
assert.equal(step("ACT.pieLic({cc:'DE'})"), ev("pieLicPrice('DE')"));
assert.ok(ev("pieLicPrice('US')") > ev("pieLicPrice('LU')"), 'big markets cost more');
assert.ok(ev("pieLicPrice('US')") <= 200e6 && ev("pieLicPrice('MH')") >= 10e6);
assert.ok(ev("pieLicPrice('US')<=PIE_LIC_MAX") && ev("pieLicPrice('MH')") >= 10e6);
assert.equal(ev("pieLicOk('DE')&&pieDishes().length"), 1, 'a licensed dish is live');
// a launch: rocket with the equatorial discount, 20 pies, the party later
ev('S.pie.stock=100');