diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 46d6b7e..294d399 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -90,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 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. | +| 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 (and the Ex-Im Pie Bank's most) 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; government money (the Rural Digital Pie Fund, Pitcairn's satellite grant) brings that forward by at most two years, never under four (`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. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b3031a..bb12e9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ All notable changes to this project are documented here. The project follows - 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. +- Governments now pay for space too, in a new Gov tab in Pie Control. The Rural Digital Pie Fund auctions support for remote towns only your satellites reach: ask less than the rival and you are paid every month for five years, as long as the town stays well served after a three-month deadline, or the award is taken away and half of it paid back. The Ex-Im Pie Bank lends a rocket company a lot of money at under 3%, if you launch the pies you promised by a deadline and keep a pie dish in its country; break that and the rate goes up and its government picks a fight. And the UK now pays a smaller grant for Pitcairn when the islanders are online through your satellites. - 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. diff --git a/docs/plans/pie-in-the-sky.md b/docs/plans/pie-in-the-sky.md index 4ee53d9..a865812 100644 --- a/docs/plans/pie-in-the-sky.md +++ b/docs/plans/pie-in-the-sky.md @@ -87,6 +87,19 @@ Reuse the existing sanctions / sovereign-drill / China licence machinery where i - Not over my airspace: two countries each demand their traffic avoid the other's dishes. Each spat is a notification with 2 choices; outcomes deterministic per seed. +## Government money (`60-features/99-pie-subsidies.js`, Pie Control's Gov tab) + +- Rural Digital Pie Fund: reverse auctions for towns only orbit reaches (a cut-off POP on backhaul, or a small town of + your terminal customers). You ask 90%, 70% or 50% of the reserve; a rival asks 40-100%; the lower ask wins and is paid + monthly for 5 years. From a 90-day deadline the town's service, averaged per month, must stay at 70%, or the award is + revoked and half of what it paid is clawed back. Counts in `book.earned`. +- Ex-Im Pie Bank: a BANKS loan (never offered by the usual banks) of half the value of the pies flying and booked, at most + 20% of a full Shortcrust (O7 counts it), 1.5-2.5% over 60 months. Covenants: launch n pies in a year, keep a dish in the + lending country. A breach: the bank's penalty, +3 points, the launch deadline moved, and with chaos a spat there + (`home` or `lic`). Off the books: financing, not orbit income. +- Pitcairn: served from orbit (its POP on backhaul, or home terminals there) at 90% of its demand, latency forgiven, the UK + pays `GRANT_SKY_MO` instead of `GRANT_MO`. Counts in `book.earned`. + ## Visualisation: a separate animated 3D globe Satellites are NEVER drawn on the existing map (no cost there). The map only gets static pie dish icons diff --git a/site/i18n/de.js b/site/i18n/de.js index aabb356..6ff8660 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -308,6 +308,10 @@ "banks.do_the_kehrwoche_keep_your_noc":"Mach die Kehrwoche: Halte dein NOC frei von Störungen, die älter als eine Woche sind.", "banks.download_our_app_and_enable_all":"Lade unsere App herunter und aktiviere alle Benachrichtigungen.", "banks.every_pop_needs_a_backup_generator":"Jeder POP braucht einen Notstromgenerator. Unser Risikoteam hat einen Katastrophenfilm gesehen.", +"banks.exim_blurb":"Der Staat leiht dir Geld, damit du Raketen aus dem Inland kaufst. Weltraum-Auflagen inklusive.", +"banks.exim_keep_a_dish_in":"Eine Pie-Schüssel in {a} behalten", +"banks.exim_launch_n_pies_by":"{n} Pies bis {d} starten ({f} bisher)", +"banks.exim_launch_pies":"Die versprochenen Pies starten", "banks.fill_in_form_t_17b_in":"Fülle Formular T-17b in dreifacher Ausfertigung aus, jeden Monat, für immer.", "banks.give_our_ceo_s_nephew_a":"Gib dem Neffen unseres CEOs einen Job. Er braucht {price}/Monat und einen Parkplatz.", "banks.instant_approval_instant_regret":"Sofortige Zusage. Sofortige Reue.", @@ -3510,6 +3514,42 @@ "pie_globe.switch_to_day_view":"Zur Tagansicht wechseln", "pie_globe.switch_to_night_view":"Zur Nachtansicht wechseln", "pie_globe.your_pies_in_orbit":"Deine Kuchen im Orbit, zum Drehen der Erde ziehen", +"pie_gov.ask":"{mo}/Monat fordern", +"pie_gov.bid":"Bieten", +"pie_gov.closes":"Gebote bis {d}", +"pie_gov.cov_dish":"Eine Pie-Schüssel in {a} behalten", +"pie_gov.cov_launch":"{n} Pies bis {d} starten", +"pie_gov.due":"Braucht {p} Versorgung bis {d}", +"pie_gov.exim":"Ex-Im Pie Bank", +"pie_gov.exim_breach":"Brichst du eine Auflage, steigt der Zins um {apr} Punkte, die Frist verschiebt sich und das Geberland ist sauer.", +"pie_gov.exim_none":"Gerade kein Angebot. Die Bank leiht Raketenfirmen mit einer Fabrik.", +"pie_gov.exim_offer":"Leiht dir {amt} zu {apr} % für {n} Monate: {pay}/Monat.", +"pie_gov.no_auction":"Keine Auktion offen. Der Fonds meldet sich, wenn eine Stadt, die nur deine Pies erreichen, gefördert wird.", +"pie_gov.open":"Öffnen", +"pie_gov.pitcairn":"Pitcairn", +"pie_gov.pitcairn_note":"UK zahlt {mo}/Monat, solange die Inselbewohner gut versorgt sind, und akzeptiert Satellit für {sky}/Monat.", +"pie_gov.rdf":"Rural Digital Pie Fund", +"pie_gov.rdf_note":"Umgekehrte Auktionen für Städte, die nur der Orbit erreicht: Die niedrigste Forderung gewinnt und wird {y} Jahre lang monatlich bezahlt. Halte die Stadt im Monatsschnitt bei {p} Versorgung: Zwei Monate in Folge darunter und die Förderung wird entzogen und {c} der Förderung des letzten Jahres zurückgefordert.", +"pie_gov.rival_coop":"Genossenschaft Kabelsalat", +"pie_gov.rival_hugsnet":"HugsNet", +"pie_gov.rival_viasad":"ViaSad", +"pie_gov.served":"{p} versorgt", +"pie_gov.t_auction":"Förderung für {city}: bis zu {mo}/Monat für {y} Jahre. Gebote bis {d}.", +"pie_gov.t_auction_title":"Auktion des Rural Digital Pie Fund", +"pie_gov.t_bid":"Gebot für {city} abgegeben: {mo}/Monat. Ergebnis am {d}.", +"pie_gov.t_breach":"Die Ex-Im Pie Bank zieht die Schrauben an: jetzt {apr} %, und {a} ist nicht amüsiert.", +"pie_gov.t_breach_spat":"Die Regierung dort hat Fragen.", +"pie_gov.t_done":"Die Förderung für {city} ist ausgelaufen: insgesamt {amt} bezahlt.", +"pie_gov.t_exim":"Die Ex-Im Pie Bank leiht dir {amt} fast umsonst, wenn du eine Pie-Schüssel in {a} behältst.", +"pie_gov.t_exim_title":"Staatsgeld für Raketen", +"pie_gov.t_lost":"{rival} hat {city} gewonnen und nur {mo}/Monat gefordert.", +"pie_gov.t_revoked":"Förderung für {city} entzogen: {p} versorgt, der Fonds will {need}. Er fordert {amt} zurück.", +"pie_gov.t_warn":"Der Fonds beobachtet {city}: letzten Monat {p} versorgt, er will {need}. Noch so ein Monat und die Förderung ist weg.", +"pie_gov.t_won":"Du hast {city} gewonnen: {mo}/Monat. Bis {d} brauchst du {p} Versorgung.", +"pie_gov.tab":"Staat", +"pie_gov.until":"Bezahlt bis {d}", +"pie_gov.up_to":"bis zu {mo}/Monat", +"pie_gov.warned":"noch ein schlechter Monat und sie ist weg", "pie_inc.dig_msg":"Ein Bagger hat die Backhaul-Glasfaser unter der Pie-Schüssel in {city} gefunden. Die Schüssel ist heil, aber ihr Traffic kommt nirgends hin.", "pie_inc.dig_press":"Die Pressestelle sagt: Die Schüssel macht eine wohlverdiente Pause vom Boden.", "pie_inc.food_fix":"Einen Space Roomba kaufen", @@ -3662,6 +3702,7 @@ "pie_traffic.via_dishes":"hoch in {up}, runter in {down}", "pitcairn.uk_grant_mo":"Zuschuss aus UK {mo}/Monat", "pitcairn.uk_grant_mo_once_islanders":"Zuschuss aus UK {mo}/Monat, sobald die Inselbewohner online sind", +"pitcairn.uk_sky_grant_mo":"Satelliten-Zuschuss aus UK {mo}/Monat (Glasfaser bekommt {full})", "pni_all.additional_per_month":"Zusätzliche Kosten pro Monat", "pni_all.all_at_port":"Mit allen Netzen peeren · {port}", "pni_all.delivery_and_traffic_charges":"Die Lieferzeiten hängen vom Netz ab. Wo verlangt, kommen trafficabhängige Peering-Gebühren dazu.", diff --git a/site/i18n/es.js b/site/i18n/es.js index d1a1b7d..8651ef4 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -306,6 +306,10 @@ "banks.do_the_kehrwoche_keep_your_noc":"Haz la Kehrwoche: mantén tu NOC libre de incidentes de más de una semana.", "banks.download_our_app_and_enable_all":"Descarga nuestra app y activa todas las notificaciones.", "banks.every_pop_needs_a_backup_generator":"Todo POP necesita un generador de respaldo. Nuestro equipo de riesgos vio una película de desastres.", +"banks.exim_blurb":"El Estado te presta dinero para comprar cohetes nacionales. Se aplican cláusulas espaciales.", +"banks.exim_keep_a_dish_in":"Mantén una antena-tarta en {a}", +"banks.exim_launch_n_pies_by":"Lanza {n} tartas antes del {d} ({f} hasta ahora)", +"banks.exim_launch_pies":"Lanza las tartas prometidas", "banks.fill_in_form_t_17b_in":"Rellena el formulario T-17b por triplicado, cada mes, para siempre.", "banks.give_our_ceo_s_nephew_a":"Dale trabajo al sobrino de nuestro CEO. Necesita {price}/mes y una plaza de aparcamiento.", "banks.instant_approval_instant_regret":"Aprobación instantánea. Arrepentimiento instantáneo.", @@ -3508,6 +3512,42 @@ "pie_globe.switch_to_day_view":"Cambiar a vista de día", "pie_globe.switch_to_night_view":"Cambiar a vista nocturna", "pie_globe.your_pies_in_orbit":"Tus tartas en órbita, arrastra para girar la Tierra", +"pie_gov.ask":"Pedir {mo}/mes", +"pie_gov.bid":"Pujar", +"pie_gov.closes":"pujas hasta el {d}", +"pie_gov.cov_dish":"Mantén una antena-tarta en {a}", +"pie_gov.cov_launch":"Lanza {n} tartas antes del {d}", +"pie_gov.due":"Necesita {p} de servicio antes del {d}", +"pie_gov.exim":"Ex-Im Pie Bank", +"pie_gov.exim_breach":"Si incumples una cláusula, el tipo sube {apr} puntos, el plazo se mueve y el país prestamista se enfada.", +"pie_gov.exim_none":"Ahora no hay oferta. El banco presta a empresas de cohetes con fábrica.", +"pie_gov.exim_offer":"Te presta {amt} al {apr} % durante {n} meses: {pay}/mes.", +"pie_gov.no_auction":"No hay subasta abierta. El fondo llama cuando un pueblo al que solo llegan tus tartas opta a una ayuda.", +"pie_gov.open":"Abrir", +"pie_gov.pitcairn":"Pitcairn", +"pie_gov.pitcairn_note":"El Reino Unido paga {mo}/mes mientras los isleños estén bien servidos, y acepta el satélite por {sky}/mes.", +"pie_gov.rdf":"Rural Digital Pie Fund", +"pie_gov.rdf_note":"Subastas inversas para pueblos a los que solo llega la órbita: gana la petición más baja y cobra cada mes durante {y} años. Mantén el pueblo servido al {p} de media cada mes: dos meses seguidos por debajo y la ayuda se revoca y se devuelve el {c} de la ayuda del último año.", +"pie_gov.rival_coop":"Cooperativa La Parabólica", +"pie_gov.rival_hugsnet":"HugsNet", +"pie_gov.rival_viasad":"ViaSad", +"pie_gov.served":"{p} servido", +"pie_gov.t_auction":"Ayuda para {city}: hasta {mo}/mes durante {y} años. Pujas hasta el {d}.", +"pie_gov.t_auction_title":"Subasta del Rural Digital Pie Fund", +"pie_gov.t_bid":"Puja hecha por {city}: {mo}/mes. Resultado el {d}.", +"pie_gov.t_breach":"El Ex-Im Pie Bank endurece tus condiciones: ahora {apr} %, y {a} no está contento.", +"pie_gov.t_breach_spat":"Su gobierno tiene preguntas.", +"pie_gov.t_done":"La ayuda del fondo para {city} ha terminado: {amt} pagados en total.", +"pie_gov.t_exim":"El Ex-Im Pie Bank te prestaría {amt} casi gratis, si mantienes una antena-tarta en {a}.", +"pie_gov.t_exim_title":"Dinero público para cohetes", +"pie_gov.t_lost":"{rival} ganó {city} pidiendo solo {mo}/mes.", +"pie_gov.t_revoked":"Ayuda para {city} revocada: {p} servido, el fondo quiere {need}. Reclama {amt}.", +"pie_gov.t_warn":"El fondo vigila {city}: {p} servido el mes pasado, quiere {need}. Otro mes así y la ayuda se revoca.", +"pie_gov.t_won":"Ganaste {city}: {mo}/mes. Tenlo servido al {p} antes del {d}.", +"pie_gov.tab":"Gobierno", +"pie_gov.until":"Pagado hasta el {d}", +"pie_gov.up_to":"hasta {mo}/mes", +"pie_gov.warned":"un mes malo más y se revoca", "pie_inc.dig_msg":"Una excavadora encontró la fibra de backhaul bajo la antena-tarta de {city}. La antena está bien, pero su tráfico no tiene adónde ir.", "pie_inc.dig_press":"La oficina de prensa dice: la antena se toma un merecido descanso del suelo.", "pie_inc.food_fix":"Comprar una Space Roomba", @@ -3660,6 +3700,7 @@ "pie_traffic.via_dishes":"sube en {up}, baja en {down}", "pitcairn.uk_grant_mo":"Subvención británica {mo}/mes", "pitcairn.uk_grant_mo_once_islanders":"Subvención británica {mo}/mes cuando los isleños estén en línea", +"pitcairn.uk_sky_grant_mo":"Subvención británica por satélite {mo}/mes (la fibra recibe {full})", "pni_all.additional_per_month":"Coste mensual adicional", "pni_all.all_at_port":"Peering con todas las redes · {port}", "pni_all.delivery_and_traffic_charges":"Los plazos de entrega varían según la red. También se aplican cargos de peering basados en el tráfico cuando corresponda.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 0220d45..ae27cdd 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -306,6 +306,10 @@ "banks.do_the_kehrwoche_keep_your_noc":"Fais la Kehrwoche : aucun incident de plus d’une semaine dans ton NOC.", "banks.download_our_app_and_enable_all":"Télécharge notre appli et active toutes les notifications.", "banks.every_pop_needs_a_backup_generator":"Chaque POP doit avoir un groupe électrogène. Notre service risques a vu un film catastrophe.", +"banks.exim_blurb":"L'État te prête de quoi acheter des fusées du pays. Clauses spatiales en sus.", +"banks.exim_keep_a_dish_in":"Garder une antenne-tarte en {a}", +"banks.exim_launch_n_pies_by":"Lancer {n} tartes d'ici le {d} ({f} pour l'instant)", +"banks.exim_launch_pies":"Lancer les tartes promises", "banks.fill_in_form_t_17b_in":"Remplis le Cerfa T-17b en trois exemplaires, chaque mois, pour toujours.", "banks.give_our_ceo_s_nephew_a":"Embauche le neveu de notre PDG. Il lui faut {price}/mois et une place de parking.", "banks.instant_approval_instant_regret":"Accord instantané. Regrets instantanés.", @@ -3508,6 +3512,42 @@ "pie_globe.switch_to_day_view":"Passer en vue de jour", "pie_globe.switch_to_night_view":"Passer en vue de nuit", "pie_globe.your_pies_in_orbit":"Tes tartes en orbite, fais glisser pour tourner la Terre", +"pie_gov.ask":"Demander {mo}/mois", +"pie_gov.bid":"Enchérir", +"pie_gov.closes":"enchères jusqu'au {d}", +"pie_gov.cov_dish":"Garder une antenne-tarte en {a}", +"pie_gov.cov_launch":"Lancer {n} tartes d'ici le {d}", +"pie_gov.due":"Doit être servie à {p} d'ici le {d}", +"pie_gov.exim":"Ex-Im Pie Bank", +"pie_gov.exim_breach":"Romps une clause et le taux monte de {apr} points, l'échéance bouge et le pays prêteur se fâche.", +"pie_gov.exim_none":"Pas d'offre pour l'instant. La banque prête aux sociétés de fusées qui ont une usine.", +"pie_gov.exim_offer":"Te prête {amt} à {apr} % sur {n} mois : {pay}/mois.", +"pie_gov.no_auction":"Aucune enchère ouverte. Le fonds appelle quand une ville que seules tes tartes atteignent peut être aidée.", +"pie_gov.open":"Ouvrir", +"pie_gov.pitcairn":"Pitcairn", +"pie_gov.pitcairn_note":"Le Royaume-Uni paie {mo}/mois tant que les insulaires sont bien servis, et accepte le satellite pour {sky}/mois.", +"pie_gov.rdf":"Rural Digital Pie Fund", +"pie_gov.rdf_note":"Enchères inversées pour les villes que seule l'orbite atteint : la demande la plus basse gagne et est payée chaque mois pendant {y} ans. Garde la ville servie à {p} en moyenne chaque mois : deux mois de suite en dessous et l'aide est retirée, et {c} de l'aide de la dernière année est récupéré.", +"pie_gov.rival_coop":"Coopérative La Parabole", +"pie_gov.rival_hugsnet":"HugsNet", +"pie_gov.rival_viasad":"ViaSad", +"pie_gov.served":"{p} servi", +"pie_gov.t_auction":"Aide pour {city} : jusqu'à {mo}/mois pendant {y} ans. Enchères jusqu'au {d}.", +"pie_gov.t_auction_title":"Enchère du Rural Digital Pie Fund", +"pie_gov.t_bid":"Offre déposée pour {city} : {mo}/mois. Résultat le {d}.", +"pie_gov.t_breach":"L'Ex-Im Pie Bank durcit tes conditions : {apr} % maintenant, et {a} n'apprécie pas.", +"pie_gov.t_breach_spat":"Son gouvernement a des questions.", +"pie_gov.t_done":"L'aide du fonds pour {city} est terminée : {amt} versés en tout.", +"pie_gov.t_exim":"L'Ex-Im Pie Bank te prêterait {amt} pour presque rien, si tu gardes une antenne-tarte en {a}.", +"pie_gov.t_exim_title":"De l'argent public pour des fusées", +"pie_gov.t_lost":"{rival} a gagné {city} en ne demandant que {mo}/mois.", +"pie_gov.t_revoked":"Aide pour {city} retirée : {p} servi, le fonds veut {need}. Il récupère {amt}.", +"pie_gov.t_warn":"Le fonds surveille {city} : {p} servi le mois dernier, il veut {need}. Encore un mois comme ça et l'aide est retirée.", +"pie_gov.t_won":"Tu as gagné {city} : {mo}/mois. Sers-la à {p} d'ici le {d}.", +"pie_gov.tab":"État", +"pie_gov.until":"Payé jusqu'au {d}", +"pie_gov.up_to":"jusqu'à {mo}/mois", +"pie_gov.warned":"encore un mauvais mois et elle est retirée", "pie_inc.dig_msg":"Une pelleteuse a trouvé la fibre de backhaul sous l'antenne-tarte de {city}. L'antenne va bien, mais son trafic ne va nulle part.", "pie_inc.dig_press":"Le service de presse dit : l'antenne prend une pause bien méritée loin du sol.", "pie_inc.food_fix":"Acheter un Space Roomba", @@ -3660,6 +3700,7 @@ "pie_traffic.via_dishes":"monte à {up}, descend à {down}", "pitcairn.uk_grant_mo":"Subvention britannique {mo}/mois", "pitcairn.uk_grant_mo_once_islanders":"Subvention britannique {mo}/mois une fois les insulaires en ligne", +"pitcairn.uk_sky_grant_mo":"Subvention britannique satellite {mo}/mois (la fibre touche {full})", "pni_all.additional_per_month":"Coût mensuel supplémentaire", "pni_all.all_at_port":"Peering avec tous les réseaux · {port}", "pni_all.delivery_and_traffic_charges":"Les délais de livraison varient selon le réseau. Des frais de peering liés au trafic s'appliquent aussi lorsque le réseau l'exige.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 91562bb..9ccf111 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -306,6 +306,10 @@ "banks.do_the_kehrwoche_keep_your_noc":"Fai la Kehrwoche: tieni il NOC libero da incidenti più vecchi di una settimana.", "banks.download_our_app_and_enable_all":"Scarica la nostra app e attiva tutte le notifiche.", "banks.every_pop_needs_a_backup_generator":"Ogni POP deve avere un generatore di backup. Il nostro risk team ha visto un film catastrofico.", +"banks.exim_blurb":"Lo Stato ti presta i soldi per comprare razzi nazionali. Si applicano clausole spaziali.", +"banks.exim_keep_a_dish_in":"Tieni una parabola-torta in {a}", +"banks.exim_launch_n_pies_by":"Lancia {n} torte entro il {d} ({f} finora)", +"banks.exim_launch_pies":"Lancia le torte che hai promesso", "banks.fill_in_form_t_17b_in":"Compila il modulo T-17b in triplice copia, ogni mese, per sempre.", "banks.give_our_ceo_s_nephew_a":"Dai un lavoro al nipote del nostro CEO. Gli servono {price}/mese e un posto auto.", "banks.instant_approval_instant_regret":"Approvazione istantanea. Pentimento istantaneo.", @@ -3508,6 +3512,42 @@ "pie_globe.switch_to_day_view":"Passa alla vista diurna", "pie_globe.switch_to_night_view":"Passa alla vista notturna", "pie_globe.your_pies_in_orbit":"Le tue torte in orbita, trascina per girare la Terra", +"pie_gov.ask":"Chiedi {mo}/mese", +"pie_gov.bid":"Fai un'offerta", +"pie_gov.closes":"offerte fino al {d}", +"pie_gov.cov_dish":"Tieni una parabola-torta in {a}", +"pie_gov.cov_launch":"Lancia {n} torte entro il {d}", +"pie_gov.due":"Serve al {p} entro il {d}", +"pie_gov.exim":"Ex-Im Pie Bank", +"pie_gov.exim_breach":"Se violi una clausola il tasso sale di {apr} punti, la scadenza si sposta e il paese che presta si arrabbia.", +"pie_gov.exim_none":"Nessuna offerta per ora. La banca presta alle aziende di razzi con una fabbrica.", +"pie_gov.exim_offer":"Ti presta {amt} al {apr}% per {n} mesi: {pay}/mese.", +"pie_gov.no_auction":"Nessuna asta aperta. Il fondo chiama quando un paese che raggiungono solo le tue torte può avere un sostegno.", +"pie_gov.open":"Apri", +"pie_gov.pitcairn":"Pitcairn", +"pie_gov.pitcairn_note":"Il Regno Unito paga {mo}/mese finché gli isolani sono ben serviti, e accetta il satellite per {sky}/mese.", +"pie_gov.rdf":"Rural Digital Pie Fund", +"pie_gov.rdf_note":"Aste al ribasso per i paesi che raggiunge solo l'orbita: vince la richiesta più bassa, pagata ogni mese per {y} anni. Tieni il paese servito al {p} in media ogni mese: due mesi di fila sotto e il sostegno viene revocato e il {c} del sostegno dell'ultimo anno va restituito.", +"pie_gov.rival_coop":"Cooperativa La Parabola", +"pie_gov.rival_hugsnet":"HugsNet", +"pie_gov.rival_viasad":"ViaSad", +"pie_gov.served":"{p} servito", +"pie_gov.t_auction":"Sostegno per {city}: fino a {mo}/mese per {y} anni. Offerte fino al {d}.", +"pie_gov.t_auction_title":"Asta del Rural Digital Pie Fund", +"pie_gov.t_bid":"Offerta per {city}: {mo}/mese. Risultato il {d}.", +"pie_gov.t_breach":"La Ex-Im Pie Bank stringe le condizioni: ora {apr}%, e {a} non è contento.", +"pie_gov.t_breach_spat":"Il suo governo ha delle domande.", +"pie_gov.t_done":"Il sostegno del fondo per {city} è finito: {amt} pagati in tutto.", +"pie_gov.t_exim":"La Ex-Im Pie Bank ti presterebbe {amt} quasi gratis, se tieni una parabola-torta in {a}.", +"pie_gov.t_exim_title":"Soldi pubblici per i razzi", +"pie_gov.t_lost":"{rival} ha vinto {city} chiedendo solo {mo}/mese.", +"pie_gov.t_revoked":"Sostegno per {city} revocato: {p} servito, il fondo vuole {need}. Si riprende {amt}.", +"pie_gov.t_warn":"Il fondo tiene d'occhio {city}: {p} servito il mese scorso, vuole {need}. Un altro mese così e il sostegno viene revocato.", +"pie_gov.t_won":"Hai vinto {city}: {mo}/mese. Servilo al {p} entro il {d}.", +"pie_gov.tab":"Stato", +"pie_gov.until":"Pagato fino al {d}", +"pie_gov.up_to":"fino a {mo}/mese", +"pie_gov.warned":"ancora un mese brutto ed è revocato", "pie_inc.dig_msg":"Una ruspa ha trovato la fibra di backhaul sotto la parabola-torta di {city}. La parabola sta bene, ma il suo traffico non va da nessuna parte.", "pie_inc.dig_press":"L'ufficio stampa dice: la parabola si prende una meritata pausa dal suolo.", "pie_inc.food_fix":"Compra uno Space Roomba", @@ -3660,6 +3700,7 @@ "pie_traffic.via_dishes":"su a {up}, giù a {down}", "pitcairn.uk_grant_mo":"Contributo UK {mo}/mese", "pitcairn.uk_grant_mo_once_islanders":"Contributo UK {mo}/mese quando gli isolani saranno online", +"pitcairn.uk_sky_grant_mo":"Contributo UK via satellite {mo}/mese (la fibra prende {full})", "pni_all.additional_per_month":"Costo mensile aggiuntivo", "pni_all.all_at_port":"Peering con tutte le reti · {port}", "pni_all.delivery_and_traffic_charges":"I tempi di consegna variano secondo la rete. Si applicano anche costi di peering basati sul traffico, dove previsti.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 04b8583..f346d51 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -306,6 +306,10 @@ "banks.do_the_kehrwoche_keep_your_noc":"Faça a Kehrwoche: mantenha seu NOC livre de incidentes com mais de uma semana.", "banks.download_our_app_and_enable_all":"Baixe nosso app e ative todas as notificações.", "banks.every_pop_needs_a_backup_generator":"Todo POP precisa de um gerador de backup. Nosso time de risco viu um filme-catástrofe.", +"banks.exim_blurb":"O Estado te empresta dinheiro para comprar foguetes nacionais. Cláusulas espaciais se aplicam.", +"banks.exim_keep_a_dish_in":"Manter uma antena-torta em {a}", +"banks.exim_launch_n_pies_by":"Lançar {n} tortas até {d} ({f} até agora)", +"banks.exim_launch_pies":"Lançar as tortas prometidas", "banks.fill_in_form_t_17b_in":"Preencha o formulário T-17b em três vias, todo mês, pra sempre.", "banks.give_our_ceo_s_nephew_a":"Dê um emprego ao sobrinho do nosso CEO. Ele precisa de {price}/mês e uma vaga na garagem.", "banks.instant_approval_instant_regret":"Aprovação instantânea. Arrependimento instantâneo.", @@ -3508,6 +3512,42 @@ "pie_globe.switch_to_day_view":"Mudar para a visão diurna", "pie_globe.switch_to_night_view":"Mudar para a visão noturna", "pie_globe.your_pies_in_orbit":"Suas tortas em órbita, arraste para girar a Terra", +"pie_gov.ask":"Pedir {mo}/mês", +"pie_gov.bid":"Dar lance", +"pie_gov.closes":"lances até {d}", +"pie_gov.cov_dish":"Manter uma antena-torta em {a}", +"pie_gov.cov_launch":"Lançar {n} tortas até {d}", +"pie_gov.due":"Precisa de {p} atendido até {d}", +"pie_gov.exim":"Ex-Im Pie Bank", +"pie_gov.exim_breach":"Quebre uma cláusula e a taxa sobe {apr} pontos, o prazo muda e o país credor fica bravo.", +"pie_gov.exim_none":"Nenhuma oferta agora. O banco empresta a empresas de foguetes com fábrica.", +"pie_gov.exim_offer":"Te empresta {amt} a {apr}% por {n} meses: {pay}/mês.", +"pie_gov.no_auction":"Nenhum leilão aberto. O fundo liga quando uma cidade que só suas tortas alcançam pode receber apoio.", +"pie_gov.open":"Abrir", +"pie_gov.pitcairn":"Pitcairn", +"pie_gov.pitcairn_note":"O Reino Unido paga {mo}/mês enquanto os ilhéus estiverem bem atendidos, e aceita satélite por {sky}/mês.", +"pie_gov.rdf":"Rural Digital Pie Fund", +"pie_gov.rdf_note":"Leilões reversos para cidades que só a órbita alcança: o menor pedido vence e recebe todo mês por {y} anos. Mantenha a cidade {p} atendida, na média de cada mês: dois meses seguidos abaixo e o apoio é revogado e {c} do apoio do último ano é devolvido.", +"pie_gov.rival_coop":"Cooperativa Parabólica", +"pie_gov.rival_hugsnet":"HugsNet", +"pie_gov.rival_viasad":"ViaSad", +"pie_gov.served":"{p} atendido", +"pie_gov.t_auction":"Apoio para {city}: até {mo}/mês por {y} anos. Lances até {d}.", +"pie_gov.t_auction_title":"Leilão do Rural Digital Pie Fund", +"pie_gov.t_bid":"Lance dado por {city}: {mo}/mês. Resultado em {d}.", +"pie_gov.t_breach":"O Ex-Im Pie Bank aperta suas condições: {apr}% agora, e {a} não achou graça.", +"pie_gov.t_breach_spat":"O governo de lá tem perguntas.", +"pie_gov.t_done":"O apoio do fundo para {city} acabou: {amt} pagos no total.", +"pie_gov.t_exim":"O Ex-Im Pie Bank te emprestaria {amt} quase de graça, se você mantiver uma antena-torta em {a}.", +"pie_gov.t_exim_title":"Dinheiro público para foguetes", +"pie_gov.t_lost":"{rival} ganhou {city} pedindo só {mo}/mês.", +"pie_gov.t_revoked":"Apoio para {city} revogado: {p} atendido, o fundo quer {need}. Ele pega de volta {amt}.", +"pie_gov.t_warn":"O fundo está de olho em {city}: {p} atendido no mês passado, ele quer {need}. Mais um mês assim e o apoio é revogado.", +"pie_gov.t_won":"Você ganhou {city}: {mo}/mês. Deixe {p} atendido até {d}.", +"pie_gov.tab":"Governo", +"pie_gov.until":"Pago até {d}", +"pie_gov.up_to":"até {mo}/mês", +"pie_gov.warned":"mais um mês ruim e é revogado", "pie_inc.dig_msg":"Uma retroescavadeira encontrou a fibra de backhaul debaixo da antena-torta em {city}. A antena está bem, mas o tráfego não tem para onde ir.", "pie_inc.dig_press":"A assessoria de imprensa diz: a antena está tirando uma pausa merecida do chão.", "pie_inc.food_fix":"Comprar um Space Roomba", @@ -3660,6 +3700,7 @@ "pie_traffic.via_dishes":"sobe em {up}, desce em {down}", "pitcairn.uk_grant_mo":"Subsídio do Reino Unido {mo}/mês", "pitcairn.uk_grant_mo_once_islanders":"Subsídio do Reino Unido {mo}/mês quando os ilhéus estiverem online", +"pitcairn.uk_sky_grant_mo":"Subsídio britânico por satélite {mo}/mês (a fibra recebe {full})", "pni_all.additional_per_month":"Custo mensal adicional", "pni_all.all_at_port":"Peering com todas as redes · {port}", "pni_all.delivery_and_traffic_charges":"Os prazos de entrega variam conforme a rede. Também se aplicam custos de peering baseados no tráfego, quando exigidos.", diff --git a/src/game/60-features/10-banks.js b/src/game/60-features/10-banks.js index 29d205b..7795eb3 100644 --- a/src/game/60-features/10-banks.js +++ b/src/game/60-features/10-banks.js @@ -18,6 +18,8 @@ const BANKS={ ppp:{name:'Peer Pressure Partners',col:'#00897B',min:'B',amt:[2,5],term:[24,36],covs:['nocache'],model:'transit',blurb:tr('banks.you_repay_with_30_of_your')}, astro:{name:'Horoscope Holdings',col:'#5E35B1',min:'CCC',apr:[.02,.3],amt:[1,4],term:[12,24],covs:['friday','nobude'],model:'astro',blurb:tr('banks.your_rate_is_set_by_the')}, pizza:{name:'Papa Pizza Capital',col:'#FF7043',min:'BB',apr:[.03,.05],amt:[1,3],term:[12,24],covs:['pizza'],blurb:tr('banks.the_cheapest_money_in_town_there')}, + // The rocket company's state lender: never calls on its own, offered in Pie Control (99-pie-subsidies.js), sized there. + exim:{name:'Ex-Im Pie Bank',col:'#1565C0',min:'C',apr:[.015,.025],amt:[0,0],term:[60,60],covs:['pielaunch','piedish'],pie:true,blurb:tr('banks.exim_blurb')}, shark:{name:'Loan Shark Telecom Finance',col:'#37474F',min:'C',apr:[.6,.9],amt:[1,2],term:[4,8],covs:[],shark:true,blurb:tr('banks.always_open_ask_no_questions_do')}, }; const RATINGS=['C','CCC','B','BB','BBB','A','AA','AAA']; @@ -49,10 +51,13 @@ const COVS={ nephew:{l:tr('banks.give_our_ceo_s_nephew_a'),fee:3000,ok:()=>true}, yacht:{l:tr('banks.our_chairman_needs_a_yacht_for'),fee:8000,ok:()=>true}, pizza:{l:tr('banks.pizza_for_the_whole_noc_after'),each:400,ok:()=>true}, + // The Ex-Im Pie Bank's space covenants: their numbers live on the loan (l.pie). + pielaunch:{l:l=>l&&l.pie?tr('banks.exim_launch_n_pies_by',{n:l.pie.n,d:dateStr(l.pie.by),f:Math.min(l.pie.flown,l.pie.n)}):tr('banks.exim_launch_pies'),ok:l=>pieEximLaunchOk(l)}, + piedish:{l:l=>tr('banks.exim_keep_a_dish_in',{a:l&&l.pie?pieLicCountry(l.pie.cc):'?'}),ok:l=>pieEximDishOk(l)}, blitz:{l:tr('banks.open_a_new_pop_at_least'),ok:l=>S.day-Math.max(l.start,...Object.values(S.pops).map(p=>p.day||0))<=90}, }; // Conditions read with their price filled in; some cost money every month, one costs money per incident. -const covLabel=c=>COVS[c]?COVS[c].l.replace('{price}',fmt$(COVS[c].fee||COVS[c].each||0)):c; +const covLabel=(c,l)=>{const C=COVS[c];return !C?c:typeof C.l==='function'?C.l(l):C.l.replace('{price}',fmt$(C.fee||C.each||0));}; const loanFees=l=>(l.covs||[]).reduce((a,c)=>a+((COVS[c]&&COVS[c].fee)||0),0); // Good terms are for good credit: every notch below AAA adds to the rate. const RATE_PREM={AAA:0,AA:.005,A:.01,BBB:.02,BB:.04,B:.07,CCC:.12,C:.2}; @@ -67,7 +72,7 @@ function rating(){if(!S)return 'BB';const rev=R.revMo||0,pay=(R.cost&&R.cost.loa const rIdx=r=>RATINGS.indexOf(r); function annuity(P,apr,n){const r=apr/12;return r?P*r/(1-Math.pow(1+r,-n)):P/n;} function spawnLoanOffer(emergency){ - const rt=rating(),keys=Object.keys(BANKS).filter(k=>rIdx(rt)>=rIdx(BANKS[k].min)&&!S.loanOffers.some(o=>o.bank===k)&&!(BANKS[k].equity&&S.loans.some(l=>l.bank===k))); + const rt=rating(),keys=Object.keys(BANKS).filter(k=>rIdx(rt)>=rIdx(BANKS[k].min)&&!S.loanOffers.some(o=>o.bank===k)&&!(BANKS[k].equity&&S.loans.some(l=>l.bank===k))&&!BANKS[k].pie); let pool=emergency?keys.filter(k=>['shark','gov','crypto','vult','rev','spk','astro','balloon'].includes(k)):keys.filter(k=>k!=='shark');if(!pool.length)pool=keys;if(!pool.length)return; const k=pick(pool),B=BANKS[k],base=Math.max(60000,R.revMo||0),ra=(a)=>a[0]+Math.random()*(a[1]-a[0]); const amount=niceAmt(base*ra(B.amt)*(emergency?0.6:1)),o={id:uid(),bank:k,amount,exp:S.day+(emergency?10:25),covs:B.covs.slice()}; @@ -105,10 +110,10 @@ function loanTick(d){ const broken=l.covs.filter(c=>COVS[c]&&!COVS[c].ok(l)); if(d-l.start<15||!broken.length){l.breach=0;continue;} l.breach=(l.breach||0)+1; - if(l.breach===1)toast(tr('banks.bank_is_unhappy_you_broke_a',{bank:esc(B.name),cond:esc(covLabel(broken[0]))}),'bad',[{l:tr('common.open_bank'),act:'bank',args:{}}]); + if(l.breach===1)toast(tr('banks.bank_is_unhappy_you_broke_a',{bank:esc(B.name),cond:esc(covLabel(broken[0],l))}),'bad',[{l:tr('common.open_bank'),act:'bank',args:{}}]); if(l.breach===10||(l.breach>10&&(l.breach-10)%30===0)){ if(B.equity){l.share=+(l.share+0.02).toFixed(3);toast(tr('banks.bank_are_circling_they_now_take',{bank:esc(B.name),pct:pct(l.share)}),'bad');} - else{const fee=Math.round(l.bal*0.05);l.bal+=fee;l.pay=Math.round(annuity(l.bal,l.apr,Math.max(1,l.left)));S.loanStrikes=(S.loanStrikes||0)+1;toast(tr('banks.penalty_from_bank_fee_added_to',{bank:esc(B.name),fee:fmt$(fee),pay:fmt$(l.pay)}),'bad');} + else{const fee=Math.round(l.bal*0.05);l.bal+=fee;l.pay=Math.round(annuity(l.bal,l.apr,Math.max(1,l.left)));S.loanStrikes=(S.loanStrikes||0)+1;toast(tr('banks.penalty_from_bank_fee_added_to',{bank:esc(B.name),fee:fmt$(fee),pay:fmt$(l.pay)}),'bad');if(B.pie)pieEximBreach(l,broken);} sfx('err');}} // monthly statement: payments already leave your cash daily as part of costs for(const l of S.loans.slice()){const B0=BANKS[l.bank];if(B0.equity||!monthiversary(l.start,d))continue; diff --git a/src/game/60-features/85-pitcairn.js b/src/game/60-features/85-pitcairn.js index 1497980..c220a47 100644 --- a/src/game/60-features/85-pitcairn.js +++ b/src/game/60-features/85-pitcairn.js @@ -2,4 +2,11 @@ islanders are online through you: a POP with broadband, up and nearly fully served. */ const GRANT_MO=300000; const grantOn=r=>!!(S&&S.pops.pcn&&S.pops.pcn.bb&&!(S.pops.pcn.down>S.day)&&sfOf(r,'pcn')>=0.9); -function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R);return `${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}`;} +/* Satellite tier: Pitcairn online through your pies (its POP on backhaul, or home terminals there) is good enough for the + UK at a lower bar, orbit's latency forgiven (sfOf() counts it, so the fiber grant never comes), for less money. */ +const GRANT_SKY_MO=120000,GRANT_SKY_Q=0.9; +function grantSky(r){if(!S||!S.pie||!r||!r.pie||grantOn(r))return false;const p=S.pops.pcn; + if(p&&p.bb&&!(p.down>S.day)&&r.pie.bh.some(b=>b.city==='pcn'&&b.g>0)){const d=r.cityDem.pcn||0;if(d>1e-6&&(r.citySrv.pcn||0)/d>=GRANT_SKY_Q)return true;} + return S.biz.some(b=>b.city==='pcn'&&b.type==='pizza'&&(r.pie.sf[b.id]||0)>=GRANT_SKY_Q);} +function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R),sky=!on&&grantSky(R); + return `${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):sky?tr('pitcairn.uk_sky_grant_mo',{mo:fmt$(GRANT_SKY_MO),full:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}`;} diff --git a/src/game/60-features/99-pie-in-the-sky.js b/src/game/60-features/99-pie-in-the-sky.js index 96f8aa3..b89b2ef 100644 --- a/src/game/60-features/99-pie-in-the-sky.js +++ b/src/game/60-features/99-pie-in-the-sky.js @@ -18,7 +18,7 @@ - book.earned: revenue from orbit, for the customers that come with routing. */ function pieBlank(day){const crusts={};for(const id in CRUSTS)crusts[id]={cohorts:[],queued:0}; return {born:day,co:null,fac:false,stock:0,rd:{reuse:false,heavy:false,heavyTests:0},pads:[],crusts,dishes:[],lic:{},q:[], - founder:{posts:[],promises:0,broken:0,due:[]},book:{spent:0,earned:0,wouldHave:0},spat:{},safe:false};} + founder:{posts:[],promises:0,broken:0,due:[]},book:{spent:0,earned:0,wouldHave:0},spat:{},safe:false,gov:pieGovBlank()};} function pieInit(){if(!S.pie)S.pie=pieBlank(S.day);return S.pie;} // The unlock: only on the Tier 1 transition of a save of this version, and only in a normal game. function pieUnlock(){if(S.pie||!(S.pieV>=1)||S.mode!=='normal'||S.scn)return;pieInit();track('pie_unlock'); @@ -107,7 +107,7 @@ function pieDay(d){const P=S.pie;if(!P)return; function pieTier(){const P=S.pie,t1=pieT1();if(P.t1&&!t1&&P.q.length&&!S.stats.pieTour){S.stats.pieTour=1;pieFounder(N_('pie.fp_tour'));}P.t1=t1;} /* The save gate for S.pie: everything clamped, unknown crusts, rockets and cities dropped, pads and dishes only where a POP is. A save without pieV (older versions) never unlocks it; puzzles, scenarios and the Architect never have it. */ -function pieSanitize(s){s.pieV=int(s.pieV,0,1,0);const p=s.pie,ob=x=>x&&typeof x==='object'&&!Array.isArray(x); +function pieSanitize(s){s.pieV=int(s.pieV,0,1,0);pieEximFix(s);const p=s.pie,ob=x=>x&&typeof x==='object'&&!Array.isArray(x); if(!ob(p)||(s.pieV<1&&s.mode!=='sandbox')||s.scn||s.mode==='puzzle'){s.pie=null;return;} const o=pieBlank(int(p.born,0,s.day,s.day)),day=s.day,n=(v,hi)=>int(v,0,hi,0),m=(v,hi)=>clamp(num(v,0),0,hi); if(ob(p.co)){const nm=p.co.name;o.co={name:typeof nm==='string'&&nm.trim()?(PIE_NAMES.includes(nm)?nm:nm.replace(/\s+/g,' ').trim().slice(0,40)):PIE_NAMES[0]};} @@ -132,5 +132,6 @@ function pieSanitize(s){s.pieV=int(s.pieV,0,1,0);const p=s.pie,ob=x=>x&&typeof x o.founder.due=(Array.isArray(F.due)?F.due:[]).map(v=>int(v,0,day+720,day)).sort((a,b)=>a-b).slice(-8);} if(ob(p.book))for(const k of ['spent','earned','wouldHave'])o.book[k]=m(p.book[k],1e15); if(ob(p.spat))for(const k of Object.keys(p.spat)){const D=PIE_SPATS[k];if(!D||!ob(p.spat[k]))continue;const v=D.fix?D.fix(p.spat[k],s):null;if(v)o.spat[k]=v;} + o.gov=pieGovFix(p.gov,s); s.pie=o;} const sid0=v=>typeof v==='string'&&v&&v.length<=40?v:uid(); diff --git a/src/game/60-features/99-pie-subsidies.js b/src/game/60-features/99-pie-subsidies.js new file mode 100644 index 0000000..251a579 --- /dev/null +++ b/src/game/60-features/99-pie-subsidies.js @@ -0,0 +1,117 @@ +/* ---------- Pie in the Sky: government money (docs/plans/pie-in-the-sky.md) ---------- + Two state programmes for a rocket company, kept in S.pie.gov (pieBlank(), repaired by pieGovFix()): + - The Rural Digital Pie Fund: reverse auctions for support of a remote town that only orbit reaches (a cut-off POP on + backhaul, or a town of your terminal customers with no POP of yours). The lowest ask wins; a rival bids too. A win + pays a monthly subsidy (V.gov in compute()) for PIE_RDF_TERM days, while the town's service, averaged over each + month, stays at PIE_RDF_NEED from the deadline on. A month below it is a warning; two in a row revoke the award, and + PIE_RDF_CLAW of the last year's support goes back. + - The Ex-Im Pie Bank: a cheap state loan sized to the constellation (a BANKS entry, so it bills and shows like any + loan), with space covenants: launch n pies by a day, keep a pie dish in the lending country. A breach is a loan + breach (the bank's penalty), plus tighter terms (PIE_EXIM_PEN on the rate, the launch target rescheduled) and, with + chaos on (rule O5), a geopolitical spat in the lending country. + Pitcairn's satellite tier of the UK grant is in 85-pitcairn.js. Subsidies count in the orbit's books (book.earned). */ +const PIE_RDF_MO=5e6,PIE_RDF_P=30,PIE_RDF_TERM=1800,PIE_RDF_DUE=90,PIE_RDF_NEED=0.7,PIE_RDF_CLAW=0.5,PIE_RDF_MAX=6, + PIE_RDF_DAYS=20,PIE_RDF_RATE=1/45,PIE_RDF_FAR=60,PIE_RDF_BIDS=[0.9,0.7,0.5],PIE_RDF_RIV=0.4, + PIE_EXIM_SHARE=0.5,PIE_EXIM_MIN=250e6,PIE_EXIM_CAPF=0.2,PIE_EXIM_APR=0.015,PIE_EXIM_TERM=60,PIE_EXIM_BY=360,PIE_EXIM_PEN=0.03, + PIE_EXIM_RESCHED=180,PIE_EXIM_EVERY=90; +// Rival bidders: the old satellite crowd and the local co-op. +const PIE_RIVALS=[N_('pie_gov.rival_viasad'),N_('pie_gov.rival_hugsnet'),N_('pie_gov.rival_coop')]; +const pieGovBlank=()=>({auc:[],aw:[],ex:null,told:0}); +// A town's service today, from the last compute: a POP's share of its demand served (orbit's latency is accepted: the +// fund pays for coverage), or the share its terminal customers get. +function pieRdfSrv(c){if(!R||!R.pie)return 0;if(S.pops[c]){const d=R.cityDem[c]||0;return d>1e-6?clamp((R.citySrv[c]||0)/d,0,1):0;} + let w=0,g=0;for(const b of S.biz)if(b.city===c&&BIZ_T[b.type].orbit){w+=b.bw;g+=b.bw*Math.min(1,R.pie.sf[b.id]||0);}return w>0?g/w:0;} +// Towns the fund will auction: cut-off POPs with home broadband on backhaul, and small towns with no POP of yours where +// your terminals are, that are not up for auction or awarded already. +function pieRdfCands(){if(!R||!R.pie||!R.pie.hubs.length)return [];const G=S.pie.gov,busy=new Set([...G.auc,...G.aw].map(x=>x.city)),o=new Set(); + for(const b of R.pie.bh)if(b.land&&S.pops[b.city]&&S.pops[b.city].bb)o.add(b.city); + for(const b of S.biz)if(BIZ_T[b.type].orbit&&!S.pops[b.city]&&CITY[b.city].P<=PIE_RDF_FAR)o.add(b.city); + return [...o].filter(c=>!busy.has(c)&&!CITY[c].cn).sort();} +// The reserve grows with the town, up to a small one's worth: the fund is for the last mile, not for cities. +const pieRdfAsk=c=>Math.round(PIE_RDF_MO*(1+Math.min(CITY[c].P,PIE_RDF_FAR)/PIE_RDF_P)/1e5)*1e5; +function pieRdfOpen(c){const G=S.pie.gov,a={id:uid(),city:c,ask:pieRdfAsk(c),close:S.day+PIE_RDF_DAYS,riv:+(PIE_RDF_RIV+(1-PIE_RDF_RIV)*Math.random()).toFixed(3),rv:Math.floor(Math.random()*PIE_RIVALS.length)%PIE_RIVALS.length,bid:0}; + G.auc.push(a);toast(`🏛️ ${tr('pie_gov.t_auction_title')}
${tr('pie_gov.t_auction',{city:esc(CITY[c].name),mo:fmt$(a.ask),y:PIE_RDF_TERM/360,d:dateStr(a.close)})}`,'goal',[{l:tr('pie_gov.bid'),act:'pieGovOpen',args:{}}]);} +// Bids close: the lower ask wins. Silent when you did not bid. +function pieRdfClose(a){const G=S.pie.gov,c=esc(CITY[a.city].name);if(!a.bid)return; + if(a.bid<=a.riv&&G.aw.lengthx!==w); + if(!pieSand())S.cash-=claw;P.book.earned=Math.max(0,P.book.earned-claw);S.stats.pieRdfLost=(S.stats.pieRdfLost||0)+1; + toast(tr('pie_gov.t_revoked',{city:esc(CITY[w.city].name),p:pct(avg),need:pct(PIE_RDF_NEED),amt:fmt$(claw)}),'bad',[{l:tr('pie_gov.open'),act:'pieGovOpen',args:{}}]);sfx('err');} +// What the fund pays this month: every award in force (compute()). +function pieGovMo(){const G=S.pie&&S.pie.gov;if(!G)return 0;let v=0;for(const w of G.aw)v+=w.mo;return v;} +/* ---- The Ex-Im Pie Bank ---- */ +// What a pie in orbit is worth to a lender: the pie, its laser and its seat on the cheapest rocket. +const pieEximUnit=()=>piePrice(PIE_PIE+PIE_LAS)+piePrice(ROCKETS.falcon.cost)/ROCKETS.falcon.pies; +// The most it lends: a share of the cheapest full Shortcrust (rule O7 counts it). +const pieEximCap=()=>Math.round(pieFullCost('short')*PIE_EXIM_CAPF/50e6)*50e6; +// Sized to the constellation: half the value of the pies flying and booked, between PIE_EXIM_MIN and the cap. +function pieEximAmt(){const P=S.pie;let n=pieLiveAll();for(const id in CRUSTS)n+=P.crusts[id].queued;return clamp(Math.round(n*pieEximUnit()*PIE_EXIM_SHARE/50e6)*50e6,PIE_EXIM_MIN,pieEximCap());} +const pieEximLoan=()=>(S.loans||[]).find(l=>l.bank==='exim')||null; +// The covenants (COVS.pielaunch / COVS.piedish, 10-banks.js). +function pieEximLaunchOk(l){const q=l&&l.pie;return !q||S.day=q.n;} +function pieEximDishOk(l){const q=l&&l.pie;return !q||!!S.pie&&S.pie.dishes.some(x=>S.pops[x.city]&&CITY[x.city].cc===q.cc);} +// A fresh offer every PIE_EXIM_EVERY days, from a country you have a POP in, while you have a factory and no Ex-Im loan. +function pieEximOffer(d){const P=S.pie,G=P.gov;if(!P.fac||pieEximLoan()||!pieCanBuild()){if(G.ex&&pieEximLoan())G.ex=null;return;}if(G.ex&&G.ex.exp>d)return; + const ccs=piePopCc();if(!ccs.length)return;const amt=pieEximAmt(); + G.ex={cc:pick(ccs),amt,apr:+(PIE_EXIM_APR+0.01*Math.random()).toFixed(3),term:PIE_EXIM_TERM,n:Math.ceil(amt/pieEximUnit()/20)*20,exp:d+PIE_EXIM_EVERY}; + if(!G.told){G.told=1;toast(`🏦 ${tr('pie_gov.t_exim_title')}
${tr('pie_gov.t_exim',{amt:fmt$(amt),a:esc(pieLicCountry(G.ex.cc))})}`,'goal',[{l:tr('pie_gov.open'),act:'pieGovOpen',args:{}}]);}} +// Taking it: a loan like any other, plus its space covenants. +function pieEximTake(){const P=S.pie,o=P.gov.ex;if(!o||pieEximLoan())return false;const pay=Math.round(annuity(o.amt,o.apr,o.term)); + S.cash+=o.amt;S.stats.loans=(S.stats.loans||0)+1; + S.loans.push({id:uid(),bank:'exim',start:S.day,amount:o.amt,got:o.amt,bal:o.amt,apr:o.apr,apr0:o.apr,pay,left:o.term,term:o.term,share:0,covs:['pielaunch','piedish'],base:{sub:S.links.filter(x=>x.sub).length}, + pie:{cc:o.cc,n:o.n,by:S.day+PIE_EXIM_BY,flown:0,br:0}}); + P.gov.ex=null;track('loan_taken');return true;} +// A breach (loanTick(), after the bank's own penalty): tighter terms, the launch target rescheduled, and a spat. +function pieEximBreach(l,broken){const q=l.pie;if(!q)return;q.br=(q.br||0)+1;l.apr=+(l.apr+PIE_EXIM_PEN).toFixed(3);l.pay=Math.round(annuity(l.bal,l.apr,Math.max(1,l.left))); + if(broken.includes('pielaunch'))q.by=S.day+PIE_EXIM_RESCHED; + let sp='';if(S.pie&&pieChaos()){const ids=broken.includes('piedish')?['home','lic']:['lic','home'];for(const id of ids)if(!S.pie.spat[id]&&pieSpatStart(id,q.cc)){sp=id;break;}} + toast(tr('pie_gov.t_breach',{a:esc(pieLicCountry(q.cc)),apr:(l.apr*100).toFixed(1)})+(sp?' '+tr('pie_gov.t_breach_spat'):''),'bad');} +/* ---- The day ---- */ +function pieGovDay(d){const P=S.pie;if(!P.co)return;const G=P.gov; + if(G.auc.length)for(const a of G.auc.slice())if(d>=a.close){G.auc=G.auc.filter(x=>x!==a);pieRdfClose(a);} + for(const w of G.aw.slice()){if(w.start===d)continue;if(d>=w.end){G.aw=G.aw.filter(x=>x!==w);toast(tr('pie_gov.t_done',{city:esc(CITY[w.city].name),amt:fmt$(w.paid)}),'good');continue;} + w.paid+=w.mo/30;w.s+=pieRdfSrv(w.city);w.n++; + if(w.n>=30){const avg=w.s/w.n;w.s=0;w.n=0;if(d=PIE_RDF_NEED){w.k=0;continue;} + if(w.k){pieRdfRevoke(w,avg);continue;}w.k=1;toast(tr('pie_gov.t_warn',{city:esc(CITY[w.city].name),p:pct(avg),need:pct(PIE_RDF_NEED)}),'bad',[{l:tr('pie_gov.open'),act:'pieGovOpen',args:{}}]);}} + if(!G.auc.length&&G.aw.length0)P.book.earned+=v/30;}} +PIE_ON.day.push(pieGovDay); +// Pies launched count towards the Ex-Im target. +PIE_ON.launch.push((L,ok)=>{const l=ok&&!L.test&&pieEximLoan();if(l&&l.pie)l.pie.flown+=L.n;}); +/* ---- The save gate ---- */ +function pieGovFix(g,s){const o=pieGovBlank(),day=s.day,ob=x=>x&&typeof x==='object'&&!Array.isArray(x);if(!ob(g))return o; + const ccs=new Set(CITIES.map(c=>c.cc)),seen=new Set(),one=x=>isCity(x.city)&&!seen.has(x.city)&&seen.add(x.city),mx=PIE_RDF_MO*20; + o.auc=(Array.isArray(g.auc)?g.auc:[]).filter(a=>ob(a)&&one(a)).slice(0,1).map(a=>({id:sid0(a.id),city:a.city,ask:clamp(num(a.ask,0),0,mx),close:int(a.close,0,day+PIE_RDF_DAYS,day), + riv:clamp(num(a.riv,1),PIE_RDF_RIV,1),rv:int(a.rv,0,PIE_RIVALS.length-1,0),bid:PIE_RDF_BIDS.includes(a.bid)?a.bid:0})); + o.aw=(Array.isArray(g.aw)?g.aw:[]).filter(w=>ob(w)&&one(w)).slice(0,PIE_RDF_MAX).map(w=>{const st=int(w.start,0,day,day); + return {id:sid0(w.id),city:w.city,mo:clamp(num(w.mo,0),0,mx),start:st,due:int(w.due,st,st+PIE_RDF_DUE,st+PIE_RDF_DUE),end:int(w.end,st,st+PIE_RDF_TERM,st+PIE_RDF_TERM), + s:clamp(num(w.s,0),0,30),n:int(w.n,0,29,0),k:w.k?1:0,paid:clamp(num(w.paid,0),0,mx*PIE_RDF_TERM/30)};}).map(w=>(w.s=Math.min(w.s,w.n),w)); + if(ob(g.ex)&&ccs.has(g.ex.cc)){const x=g.ex;o.ex={cc:x.cc,amt:clamp(num(x.amt,PIE_EXIM_MIN),0,pieEximCap()),apr:clamp(num(x.apr,PIE_EXIM_APR),0,0.2),term:PIE_EXIM_TERM,n:int(x.n,0,1e5,0),exp:int(x.exp,0,day+PIE_EXIM_EVERY,day)};} + o.told=g.told?1:0;return o;} +// Ex-Im loans live in S.loans (sanitized there); their covenants' numbers are repaired here, or reset when unreadable. +function pieEximFix(s){const ccs=new Set(CITIES.map(c=>c.cc)),home=isCity(s.home)?CITY[s.home].cc:CITIES[0].cc; + for(const l of s.loans||[]){if(l.bank!=='exim')continue;const q=l.pie&&typeof l.pie==='object'?l.pie:{}; + l.pie={cc:ccs.has(q.cc)?q.cc:home,n:int(q.n,0,1e5,0),by:int(q.by,0,s.day+PIE_EXIM_BY,0),flown:int(q.flown,0,1e6,0),br:int(q.br,0,1e4,0)};l.covs=['pielaunch','piedish'];}} +/* ---- Pie Control: the Gov tab ---- */ +function pieGovHtml(){const P=S.pie,G=P.gov,can=pieCanBuild();let h=`
🏛️ ${tr('pie_gov.rdf')}

${tr('pie_gov.rdf_note',{y:PIE_RDF_TERM/360,p:pct(PIE_RDF_NEED),c:pct(PIE_RDF_CLAW)})}

`; + for(const a of G.auc)h+=`
${esc(CITY[a.city].name)} · ${tr('pie_gov.up_to',{mo:fmt$(a.ask)})}${tr('pie_gov.closes',{d:dateStr(a.close)})}
+
${PIE_RDF_BIDS.map(f=>btn(tr('pie_gov.ask',{mo:fmt$(Math.round(a.ask*f))}),'pieBid',{id:a.id,f},a.bid===f?'pink sm':'ghost sm',!can)).join('')}
`; + if(!G.auc.length)h+=`

${tr('pie_gov.no_auction')}

`; + for(const w of G.aw){const s=pieRdfSrv(w.city),ok=s>=PIE_RDF_NEED; + h+=`
${esc(CITY[w.city].name)} · ${tr('common.price_mo',{price:fmt$(w.mo)})}${tr('pie_gov.served',{p:pct(s)})}
+
${S.day'+tr('pie_gov.warned')+'':''}
`;} + h+=`
🇵🇳 ${tr('pie_gov.pitcairn')}

${tr('pie_gov.pitcairn_note',{mo:fmt$(GRANT_MO),sky:fmt$(GRANT_SKY_MO)})}

${grantFact('pcn')}
`; + const l=pieEximLoan(),o=G.ex;h+=`
🏦 ${tr('pie_gov.exim')}
`; + if(l){const q=l.pie;h+=`
${tr('common.still_owed')}${fmt$(l.bal)}
${loanLine(l)}
+
${pieEximLaunchOk(l)?'✓':'✗'} ${esc(covLabel('pielaunch',l))}
+
${pieEximDishOk(l)?'✓':'✗'} ${esc(covLabel('piedish',l))}
`;} + else if(o){const pay=Math.round(annuity(o.amt,o.apr,o.term));h+=`

${tr('pie_gov.exim_offer',{amt:fmt$(o.amt),apr:(o.apr*100).toFixed(1),n:o.term,pay:fmt$(pay)})}

+
• ${tr('pie_gov.cov_launch',{n:o.n,d:dateStr(S.day+PIE_EXIM_BY)})}
• ${tr('pie_gov.cov_dish',{a:esc(pieLicCountry(o.cc))})}
+

${tr('pie_gov.exim_breach',{apr:(PIE_EXIM_PEN*100).toFixed(0)})}

${btn(tr('bank.take_the_money'),'pieExim',{},'pink sm',!can)}
`;} + else h+=`

${tr('pie_gov.exim_none')}

`; + return h+'
';} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index c8735d6..cc9ce0c 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -370,12 +370,14 @@ function computeMoney(R2,PX=null){ C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.model==='transit'?Math.round((C.transit||0)*(l.cut||0.3)):l.pay)+loanFees(l),0); C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.ops&&S.ops.intern?INTERN_MO:0)+salesMo(); if(S.pie&&S.mode!=='sandbox')C.pie=pieMo(); - V.eyeballs=0;V.business=0;V.ix=0;V.grant=grantOn(R2)?GRANT_MO:0; + V.eyeballs=0;V.business=0;V.ix=0; C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c)*(R2.bbF[c]??1),v=R2.cityEye[c]*sf*EYE_RATE*arpuOf(c);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}} const ids=linkIds();for(const b of S.biz){if(capPend(b)||BIZ_T[b.type].orbit)continue;const sf=BIZ_T[b.type].fiber?(fiberOk(b,ids)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city)*(R2.tgtF[b.id]??1);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);} for(const c in S.myIx)V.ix+=S.myIx[c].members.length*MYIX_FEE; if(PX)pieMoney(PX,R2,V); + // The UK grant for Pitcairn, its satellite tier once orbit is known; the Rural Digital Pie Fund (99-pie-subsidies.js). + {const on=grantOn(R2),sky=!on&&!!PX&&grantSky(R2);V.grant=on?GRANT_MO:sky?GRANT_SKY_MO:0;V.gov=PX?pieGovMo():0;if(PX)R2.pie.gov={rdf:V.gov,sky:sky?GRANT_SKY_MO:0};} C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix+(V.orbit||0)); R2.costMo=Object.values(C).reduce((a,b)=>a+b,0); - R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.orbit||0); + R2.revMo=V.eyeballs+V.business+V.ix+V.grant+V.gov+(V.orbit||0); } diff --git a/src/game/85-incidents/65-pie-spats.js b/src/game/85-incidents/65-pie-spats.js index 4392eec..a4d0cce 100644 --- a/src/game/85-incidents/65-pie-spats.js +++ b/src/game/85-incidents/65-pie-spats.js @@ -102,11 +102,11 @@ function pieSpatFix(id,o,s){const D=PIE_SPAT_DEF[id],A=pieCcAll(),day=s.day,cc=v // The day: an unanswered spat decides itself on its deadline. function pieSpatTick(id,o,d){const D=PIE_SPAT_DEF[id];if(o.st==='ask'&&d>=o.ask){pieSpatChoose(id,D.def,true);return;}if(D.day)D.day(o,d);} for(const id of PIE_SPAT_KEYS)PIE_SPATS[id]={fix:(o,s)=>pieSpatFix(id,o,s),day:(o,d)=>pieSpatTick(id,o,d),end:o=>{const D=PIE_SPAT_DEF[id];if(D.end)D.end(o);pieRelease(o);}}; -// Starts one (id forces which, for tests and the astronomers); true when it did. -function pieSpatStart(id){const P=S.pie;if(!P||!P.co)return false; +// Starts one (id forces which, for tests, the astronomers and the Ex-Im Pie Bank; cc which country); true when it did. +function pieSpatStart(id,cc){const P=S.pie;if(!P||!P.co)return false; if(!id){const ok=PIE_SPAT_KEYS.filter(k=>k!=='astro'&&!P.spat[k]&&PIE_SPAT_DEF[k].can().length);if(!ok.length)return false;id=pick(ok);} const D=PIE_SPAT_DEF[id];if(!D||P.spat[id])return false;const cs=D.can();if(!cs.length)return false; - const o={st:'ask',ask:S.day+PIE_SPAT_ASK,c:-1};D.start(o,pick(cs));if(!o.until)o.until=o.ask+1;P.spat[id]=o; + if(cc&&!cs.includes(cc))return false;const o={st:'ask',ask:S.day+PIE_SPAT_ASK,c:-1};D.start(o,cc||pick(cs));if(!o.until)o.until=o.ask+1;P.spat[id]=o; S.stats.incidents++;S.stats.pieSpat=(S.stats.pieSpat||0)+1;pieFounder(N_('pie.fp_spat')); const t=D.txt(o);toast(`🌍 ${t.t}
${t.b}`,'bad',[{l:tr('pie_spat.decide'),act:'pieSpatOpen',args:{id}}]);sfx('alert');return true;} // The answer: what it costs (sandbox keeps count), what happens, and the press office's line. diff --git a/src/game/90-actions/97-pie.js b/src/game/90-actions/97-pie.js index 5b6e0d8..9805635 100644 --- a/src/game/90-actions/97-pie.js +++ b/src/game/90-actions/97-pie.js @@ -28,6 +28,12 @@ Object.assign(ACT,{ pieSafe:()=>{const P=pieGet();if(!P||!P.co)return;P.safe=!P.safe;sfx('click');pieRe();}, pieName:()=>{const P=pieGet();if(!P||!P.co)return;const i=PIE_NAMES.indexOf(P.co.name);P.co.name=PIE_NAMES[(i+1)%PIE_NAMES.length];pieFounder(N_('pie.fp_rename'));pieRe();}, pieRename:()=>{const P=pieGet(),el=$('pieNm');if(!P||!P.co||!el)return;const v=el.value.replace(/\s+/g,' ').trim().slice(0,40);if(!v)return;P.co.name=v;pieFounder(N_('pie.fp_rename'));pieRe();}, + // Government money (60-features/99-pie-subsidies.js): Pie Control's Gov tab, a bid, the Ex-Im loan. + pieGovOpen:()=>{if(!S||pzOn()||!pieOn())return;UI.pieTab='gov';UI.confirm=null;pieModal();}, + pieBid:({id,f})=>{const P=pieGet();f=+f;const a=P&&P.gov.auc.find(x=>x.id===id);if(!a||!PIE_RDF_BIDS.includes(f))return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1')); + a.bid=f;toast(tr('pie_gov.t_bid',{city:esc(CITY[a.city].name),mo:fmt$(Math.round(a.ask*f)),d:dateStr(a.close)}),'good');sfx('click');pieRe();}, + pieExim:()=>{const P=pieGet();if(!P||!P.co)return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));if(!pieEximTake())return pieRe(); + const l=pieEximLoan();toast(`${tr('interface.amt_from_bank_has_landed',{amt:fmt$(l.amount),bank:esc(BANKS.exim.name)})}
${loanSummary(l)}`,'good');sfx('coin');pieRe();}, pieTab:({t})=>{if(!PIE_TABS.includes(t))return;UI.pieTab=t;pieModal();}, pieHi:({id})=>{if(typeof id!=='string')return;sfx('click');pieHiSet(id);}, pieCity:({v})=>{if(!S||!S.pops[v])return;UI.pieCity=v;pieModal();}, diff --git a/src/game/93-ui/85-pie-control.js b/src/game/93-ui/85-pie-control.js index 7ebda7f..c8a048a 100644 --- a/src/game/93-ui/85-pie-control.js +++ b/src/game/93-ui/85-pie-control.js @@ -4,7 +4,7 @@ function pieLicCountry(cc){try{PIE_CCN=PIE_CCN&&PIE_CCN.l===LANG?PIE_CCN:{l:LANG function pieCard(){if(!pieOn())return '';const P=S.pie; return `
🥧 ${tr('pie.pie_in_the_sky')}
${P&&P.co?esc(pieCoName())+' · '+tr('pie.card_live',{n:Object.keys(CRUSTS).reduce((a,id)=>a+pieLive(id),0),q:P.q.length}):tr('pie.card_pitch')}
${pieSpatCard()}
${btn(tr('pie.open_pie_control'),'pieOpen',{},P&&P.co?'sm':'pink sm')}
`;} -const PIE_TABS=['traffic','co','fly','dish','book']; +const PIE_TABS=['traffic','co','fly','dish','gov','book']; const pieTag=(t,on)=>`${t}`; function pieModal(){if(!S||!pieOn())return;const P=S.pie||pieBlank(S.day),can=pieCanBuild(),T=PIE_TABS.includes(UI.pieTab)?UI.pieTab:'traffic'; let h=`
${tr('pie.pie_in_the_sky')}

${P.co?esc(pieCoName()):tr('pie.pie_control')}

`; @@ -13,7 +13,7 @@ function pieModal(){if(!S||!pieOn())return;const P=S.pie||pieBlank(S.day),can=pi if(!P.co){h+=`

${tr('pie.found_pitch')}

${btn(tr('pie.found_price',{price:fmt$(piePrice(PIE_CO)),mo:fmt$(PIE_CO_MO)}),'pieFound',{},'pink',!can)}
`;openModal(h,'pie');return;} const tab=(k,l)=>``; h+=pieGlobeHtml()+pieSpatCard(); - h+=`
${tab('traffic',tr('pie_traffic.tab'))}${tab('co',tr('pie.tab_company'))}${tab('fly',tr('pie.tab_launch'))}${tab('dish',tr('pie.tab_dishes'))}${tab('book',tr('pie.tab_founder'))}
`; + h+=`
${tab('traffic',tr('pie_traffic.tab'))}${tab('co',tr('pie.tab_company'))}${tab('fly',tr('pie.tab_launch'))}${tab('dish',tr('pie.tab_dishes'))}${tab('gov',tr('pie_gov.tab'))}${tab('book',tr('pie.tab_founder'))}
`; const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)),c=S.pops[UI.pieCity]?UI.pieCity:cities[0]; const sel=`
`; if(T==='traffic')h+=pieTrafficHtml(); @@ -40,7 +40,8 @@ function pieModal(){if(!S||!pieOn())return;const P=S.pie||pieBlank(S.day),can=pi const ccs=[...new Set([...P.dishes.map(x=>CITY[x.city].cc),CITY[c].cc,...Object.keys(P.lic)])]; h+=`

${tr('pie.landing_rights')}

`+ccs.map(cc=>{const l=P.lic[cc],ok=pieLicOk(cc); return `
${esc(pieLicCountry(cc))}${ok?' · '+tr('pie.lic_until',{d:dateStr(l.until)}):l&&l.state!=='ok'&&l.until>S.day?' · '+tr('pie.lic_refused'):''}${btn((ok?tr('pie.renew'):tr('pie.buy'))+' '+fmt$(pieLicPrice(cc)),'pieLic',{cc},'ghost sm')}
`;}).join(''); - }else{ + }else if(T==='gov')h+=pieGovHtml(); + else{ const F=P.founder;h+=`
${tr('pie.promises')}${tr('pie.promises_line',{n:F.promises,b:F.broken})}
`; h+=`
${tr('pie.spent')}${fmt$(P.book.spent)}
${tr('pie.earned')}${fmt$(P.book.earned)}
`; if(R&&R.pie)h+=`

${tr('pie.earned_mo',{amt:fmt$(R.pie.rev),n:R.pie.isl.length})}

`; diff --git a/src/game/94-dashboard/70-bank.js b/src/game/94-dashboard/70-bank.js index 2051246..5232ce7 100644 --- a/src/game/94-dashboard/70-bank.js +++ b/src/game/94-dashboard/70-bank.js @@ -10,7 +10,7 @@ function renderBank(){ if(o.model==='balloon')return `${tr('bank.nothing_to_pay_until_the_end_2a38')}${tr('bank.apr_apr',{apr:(o.apr*100).toFixed(1)})}${tr('bank.n_months',{n:o.term})}${tr('bank.then_about_price_at_once',{price:fmt$(o.amount*Math.pow(1+o.apr/12,o.term))})}${sh}`; const extra=o.model==='storm'?`${tr('bank.2_per_open_incident')}`:o.model==='astro'?`${tr('bank.rate_set_by_the_stars_each')}`:''; return (B.equity?`${tr('common.no_repayments')}${tr('bank.pct_of_revenue_forever',{pct:pct(o.share)})}${tr('bank.buy_out_price',{price:fmt$(o.amount*3)})}`:`${tr('bank.apr_apr',{apr:(o.apr*100).toFixed(1)})}${tr('bank.n_months',{n:o.term})}${tr('common.price_mo',{price:fmt$(o.pay)})}${B.crypto?''+tr('bank.paid_in_tubecoin')+'':''}`)+extra+sh;}; - const covList=(l)=>l.covs.length?l.covs.map(c=>{const ok=COVS[c].ok(l);return `
${ok?'✓':'✗'} ${esc(covLabel(c))}
`;}).join(''):'
'+tr('bank.no_conditions_that_is_the_scary')+'
'; + const covList=(l)=>l.covs.length?l.covs.map(c=>{const ok=COVS[c].ok(l);return `
${ok?'✓':'✗'} ${esc(covLabel(c,l))}
`;}).join(''):'
'+tr('bank.no_conditions_that_is_the_scary')+'
'; let h=`
AS${S.asn} · ${esc(S.name)}

${tr('common.bank')}

${tr('common.cash')}
${fmt$(S.cash)}
${S.cash<0?tr('bank.bankrupt_at_100k'):tr('bank.in_the_vault')}
${tr('dashboard.monthly_p_l')}
${net>=0?'+':''}${fmt$(net)}
${tr('bank.after_loan_payments')}
diff --git a/src/i18n/en.js b/src/i18n/en.js index 05ca6a9..c25dbdf 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -307,6 +307,10 @@ "banks.do_the_kehrwoche_keep_your_noc":"Do the Kehrwoche: keep your NOC free of incidents older than a week.", "banks.download_our_app_and_enable_all":"Download our app and enable all notifications.", "banks.every_pop_needs_a_backup_generator":"Every POP needs a backup generator. Our risk team saw one disaster movie.", +"banks.exim_blurb":"The state lends you money to buy rockets from home. Space covenants apply.", +"banks.exim_keep_a_dish_in":"Keep a pie dish in {a}", +"banks.exim_launch_n_pies_by":"Launch {n} pies by {d} ({f} so far)", +"banks.exim_launch_pies":"Launch the pies you promised", "banks.fill_in_form_t_17b_in":"Fill in form T-17b in triplicate, every month, forever.", "banks.give_our_ceo_s_nephew_a":"Give our CEO’s nephew a job. He needs {price}/mo and a parking spot.", "banks.instant_approval_instant_regret":"Instant approval. Instant regret.", @@ -3509,6 +3513,42 @@ "pie_globe.switch_to_day_view":"Switch to day view", "pie_globe.switch_to_night_view":"Switch to night view", "pie_globe.your_pies_in_orbit":"Your pies in orbit, drag to turn the Earth", +"pie_gov.ask":"Ask {mo}/mo", +"pie_gov.bid":"Bid", +"pie_gov.closes":"bids close {d}", +"pie_gov.cov_dish":"Keep a pie dish in {a}", +"pie_gov.cov_launch":"Launch {n} pies by {d}", +"pie_gov.due":"Needs {p} served by {d}", +"pie_gov.exim":"Ex-Im Pie Bank", +"pie_gov.exim_breach":"Break a covenant and the rate goes up {apr} points, the deadline moves and the lending country gets cross.", +"pie_gov.exim_none":"No offer right now. The bank lends to rocket companies with a factory.", +"pie_gov.exim_offer":"Lends you {amt} at {apr}% for {n} months: {pay}/mo.", +"pie_gov.no_auction":"No auction open. The fund calls when a town only your pies reach is up for support.", +"pie_gov.open":"Open", +"pie_gov.pitcairn":"Pitcairn", +"pie_gov.pitcairn_note":"The UK pays {mo}/mo while the islanders are well served, and accepts satellite service for {sky}/mo.", +"pie_gov.rdf":"Rural Digital Pie Fund", +"pie_gov.rdf_note":"Reverse auctions for towns only orbit reaches: the lowest ask wins and is paid monthly for {y} years. Keep the town {p} served, averaged over each month: two months under it in a row and the award is revoked and {c} of the last year's support is clawed back.", +"pie_gov.rival_coop":"Co-op de Ville", +"pie_gov.rival_hugsnet":"HugsNet", +"pie_gov.rival_viasad":"ViaSad", +"pie_gov.served":"{p} served", +"pie_gov.t_auction":"Support for {city}: up to {mo}/mo for {y} years. Bids close {d}.", +"pie_gov.t_auction_title":"Rural Digital Pie Fund auction", +"pie_gov.t_bid":"Bid in for {city}: {mo}/mo. Results on {d}.", +"pie_gov.t_breach":"The Ex-Im Pie Bank tightens your terms: {apr}% now, and {a} is not amused.", +"pie_gov.t_breach_spat":"Its government has questions.", +"pie_gov.t_done":"The fund's support for {city} has ended: {amt} paid in all.", +"pie_gov.t_exim":"The Ex-Im Pie Bank would lend you {amt} at almost nothing, if you keep a pie dish in {a}.", +"pie_gov.t_exim_title":"State money for rockets", +"pie_gov.t_lost":"{rival} won {city} asking only {mo}/mo.", +"pie_gov.t_revoked":"Award for {city} revoked: {p} served, the fund wants {need}. It claws back {amt}.", +"pie_gov.t_warn":"The fund is watching {city}: {p} served last month, it wants {need}. Another month like that and the award is revoked.", +"pie_gov.t_won":"You won {city}: {mo}/mo. Have it {p} served by {d}.", +"pie_gov.tab":"Gov", +"pie_gov.until":"Paid until {d}", +"pie_gov.up_to":"up to {mo}/mo", +"pie_gov.warned":"one more bad month and it is revoked", "pie_inc.dig_msg":"A backhoe found the backhaul fiber under the pie dish in {city}. The dish is fine, but its traffic has nowhere to go.", "pie_inc.dig_press":"The press office says: the dish is taking a well-earned break from the ground.", "pie_inc.food_fix":"Buy a Space Roomba", @@ -3661,6 +3701,7 @@ "pie_traffic.via_dishes":"up at {up}, down at {down}", "pitcairn.uk_grant_mo":"UK grant {mo}/mo", "pitcairn.uk_grant_mo_once_islanders":"UK grant {mo}/mo once the islanders are online", +"pitcairn.uk_sky_grant_mo":"UK satellite grant {mo}/mo (fiber gets {full})", "pni_all.additional_per_month":"Additional monthly cost", "pni_all.all_at_port":"Peer all networks · {port}", "pni_all.delivery_and_traffic_charges":"Delivery times vary by network. Traffic-based peering charges also apply where required.", diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 2d54560..91e9080 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -627,11 +627,12 @@ test('O5: launches fail only with chaos on, never in the first 90 days after the test('O7: a fresh Tier 1 cannot afford a full Shortcrust in its first year', () => { // Reference: the big-network benchmark save, a won network far larger than a fresh Tier 1. A year of its profit at - // today's revenue (costs ignored, so generously) plus the largest loan any bank offers (12x monthly revenue). + // today's revenue (costs ignored, so generously) plus the largest loan any bank offers (12x monthly revenue), and the + // most the Ex-Im Pie Bank lends a rocket company on top. const g = load(); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`); - const rev = g.ev('R.revMo'), loan = g.ev('Math.max(...Object.values(BANKS).map(b=>b.amt[1]))') * rev, cash = Math.max(0, g.ev('S.cash')); + const rev = g.ev('R.revMo'), loan = g.ev('Math.max(...Object.values(BANKS).map(b=>b.amt[1]))') * rev + g.ev('pieEximCap()'), cash = Math.max(0, g.ev('S.cash')); const year = 12 * rev + loan + Math.min(cash, 12 * rev); const full = g.ev("pieFullCost('short')"); assert.ok(full > 5e9, `O7: a full Shortcrust costs ${Math.round(full / 1e6)}M`); diff --git a/tests/pie-balance.test.js b/tests/pie-balance.test.js index 417bfe3..3897434 100644 --- a/tests/pie-balance.test.js +++ b/tests/pie-balance.test.js @@ -3,7 +3,7 @@ // 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). +// and PIE_BALANCE_SEED another seed (for tuning). PIE_BALANCE_GOV=1 plays only the run with government money (below). const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); @@ -21,9 +21,11 @@ const YEARS = +(process.env.PIE_BALANCE_YEARS || 0); // 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. +// With gov (the second test), the same player also takes government money: asks 50% in every Rural Digital Pie Fund +// auction, takes the Ex-Im Pie Bank's loan and keeps a dish in its country (the covenant). // 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) { +function sim(days, stop = false, seed = 7, gov = false) { 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; @@ -41,12 +43,17 @@ function sim(days, stop = false, seed = 7) { 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; + if(window.__gov){const G=P.gov;for(const a of G.auc)if(a.bid!==0.5)ACT.pieBid({id:a.id,f:0.5});if(G.ex)ACT.pieExim(); + const l=pieEximLoan();if(l&&!pieEximDishOk(l)){const c=Object.keys(S.pops).filter(c=>CITY[c].cc===l.pie.cc&&pieCovers('short',c)&&!P.dishes.some(x=>x.city===c)).sort((a,b)=>sfOf(R,b)-sfOf(R,a))[0]; + if(c){if(!pieLicOk(l.pie.cc))ACT.pieLic({cc:l.pie.cc});ACT.pieDish({city:c});}}} + 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(),P.gov.aw.length].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()`); + window.__gov=${gov};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 f=pieDay;pieDay=d=>{const s0=S.pie.book.spent;f(d);__B.day=(__B.day||0)+(S.pie.book.spent-s0)/1e6;};} + {const f=pieRdfRevoke;pieRdfRevoke=(w,avg)=>{(window.__L=window.__L||[]).push(['revoked',S.day,w.city,S.pops[w.city]?'pop':'terminals',avg.toFixed(2),Math.round(w.mo/1e6)+'M/mo',S.biz.filter(b=>b.city===w.city&&BIZ_T[b.type].orbit).length].join(' '));f(w,avg);};} + {const f=pieRdfClose;pieRdfClose=a=>{if(a.bid&&a.bid<=a.riv)(window.__L=window.__L||[]).push(['award',S.day,a.city,S.pops[a.city]?'pop':'terminals',CITY[a.city].P,Math.round(a.ask*a.bid/1e6)+'M/mo'].join(' '));f(a);};}`); const rows = []; try { const d0 = g.ev('S.day'); @@ -71,7 +78,8 @@ function payback(rows) { 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 }, () => { +let BASE = null; +test('O7: a full lasered Shortcrust, run sensibly through the game loop, pays back in 5 to 10 years', { timeout: 600000, skip: !!process.env.PIE_BALANCE_GOV }, () => { 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`); @@ -80,6 +88,25 @@ test('O7: a full lasered Shortcrust, run sensibly through the game loop, pays ba 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`); + BASE = y; 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, []); }); + +// Government money (src/game/60-features/99-pie-subsidies.js, the Pitcairn grant has no town in this save) helps, but +// never turns the constellation into a bargain: at most two years sooner than without it, and never under four. +test('O7: government money pays back sooner, by two years at most', { timeout: 600000 }, () => { + const years = YEARS || 10, seed = +(process.env.PIE_BALANCE_SEED || 7); + const { rows, errors, ev } = sim(360 * years, !YEARS, seed, true); + if (YEARS) for (const r of rows) console.log(`gov 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, ${r.cust} customers`); + const y = payback(rows), st = JSON.parse(ev('JSON.stringify({won:S.stats.pieRdf|0,lost:S.stats.pieRdfLost|0,aw:S.pie.gov.aw.length,mo:pieGovMo(),exim:(S.loans.find(l=>l.bank===\'exim\')||{}).pie||null})')); + if (process.env.PIE_BALANCE_DIAG) for (const l of JSON.parse(ev('JSON.stringify(window.__L||[])'))) console.log(l); + if (YEARS) console.log(`gov payback: year ${y.toFixed(1)} (${st.won} awards won, ${st.lost} revoked, ${st.aw} in force at ${(st.mo / 1e6).toFixed(1)}M/mo, Ex-Im ${JSON.stringify(st.exim)})`); + assert.ok(st.won > 0, 'the fund awarded something'); + assert.ok(y >= 4, `O7: with government money a full Shortcrust pays back in ${y.toFixed(1)} years; the fund pays too much`); + if (BASE !== null) { + assert.ok(y <= BASE + 0.3, `government money must not slow payback (the runs differ by chance after the first auction) (${y.toFixed(1)} vs ${BASE.toFixed(1)})`); + assert.ok(BASE - y <= 2, `O7: government money pays back ${(BASE - y).toFixed(1)} years sooner (${y.toFixed(1)} vs ${BASE.toFixed(1)}); the fund pays too much`); + } + assert.deepEqual(errors, []); +}); diff --git a/tests/pie-gov.test.js b/tests/pie-gov.test.js new file mode 100644 index 0000000..d56ec80 --- /dev/null +++ b/tests/pie-gov.test.js @@ -0,0 +1,263 @@ +// Pie in the Sky: government money (src/game/60-features/99-pie-subsidies.js, 85-pitcairn.js). The Rural Digital Pie +// Fund's auctions and awards, the Ex-Im Pie Bank's loan and its space covenants, and Pitcairn's satellite grant. +// Seeded; auctions, rival bids and days are set or driven directly, so nothing depends on luck. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// The backhaul world (tests/pie-backhaul.test.js): a London – New York – Auckland backbone, a full lasered Shortcrust and +// Pitcairn on its own, with broadband and a dish, reaching the backbone only through orbit. +const pitcairn = (ev) => { + ev("ACT.modeSet({m:'sandbox'});ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.nextFail=1e9;S.nextEvent=1e9"); + ev("for(const c of ['lon','nyc','akl','pcn'])if(!S.pops[c])ACT.buildPop({city:c});S.links=[];" + + "S.links.push({id:'ln',a:'lon',b:'nyc',kind:'wave',tier:3,km:5818,sub:true,cable:'grace',cut:0,mo:1},{id:'na',a:'nyc',b:'akl',kind:'wave',tier:3,km:14200,sub:true,cut:0,mo:1});for(const c of ['lon','nyc'])ACT.buyTransit({city:c,net:'cog',tier:1});ACT.buyTransit({city:'akl',net:'sgt',tier:1})"); + ev("ACT.pieFound();for(const c of ['lon','nyc','akl','pcn']){ACT.pieDish({city:c});S.pie.lic[CITY[c].cc]={state:'ok',until:1e6};}for(const x of S.pie.dishes)x.ant=PIE_ANT_MAX"); + ev("S.pops.pcn.bb={d:5};S.pie.crusts.short.cohorts=[{n:CRUSTS.short.full,day:S.day,las:true}];compute()"); +}; +// The spats world (tests/pie-spats.test.js): a normal game with real chaos and open gates, dishes in NL, BE, DE, SG. +const sky = (ev) => { + ev("beginGame('Sky','fra',{mode:'normal',preset:'oncall',rules:{gates:'open'}});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;S.nextFail=1e9;S.nextEvent=1e9;S.monkey&&(S.monkey.next=1e9)"); + ev("for(const c of ['sin','ams','bru','lon'])ACT.buildPop({city:c});ACT.pieFound();ACT.pieFactory();ACT.piePad({city:'sin'});for(const c of ['ams','bru','fra','sin'])ACT.pieDish({city:c});for(const cc of ['NL','BE','DE','SG'])ACT.pieLic({cc})"); + ev('pieCohort(\'short\',1200,true);S.day=S.pie.born+120;compute();S.pie.stock=400'); +}; +const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`)); +// Days of the fund alone (no failures, no other randomness): the day counter and pieGovDay(). +const govDays = (ev, n) => ev(`for(let i=0;i<${n};i++){S.day++;pieGovDay(S.day);}`); + +test('Pitcairn served from orbit earns the UK satellite grant: less than the fiber grant, latency forgiven', () => { + const { ev, errors } = load(); + pitcairn(ev); + assert.ok(ev("sfOf(R,'pcn')") < 0.9, `orbit's latency keeps sfOf under the fiber bar (${ev("sfOf(R,'pcn')")})`); + assert.equal(ev('grantOn(R)'), false, 'no fiber grant'); + assert.equal(ev('grantSky(R)'), true, 'but the satellite tier'); + assert.equal(ev('R.rev.grant'), ev('GRANT_SKY_MO')); + assert.ok(ev('GRANT_SKY_MO') < ev('GRANT_MO'), 'it pays less'); + assert.equal(ev('R.pie.gov.sky'), ev('GRANT_SKY_MO'), 'and counts in the orbit\'s books'); + ev('S.pie.book.earned=0;R.pie.gov.rdf=0;pieGovDay(S.day)'); + assert.ok(Math.abs(ev('S.pie.book.earned') - ev('GRANT_SKY_MO') / 30) < 1e-6, 'a day of it is booked'); + assert.match(ev("grantFact('pcn')"), /satellite grant/); + // Under the bar (a dish of one antenna for a big town) or no orbit at all: nothing. + ev("S.pops.pcn.bb={d:300};S.pie.dishes.find(x=>x.city==='pcn').ant=1;compute()"); + assert.equal(ev('R.rev.grant'), 0, 'a full pipe is not service'); + ev("S.pops.pcn.bb={d:5};S.pie.dishes=S.pie.dishes.filter(x=>x.city!=='pcn');compute()"); + assert.equal(ev('R.rev.grant'), 0, 'no dish, no grant'); + assert.deepEqual(errors, []); +}); + +test('Rural Digital Pie Fund: a cut-off town is auctioned, the lowest ask wins and is paid monthly', () => { + const { ev, errors } = load(); + pitcairn(ev); + assert.ok(J(ev, 'pieRdfCands()').includes('pcn'), 'Pitcairn on backhaul is a candidate'); + assert.ok(!J(ev, 'pieRdfCands()').includes('akl'), 'a POP on the backbone is not'); + ev("pieRdfOpen('pcn')"); + assert.ok(ev('S.log[0].t').includes('Pitcairn') || ev('S.log[0].t').includes('Adamstown'), 'announced'); + assert.equal(J(ev, 'pieRdfCands()').includes('pcn'), false, 'one auction per town'); + // The rival asks 60%: asking 50% wins, at 50% of the reserve. + ev("const a=S.pie.gov.auc[0];a.riv=0.6;ACT.pieBid({id:a.id,f:0.5})"); + assert.equal(ev('S.pie.gov.auc[0].bid'), 0.5); + ev('ACT.pieBid({id:S.pie.gov.auc[0].id,f:0.33})'); + assert.equal(ev('S.pie.gov.auc[0].bid'), 0.5, 'only the offered bids'); + const ask = ev('S.pie.gov.auc[0].ask'); + govDays(ev, ev('PIE_RDF_DAYS')); + assert.equal(ev('S.pie.gov.auc.length'), 0, 'closed'); + const w = J(ev, 'S.pie.gov.aw[0]'); + assert.equal(w.city, 'pcn'); + assert.equal(w.mo, Math.round(ask * 0.5)); + ev('compute()'); + assert.equal(ev('R.rev.gov'), w.mo, 'the subsidy is revenue'); + assert.equal(ev('R.pie.gov.rdf'), w.mo, 'and orbit income in the books'); + ev('S.pie.book.earned=0'); + govDays(ev, 3); + assert.ok(Math.abs(ev('S.pie.book.earned') - 3 * (w.mo + ev('GRANT_SKY_MO')) / 30) < 1e-3, 'three days booked'); + // Served well past the deadline: still paid. + govDays(ev, ev('PIE_RDF_DUE')); + assert.equal(ev('S.pie.gov.aw.length'), 1, 'kept while served'); + assert.ok(ev("pieRdfSrv('pcn')") >= ev('PIE_RDF_NEED')); + assert.deepEqual(errors, []); +}); + +test('the rival under your ask wins; you only hear about auctions you bid in', () => { + const { ev, errors } = load(); + pitcairn(ev); + ev("pieRdfOpen('pcn');const a=S.pie.gov.auc[0];a.riv=0.6;a.rv=0;ACT.pieBid({id:a.id,f:0.9})"); + govDays(ev, ev('PIE_RDF_DAYS')); + assert.equal(ev('S.pie.gov.aw.length'), 0); + assert.match(ev('S.log[0].t'), /ViaSad won/); + ev("pieRdfOpen('pcn');S.pie.gov.auc[0].riv=0.95"); + const n = ev('S.log.length'); + govDays(ev, ev('PIE_RDF_DAYS')); + assert.equal(ev('S.pie.gov.aw.length'), 0, 'no bid, no award'); + assert.equal(ev('S.log.length'), n, 'and no news'); + assert.deepEqual(errors, []); +}); + +test('service under the minimum past the deadline: a warning, then the award is revoked and part of it clawed back', () => { + const { ev, errors } = load(); + pitcairn(ev); + ev("pieRdfOpen('pcn');const a=S.pie.gov.auc[0];a.riv=1;ACT.pieBid({id:a.id,f:0.7})"); + govDays(ev, ev('PIE_RDF_DAYS')); + const w = J(ev, 'S.pie.gov.aw[0]'); + // The pies go to safe mode: Pitcairn is cut off. Before the deadline the fund waits. + ev('S.pie.safe=true;compute()'); + assert.equal(ev("pieRdfSrv('pcn')"), 0); + govDays(ev, 60); + assert.equal(ev('S.pie.gov.aw.length'), 1, 'still building out: no check before the deadline'); + assert.equal(ev('S.pie.gov.aw[0].k'), 0); + govDays(ev, 30); + assert.equal(ev('S.pie.gov.aw.length'), 1, 'the first bad month past the deadline is a warning'); + assert.equal(ev('S.pie.gov.aw[0].k'), 1); + assert.match(ev('S.log[0].t'), /watching/); + ev('S.pie.book.earned=1e9'); + govDays(ev, 30); + assert.equal(ev('S.pie.gov.aw.length'), 0, 'the second in a row revokes it'); + const paid = 120 * w.mo / 30, claw = Math.round(Math.min(paid, 12 * w.mo) * ev('PIE_RDF_CLAW')); + // The month's subsidy was booked day by day (compute() still counted it), then the claw came off. + assert.equal(ev('R.pie.gov.sky'), 0, 'no satellite grant in safe mode'); + assert.ok(Math.abs(ev('1e9-S.pie.book.earned') - (claw - w.mo)) < 2, `clawed back ${claw}`); + assert.match(ev('S.log[0].t'), /revoked/); + assert.equal(ev('S.stats.pieRdfLost'), 1); + ev('compute()'); + assert.equal(ev('R.rev.gov'), 0, 'no more subsidy'); + assert.deepEqual(errors, []); +}); + +test('a good month clears the warning', () => { + const { ev, errors } = load(); + pitcairn(ev); + ev("pieRdfOpen('pcn');const a=S.pie.gov.auc[0];a.riv=1;ACT.pieBid({id:a.id,f:0.7})"); + govDays(ev, ev('PIE_RDF_DAYS')); + ev('S.pie.safe=true;compute()'); + govDays(ev, 90); + assert.equal(ev('S.pie.gov.aw[0].k'), 1); + ev('S.pie.safe=false;compute()'); + govDays(ev, 30); + assert.equal(ev('S.pie.gov.aw[0].k'), 0); + ev('S.pie.safe=true;compute()'); + govDays(ev, 30); + assert.equal(ev('S.pie.gov.aw.length'), 1, 'one bad month again: only a warning'); + assert.deepEqual(errors, []); +}); + +test('Ex-Im Pie Bank: a cheap loan sized to the constellation, with space covenants', () => { + const { dom, ev, errors } = load(); + sky(ev); + ev("S.pie.crusts.short.cohorts=[{n:100,day:S.day,las:true}];pieGovDay(S.day)"); + const o = J(ev, 'S.pie.gov.ex'); + assert.ok(o, 'offered once there is a factory'); + assert.ok(J(ev, 'piePopCc()').includes(o.cc), 'by a country you have a POP in'); + assert.ok(o.amt >= ev('PIE_EXIM_MIN') && o.amt <= ev('pieEximCap()'), `${o.amt}`); + assert.ok(o.apr >= 0.015 && o.apr <= 0.025, `cheap: ${o.apr}`); + // Bigger constellation, bigger loan, never past the cap. + ev("S.pie.gov.ex=null;pieCohort('short',200,true);pieGovDay(S.day)"); + assert.ok(ev('S.pie.gov.ex.amt') > o.amt, 'grows with the pies'); + ev("pieCohort('short',30000,true);S.pie.gov.ex=null;pieGovDay(S.day)"); + assert.equal(ev('S.pie.gov.ex.amt'), ev('pieEximCap()')); + ev("S.pie.gov.ex.cc='GB'"); + const cash = ev('S.cash'), amt = ev('S.pie.gov.ex.amt'); + ev('ACT.pieExim()'); + const l = J(ev, "S.loans.find(l=>l.bank==='exim')"); + assert.ok(l, 'taken'); + assert.equal(ev('S.cash') - cash >= amt - 1, true, 'paid out'); + assert.deepEqual(l.covs, ['pielaunch', 'piedish']); + assert.equal(l.pie.cc, 'GB'); + assert.equal(ev('S.pie.gov.ex'), null); + ev('pieGovDay(S.day)'); + assert.equal(ev('S.pie.gov.ex'), null, 'one at a time'); + ev('compute()'); + assert.ok(ev('R.cost.loans') >= l.pay, 'billed like any loan'); + // Launches count; the dish covenant wants a dish in Britain. + ev('for(const f of PIE_ON.launch)f({n:20,test:false},true)'); + assert.equal(ev("S.loans.find(l=>l.bank==='exim').pie.flown"), 20); + assert.equal(ev("COVS.pielaunch.ok(S.loans.find(l=>l.bank==='exim'))"), true, 'before the deadline'); + assert.equal(ev("COVS.piedish.ok(S.loans.find(l=>l.bank==='exim'))"), false, 'no dish in GB'); + // The bank and Pie Control show it, on a phone. + ev("window.innerWidth=360;UI.started=true;$('bankBox').hidden=false;renderBank()"); + const bank = dom.window.document.querySelector('#bankCard').textContent; + assert.match(bank, /Ex-Im Pie Bank/); + assert.match(bank, /Launch \d+ pies by .* \(20 so far\)/); + assert.match(bank, /Keep a pie dish in/); + ev("$('bankBox').hidden=true;ACT.pieGovOpen()"); + assert.match(dom.window.document.querySelector('#modal').textContent, /Ex-Im Pie Bank/); + ev('closeModal()'); + assert.deepEqual(errors, []); +}); + +test('a broken space covenant: the bank penalty, tighter terms and a spat in the lending country', () => { + const { ev, errors } = load(); + sky(ev); + ev("pieGovDay(S.day);S.pie.gov.ex.cc='GB';ACT.pieExim()"); + const L = "S.loans.find(l=>l.bank==='exim')"; + const apr = ev(`${L}.apr`); + assert.equal(ev('pieChaos()'), true); + ev("S.pie.spat={};for(let i=0;i<26;i++){S.day++;loanTick(S.day);}"); + assert.ok(Math.abs(ev(`${L}.apr`) - apr - ev('PIE_EXIM_PEN')) < 1e-9, 'rate up'); + assert.equal(ev(`${L}.pie.br`), 1); + assert.equal(ev('S.pie.spat.home&&S.pie.spat.home.cc'), 'GB', 'no dish in Britain: "data stays home"'); + assert.ok(ev('S.loanStrikes') >= 1, 'and the bank\'s own penalty'); + // A dish there mends that one; missing the launch target reschedules it and Britain is cross again. + ev(`ACT.pieDish({city:'lon'});ACT.pieLic({cc:'GB'});S.pie.spat={};${L}.pie.by=S.day;${L}.breach=0`); + assert.equal(ev(`COVS.piedish.ok(${L})`), true); + ev('for(let i=0;i<11;i++){S.day++;loanTick(S.day);}'); + assert.equal(ev(`${L}.pie.br`), 2); + assert.ok(ev(`${L}.pie.by`) > ev('S.day'), 'a new deadline'); + assert.equal(ev(`COVS.pielaunch.ok(${L})`), true); + assert.equal(ev('S.pie.spat.lic&&S.pie.spat.lic.cc'), 'GB', 'landing rights questioned'); + // Without chaos: tighter terms, no spat (rule O5). + ev(`S.rules.chaos='none';S.pie.spat={};${L}.pie.by=S.day;${L}.breach=0;for(let i=0;i<11;i++){S.day++;loanTick(S.day);}`); + assert.equal(ev(`${L}.pie.br`), 3); + assert.deepEqual(J(ev, 'Object.keys(S.pie.spat)'), []); + assert.deepEqual(errors, []); +}); + +test('the Gov tab fits a phone and lists the auction, the awards, Pitcairn and the bank', () => { + const { dom, ev, errors } = load(); + pitcairn(ev); + ev("window.innerWidth=360;pieRdfOpen('pcn');S.pie.gov.aw.push({id:'w1',city:'akl',mo:5e6,start:S.day,due:S.day+90,end:S.day+1800,s:0,n:0,paid:0});UI.pieTab=null;ACT.pieGovOpen()"); + const m = dom.window.document.querySelector('#modal'); + assert.equal(ev("$('modal').hidden"), false); + assert.equal(m.querySelectorAll('[data-act=pieBid]').length, 3, 'three asks'); + assert.match(m.textContent, /Rural Digital Pie Fund/); + assert.match(m.textContent, /Auckland/); + assert.match(m.textContent, /Pitcairn/); + assert.match(m.textContent, /satellite grant/); + assert.doesNotMatch(m.textContent, /pie_gov\.|banks\.|undefined|NaN/); + ev("ACT.pieBid({id:S.pie.gov.auc[0].id,f:0.7})"); + assert.ok(dom.window.document.querySelector('#modal [data-act=pieBid].pink'), 'your bid is marked'); + ev('closeModal()'); + assert.deepEqual(errors, []); +}); + +test('saves: the fund and the bank survive a round trip, garbage is repaired, old saves load', () => { + const { ev, errors } = load(); + sky(ev); + ev("pieRdfOpen('ams');S.pie.gov.aw.push({id:'w1',city:'bru',mo:5e6,start:S.day-10,due:S.day+80,end:S.day+1790,s:4.5,n:5,k:1,paid:1e6});pieGovDay(S.day);S.pie.gov.ex.cc='GB';ACT.pieExim()"); + const before = J(ev, 'S.pie.gov'); + ev('S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.deepEqual(J(ev, 'S.pie.gov'), before); + assert.equal(ev("S.loans.find(l=>l.bank==='exim').pie.cc"), 'GB'); + // Garbage. + ev("S.pie.gov={auc:[{city:'nowhere'},{id:'x',city:'ams',ask:1e30,close:-5,riv:7,bid:0.42}],aw:'lots',ex:{cc:'XX'},told:'yes'};S.loans.find(l=>l.bank==='exim').pie={cc:'XX',n:-4};S.loans.find(l=>l.bank==='exim').covs=['golf'];S=migrate(JSON.parse(JSON.stringify(S)))"); + const g = J(ev, 'S.pie.gov'); + assert.equal(g.auc.length, 1); + assert.equal(g.auc[0].bid, 0); + assert.ok(g.auc[0].ask <= ev('PIE_RDF_MO*20')); + assert.ok(g.auc[0].riv <= 1); + assert.deepEqual(g.aw, []); + assert.equal(g.ex, null); + const l = J(ev, "S.loans.find(l=>l.bank==='exim')"); + assert.equal(l.pie.cc, 'DE', 'the home country'); + assert.equal(l.pie.n, 0); + assert.deepEqual(l.covs, ['pielaunch', 'piedish']); + // A save from before: no gov at all. + ev('delete S.pie.gov;S=migrate(JSON.parse(JSON.stringify(S)));pieGovDay(S.day);compute()'); + assert.deepEqual(J(ev, 'S.pie.gov.aw'), []); + assert.equal(ev('R.rev.gov'), 0); + assert.deepEqual(errors, []); +}); + +test('ordinary banks never offer the Ex-Im loan', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.day=100;S.cash=1000;for(let i=0;i<300;i++){S.loanOffers=[];spawnLoanOffer(i%2===0);if(S.loanOffers.some(o=>o.bank==='exim'))break;}"); + assert.equal(ev("S.loanOffers.some(o=>o.bank==='exim')"), false); + assert.deepEqual(errors, []); +}); diff --git a/tests/pie-in-the-sky.test.js b/tests/pie-in-the-sky.test.js index 29fe732..d623f89 100644 --- a/tests/pie-in-the-sky.test.js +++ b/tests/pie-in-the-sky.test.js @@ -273,7 +273,7 @@ test('Pie Control renders every tab on a phone', () => { ev('window.innerWidth=360'); won(ev); company(ev); - for (const t of ['co', 'fly', 'dish', 'book']) { + for (const t of ['co', 'fly', 'dish', 'gov', 'book']) { ev(`ACT.pieTab({t:'${t}'})`); assert.equal(ev("$('modal').hidden"), false); assert.ok(dom.window.document.querySelectorAll('#modalCard [data-act]').length > 2, t); diff --git a/tests/pie-routing.test.js b/tests/pie-routing.test.js index 2e84f38..575bbfc 100644 --- a/tests/pie-routing.test.js +++ b/tests/pie-routing.test.js @@ -174,7 +174,9 @@ test('orbit earnings go into the book, day by day', () => { const { ev, errors } = load(); world(ev); term(ev, 'pz', 'pcn'); - const mo = ev('R.pie.rev'); + // Homes on Pitcairn online through the pies also bring the UK's satellite grant (tests/pie-gov.test.js). + assert.equal(ev('R.pie.gov.sky'), ev('GRANT_SKY_MO')); + const mo = ev('R.pie.rev+R.pie.gov.rdf+R.pie.gov.sky'); ev('for(let i=0;i<30;i++)dayTick()'); assert.ok(Math.abs(ev('S.pie.book.earned') - mo) / mo < 0.05, `${ev('S.pie.book.earned')} ≈ ${mo}`); assert.deepEqual(errors, []);