F5: client con i pannelli Industrie, Compagnie e borsa e la Cronaca finale

- Pannello «Industrie»: elenco, scheda del proprietario con condizione, resa degli impianti,
  fermi, ricambi e macchinari, budget, ricambi da ordinare, fermo programmato, ammodernamento
  e acquisto al prezzo chiesto.
- Pannello a tutto schermo «Compagnie e borsa»: listino, offerte con difese, scheda della
  compagnia con libro dei soci e storico, compravendita, quotazione, dividendi, riacquisto,
  offerte pubbliche, fusione, aste; banner dell'amministrazione controllata.
- Cronaca finale e provvisoria, modalità osservatore.
- Tema applicato a ogni radice dell'interfaccia (prima non arrivava ai controlli), menu e
  connessione a tutta finestra, barra degli strumenti scorrevole; 228 nuove chiavi it/en.
- Schermate docs/screenshots/f5-*.jpg dal pilota automatico.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-12 10:57:19 +00:00
1 parent 7879ac502d
commit ebf6163a4b
25 files changed
+2300 -25

No files matched your search

@@ -1,27 +1,52 @@
keys,it,en
Abitanti,,Population
Accetta,,Accept
Acquista,,Buy
Aderisci con le tue azioni,,Tender your shares
Aggiorna,,Refresh
Alto,,High
Ambra,,Amber
Amministrazione controllata,,Receivership
Ammoderna,,Upgrade
Ammodernamento,,Upgrade
Ammodernamento di livello,,Level upgrade
Ammodernamento programmato,,Upgrade scheduled
Ancora nessun fatto da raccontare.,,Nothing to tell yet.
Anno,,Year
Annulla,,Cancel
Anteprima non disponibile: ,,Preview unavailable:
Appartiene a,,Belongs to
Assegna,,Assign
Asta degli attivi,,Asset auction
Attendi il pieno alla prima fermata (max 2 giorni),,Wait for full load at the first stop (max 2 days)
Attiva,,Active
Avvio del server locale…,,Starting the local server…
Azioni proprie (non votano),,Treasury shares (no vote)
Base,,Base
Base d'asta,,Reserve price
Binari,,Track
Binari di stazione,,Platforms
Blu,,Blue
Budget di manutenzione,,Maintenance budget
C'è già un'offerta in corso su questa compagnia: la trovi nell'elenco a sinistra.,,There is already a bid on this company: see the list on the left.
Cantiere,,Construction
Capitalizz.,,Market cap
Capitalizzazione,,Market cap
Carico,,Load
Cartella di manutenzione,,Maintenance record
Cartella in arrivo dal server…,,Record on its way from the server…
Cassa,,Cash
Cassa dell'industria,,Industry cash
Cavaliere bianco,,White knight
Celeste,,Light blue
"Chi offre di più alla chiusura compra treni, binari, stazioni e industrie della compagnia fallita.",,"The highest bidder at closing buys the bankrupt company's trains, track, stations and industries."
Chiedi il prestito,,Request loan
Chiudi,,Close
Chiusa,,Closed
Chiusura,,Closes
Classe,,Class
Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea.,,Click a track to place a block signal: it splits the edge into sections and raises line capacity.
"Clic su una compagnia per la scheda, il libro dei soci e le operazioni. Prezzo per azione: il maggiore tra patrimonio netto e",,"Click a company for its card, shareholder register and actions. Share price: the greater of net worth and"
"Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo.",,"Click a station, depot or free track to demolish it; part of the cost is refunded."
"Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare.",,"Click the map to place route points (Shift: no 45° snap), Enter to build, right click to cancel."
"Clic sulla mappa vicino a un binario, poi raccordalo con lo strumento Binari. Nel deposito si comprano i veicoli e si compongono i treni.",,"Click the map near a track, then connect it with the Track tool. Vehicles are bought and trains composed in the depot."
@@ -31,77 +56,160 @@ Collegamento in corso…,,Connecting…
Collegamento non riuscito,,Connection failed
Collegati,,Connect
Collegati a un server,,Connect to a server
Colloca il,,Float
Come la linea o la flotta,,Same as line or fleet
Compagnia,,Company
Compagnia fallita: nessuna asta in corso.,,Bankrupt company: no auction running.
Compagnie,,Companies
Compagnie e borsa,,Companies and stock exchange
Componi,,Compose
Compra,,Buy
Compra veicoli,,Buy vehicles
Compravendita di azioni,,Share trading
Condizione,,Condition
Connessione persa,,Connection lost
Consuma,,Consumes
Continua come osservatore,,Continue as observer
Controllo,,Control
Controvalore,,Value
Convenzioni,,Agreements
Coperto dalla riserva,,Covered by reserve
Costi dell'anno,,Costs this year
Costo,,Cost
Costo dell'ammodernamento,,Upgrade cost
Costruisci,,Build
Crea linea,,Create line
Cronaca finale,,Final chronicle
Cronaca provvisoria,,Chronicle so far
Dati del gioco non trovati o non validi.,,Game data missing or invalid.
Dati insufficienti,,Not enough data
Debito,,Debt
Demolisci,,Demolish
Depositi e officine,,Depots and workshops
Deposito,,Depot
Deragliamento,,Derailment
Difese del bersaglio,,Target's defences
Disconnesso,,Disconnected
Dividendi (12 mesi),,Dividends (12 months)
Dividendo,,Dividend
Dividendo per azione,,Dividend per share
Dividendo straordinario,,Extra dividend
Doppio binario,,Double track
Dove lavorano gli abitanti,,Where residents work
Efficienza,,Efficiency
Elettrificato,,Electrified
Esci,,Quit
Espansiva,,Expansive
Fallimento,,Bankruptcy
Fatti salienti,,Highlights
Fermo,,Shutdown
Fermo programmato,,Planned shutdown
Finanze,,Finance
"Flotta, dal treno più usurato",,"Fleet, most worn first"
Fondatore (tu),,Founder (you)
Fondatore privato,,Private founder
Fusione,,Merger
Galleria,,Tunnel
Gallerie,,Tunnels
Gestionale ferroviario dall'alto,,Top-down railway management
Gestisci l'industria,,Manage the industry
Grano,,Wheat
Guasti nell'anno,,Failures this year
Guasto,,Breakdown
Guasto grave,,Major failure
Guasto lieve,,Minor failure
Hai aderito con tutte le tue azioni.,,You tendered all your shares.
"Il mondo continua: le compagnie IA giocano e puoi guardarle come osservatore, ma il server non accetta più i tuoi comandi.",,"The world goes on: AI companies keep playing and you can watch as an observer, but the server no longer accepts your commands."
Il server non risponde più. La partita continua sul server.,,The server is not responding. The game goes on on the server.
Impegno massimo,,Maximum commitment
Impianti,,Plant
Impieghi,,Jobs
"In amministrazione controllata compri anche dal controllante, con il premio di riscatto.",,"In receivership you also buy from the controller, at the ransom premium."
In attesa del listino del giorno…,,Waiting for today's share list…
In vendita,,For sale
Incidente grave,,Serious accident
Incorpora la controllata,,Merge the subsidiary
Indica l'indirizzo del server,,Enter the server address
Indietro,,Back
Indirizzo (host:porta),,Address (host:port)
Indirizzo non valido,,Invalid address
Industrie,,Industries
Km di binari,,Track km
Km di servizio al giorno,,Service km per day
L'acquisto di industrie si sblocca al livello,,Buying industries unlocks at level
La compagnia è stata scalata,,The company was taken over
La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).,,The connection is not encrypted: over the Internet use a TLS reverse proxy (wss://).
La controlli da,,You have controlled it for
La partita è in corso: questa è la storia finora. La Cronaca finale arriva quando la tua compagnia esce di scena.,,The game is still running: this is the story so far. The final chronicle comes when your company leaves the stage.
La quotazione si sblocca al livello,,Listing unlocks at level
"La storia della tua compagnia finora: grafici, primati, fatti salienti e prestigio.",,"Your company's story so far: charts, records, highlights and prestige."
La tua compagnia,,Your company
La tua compagnia è il bersaglio. Difese: riacquisto del flottante con la cassa; dividendo straordinario del,,Your company is the target. Defences: buy back the free float with cash; extra dividend of
La tua offerta: gli azionisti aderiscono ogni giorno finché l'obiettivo non è raggiunto o l'offerta scade.,,Your bid: shareholders tender every day until the target is reached or the bid expires.
Lancia l'offerta,,Launch the bid
Lavoratori,,Workers
Lavoratori e personale,,Workers and staff
Le azioni tornano al fondatore e alzano la tua quota.,,Shares return to the founder and raise your stake.
Le scalate ostili si sbloccano al livello,,Hostile takeovers unlock at level
Libro dei soci,,Shareholder register
Linea,,Line
Linee,,Lines
Linee della compagnia,,Company lines
Listino,,Share list
Listino del,,Share list of
Liv.,,Lvl
Livello,,Level
Lo storico si forma alla fine di ogni mese,,History builds up at the end of each month
Locomotiva,,Locomotive
Lunghezza,,Length
Macchinari,,Machinery
Manda al deposito,,Send to depot
Manutenzione,,Maintenance
Manutenzione al giorno,,Maintenance per day
Mappa di calore della condizione,,Condition heat map
Margine,,Margin
Mercato,,Market
Mercato (flottante),,Market (free float)
Merci e passeggeri in attesa,,Waiting goods and passengers
Miglior offerta,,Best offer
Minimappa,,Minimap
Nel bacino,,In the catchment
Nessun anno concluso: lo storico si scrive a fine anno.,,No year closed yet: history is written at year end.
Nessun anno registrato,,No year recorded
Nessun fermo finora,,No shutdowns so far
Nessun posto di lavoro servito dai tuoi treni.,,No workplace served by your trains.
Nessun tracciato,,No route
Nessun treno in officina,,No trains in the workshop
Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno.,,No agreements: industries offer one when your trains carry at least 20 commuters a day.
Nessuna linea,,No line
Nessuna offerta in corso. Un'offerta dura,,No open bids. A bid lasts
Nessuno,,None
Nome automatico,,Automatic name
Nome del treno,,Train name
Nome della linea,,Line name
Non quotata: le sue azioni non sono sul mercato.,,Not listed: its shares are not on the market.
Notizie,,News
Numero di azioni,,Number of shares
Nuova mappa con la difficoltà,,New map at difficulty
Nuova partita+,,New game+
Nuova partita+ in preparazione,,Preparing New game+
Offerta pubblica di acquisto,,Takeover bid
Offerte pubbliche in corso,,Open takeover bids
Officine,,Workshops
Offri all'asta,,Bid at auction
Oggi il fondatore ha il,,The founder now holds
"Ogni mese le città mandano i loro lavoratori alle industrie e ai depositi raggiungibili con i tuoi treni entro 60 minuti (personale: 90). Qui vedi da dove arrivano, quanti posti restano scoperti e perché.",,"Every month towns send their workers to the industries and depots your trains reach within 60 minutes (staff: 90). Here you see where they come from, how many jobs stay vacant and why."
Operazioni,,Actions
Ordina,,Order
Ordina ricambi,,Order parts
Paga dividendo,,Pay dividend
Partita conclusa,,Game over
Partita conclusa: sei un osservatore. Il mondo va avanti e le compagnie IA continuano a giocare.,,Game over: you are an observer. The world goes on and the AI companies keep playing.
Partita locale,,Local game
Partita locale non avviata,,Local game not started
Patrimonio,,Net worth
Patrimonio netto,,Net worth
Patrimonio netto anno per anno,,Net worth year by year
Pausa,,Pause
Pendenza massima,,Max gradient
Personale,,Staff
@@ -110,74 +218,156 @@ Politica della flotta,,Fleet policy
Ponte,,Bridge
Ponti,,Bridges
Posti di lavoro,,Workplaces
Predatoria,,Predatory
Premio,,Premium
Prenotato,,Booked
Prestigio,,Prestige
Prestito,,Loan
Prezzi globali di oggi (la borsa arriva in seguito).,,Today's global prices (the stock market comes later).
Prezzo chiesto dai proprietari,,Asking price
Prezzo dell'azione a fine mese,,Month-end share price
Prezzo per azione,,Share price
Prezzo · var.,,Price · chg.
Primati,,Records
Produce,,Produces
Proprietari privati,,Private owners
Proprietà,,Owner
Prossimo intervento,,Next intervention
Prudente,,Prudent
Quota obiettivo,,Target stake
Quota rispetto al terreno,,Height above ground
Quotati in borsa,,Go public
Quotazione in borsa,,Stock market listing
Quote sulle,,Stakes of the
Raggio minimo,,Min radius
Rating,,Rating
Recupero,,Recovery
Recupero al giorno,,Recovery per day
Regione di,,Region of
Registro degli impieghi,,Employment register
Registro in arrivo dal server…,,Register on its way from the server…
Registro officina,,Workshop register
Resa impianti,,Plant output
Revisione,,Overhaul
Revisione programmata,,Overhaul scheduled
Riacquista,,Buy back
Riacquista almeno il,,Buy back at least
Riacquista azioni,,Buy back shares
Riacquisto,,Buyback
Riacquisto di azioni proprie,,Own share buyback
Ricambi,,Spare parts
Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.,,Spare parts to order beyond the policy stock: they become explicit demand on your lines.
Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto.,,Spare parts exhausted: interventions are waiting. Bring parts by train from a machine factory or a port.
Ricambi extra,,Extra parts
Ricambi già destinati,,Parts already allocated
Ricavi,,Revenue
Rifiuta,,Reject
Rilevato,,Embankment
Riscatto non riuscito in tempo,,Buyback not completed in time
Rischio di fermo in un anno,,Breakdown risk within a year
Ritira l'adesione,,Withdraw acceptance
Ritmo di lavoro (manca personale),,Work rate (staff shortage)
Rosso coppo,,Tile red
"Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute.",,Pick an industry from the list or on the map. Plants wear out with use: the maintenance budget and the spare parts and machinery brought by train keep them healthy.
Scegli una compagnia nel listino,,Pick a company from the list
"Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda.",,"Pick a tool on the left or click a train, station, industry or town to see its card."
Scheda del proprietario,,Owner's card
Scheda in arrivo dal server…,,Card on its way from the server…
Scorta desiderata,,Target stock
Scorte,,Stock
Se la capacità manca per 30 giorni la convenzione salta con una penale.,,If capacity falls short for 30 days the agreement breaks with a penalty.
Segnali,,Signals
Seleziona i veicoli da comporre,,Select the vehicles to compose
Seleziona un treno,,Select a train
Seleziona un treno e un deposito,,Select a train and a depot
Sentiment del mercato,,Market sentiment
Serve un deposito,,A depot is required
Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH.,,Local server not found: build src/ViaFerrea.Server or set VF_SERVER_PATH.
Servizi,,Services
Servono almeno due fermate,,At least two stops are needed
Soddisfazione,,Satisfaction
Sopra il,,Above
Spesa di manutenzione nell'anno,,Maintenance spent this year
Spread,,Spread
Stalli,,Stalls
Stato,,Status
Stazione,,Station
Storico,,History
Storico annuale,,Yearly history
Storico dei fermi,,Shutdown history
Svuota,,Clear
Token,,Token
Token del server,,Server token
Torna al menu,,Back to menu
Torna alla partita,,Back to the game
Totale,,Total
Treni,,Trains
Treni della compagnia,,Company trains
Treno di riserva in deposito,,Reserve train in depot
Trincea,,Cutting
Tua quota,,Your stake
Usura al giorno,,Wear per day
Utile,,Profit
Utile annuo,,Annual profit
Veicoli,,Vehicles
"Veicoli liberi nel deposito (selezione multipla, in ordine)",,"Free vehicles in the depot (multiple selection, in order)"
Velocità,,Speed
Vendi,,Sell
Verde,,Green
Via Ferrea,,Via Ferrea
a piedi,,on foot
abitanti,,inhabitants
agli azionisti; i dividendi alzano il sentiment del titolo.,,to shareholders; dividends raise the share's sentiment.
al 20% e si fermano più spesso.,,at 20% and stop more often.
al massimo il,,at most
al mese,,per month
altrimenti la partita finisce. Intanto versi il,,or the game ends. Meanwhile you pay
amministrazione controllata,,receivership
anni,,years
attende,,waiting for
attende i ricambi,,waiting for parts
attendi il pieno,,wait for full load
azioni,,shares
azioni in circolazione: oltre il,,outstanding shares: above
capacità delle carrozze insufficiente sulla,,not enough coach capacity on
capacità mancante da,,capacity short for
carica,,load
cavaliere bianco,,white knight
città senza servizi per il personale,,towns without services for staff
consumo,,use
controlla la compagnia,,controls the company
controllata da,,controlled by
copertura,,coverage
da,,from
degli utili come dividendo e non puoi chiedere prestiti.,,of profits as dividends and cannot take new loans.
dei ricavi,,of revenue
del capitale,,of the capital
del capitale per ordine.,,of the capital per order.
della cassa (il titolo sale); cavaliere bianco: un'alleata compra il flottante al prezzo dell'offerta più il,,of cash (the share price rises); white knight: an ally buys the free float at the bid price plus
delle azioni entro il,,of the shares by
di,,of
dividendo straordinario,,extra dividend
durata,,duration
e il,,and
e personale sufficiente,,and enough staff
fallita,,bankrupt
"fallita, attivi all'asta",,"bankrupt, assets at auction"
ferma,,stopped
ferma fino al,,stopped until
fermo in linea,,stranded on the line
fermo in salita,,stalled on grade
g,,d
giorni,,days
giorni di fermo,,days of shutdown
giorni e liquida le minoranze al prezzo di mercato.,,days and buys out the minorities at market price.
giorni e offre un premio tra il,,days and offers a premium between
giorno,,day
gli impianti rendono pieno; sotto calano fino a,,plants run at full output; below they drop to
guasto,,broken down
guasto lieve,,minor failure
hub mercato mondiale,,world market hub
il fondatore ha,,the founder holds
impegnato,,committed
in arrivo,,arriving
in attesa,,waiting
in attesa di via libera,,waiting for clearance
@@ -185,32 +375,70 @@ in coda,,queued
in deposito,,in depot
in marcia,,running
in officina,,in the workshop
in scorta,,in stock
in servizio,,in service
in stazione,,at station
incasso stimato,,estimated proceeds
intervento prenotato,,intervention booked
la fusione è possibile dopo,,the merger is possible after
la tua compagnia,,your company
large,Grande,Large
lavoratori,,workers
lavori,,jobs
le città raggiungibili non hanno lavoratori liberi,,reachable towns have no free workers
linea,,line
livello,,level
macchinari,,machinery
macchinari per il prossimo lavoro,,machinery for the next job
macchinari per livello,,machinery per level
medium,Medio,Medium
mesi,,months
mila km,,thousand km
nessuna,,none
nessuna città raggiungibile entro,,no town reachable within
nessuna stazione serve il posto di lavoro,,no station serves the workplace
non quotata,,not listed
non è in vendita.,,not for sale.
obiettivo,,target
ordinati in più,,extra ordered
ore,,hours
per,,for
per azione,,per share
personale,,staff
personale almeno al,,staff at least at
portafoglio azioni,,share portfolio
possiedi,,you hold
posti al giorno garantiti,,guaranteed seats a day
privati,,private
punti al giorno,,points per day
quotata,,listed
respinta dal consiglio,,rejected by the board
riacquisto,,buyback
ricambi,,parts
ricambi al mese per livello,,spare parts per month per level
rimorchiato,,towed
riporta la condizione a 100.,,restores condition to 100.
riserva,,reserve
scade il,,expires on
scaduta,,overdue
scaduto,,overdue
scarica,,unload
scorta della politica,,policy stock
senza linea,,no line
senza percorso,,no route
servono,,needs
si controlla la compagnia.,,you control the company.
small,Piccolo,Small
soccorso tra,,rescue in
stallo,,stall
sul mercato,,on the market
sul prezzo di mercato.,,over the market price.
tecnici,,staff
tra,,in
treni,,trains
tu,,you
tua,,yours
ultimi,,last
vincitore,,winner
"volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.",,"times annual profit, divided by the shares and multiplied by market sentiment."
⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto.,,⚠ Out of spare parts: plant recovery is halved. Bring them by train from a machinery factory or a port.
1 keys it en
2 Abitanti Population
3 Accetta Accept
4 Acquista Buy
5 Aderisci con le tue azioni Tender your shares
6 Aggiorna Refresh
7 Alto High
8 Ambra Amber
9 Amministrazione controllata Receivership
10 Ammoderna Upgrade
11 Ammodernamento Upgrade
12 Ammodernamento di livello Level upgrade
13 Ammodernamento programmato Upgrade scheduled
14 Ancora nessun fatto da raccontare. Nothing to tell yet.
15 Anno Year
16 Annulla Cancel
17 Anteprima non disponibile: Preview unavailable:
18 Appartiene a Belongs to
19 Assegna Assign
20 Asta degli attivi Asset auction
21 Attendi il pieno alla prima fermata (max 2 giorni) Wait for full load at the first stop (max 2 days)
22 Attiva Active
23 Avvio del server locale… Starting the local server…
24 Azioni proprie (non votano) Treasury shares (no vote)
25 Base Base
26 Base d'asta Reserve price
27 Binari Track
28 Binari di stazione Platforms
29 Blu Blue
30 Budget di manutenzione Maintenance budget
31 C'è già un'offerta in corso su questa compagnia: la trovi nell'elenco a sinistra. There is already a bid on this company: see the list on the left.
32 Cantiere Construction
33 Capitalizz. Market cap
34 Capitalizzazione Market cap
35 Carico Load
36 Cartella di manutenzione Maintenance record
37 Cartella in arrivo dal server… Record on its way from the server…
38 Cassa Cash
39 Cassa dell'industria Industry cash
40 Cavaliere bianco White knight
41 Celeste Light blue
42 Chi offre di più alla chiusura compra treni, binari, stazioni e industrie della compagnia fallita. The highest bidder at closing buys the bankrupt company's trains, track, stations and industries.
43 Chiedi il prestito Request loan
44 Chiudi Close
45 Chiusa Closed
46 Chiusura Closes
47 Classe Class
48 Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea. Click a track to place a block signal: it splits the edge into sections and raises line capacity.
49 Clic su una compagnia per la scheda, il libro dei soci e le operazioni. Prezzo per azione: il maggiore tra patrimonio netto e Click a company for its card, shareholder register and actions. Share price: the greater of net worth and
50 Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo. Click a station, depot or free track to demolish it; part of the cost is refunded.
51 Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare. Click the map to place route points (Shift: no 45° snap), Enter to build, right click to cancel.
52 Clic sulla mappa vicino a un binario, poi raccordalo con lo strumento Binari. Nel deposito si comprano i veicoli e si compongono i treni. Click the map near a track, then connect it with the Track tool. Vehicles are bought and trains composed in the depot.
56 Collegamento non riuscito Connection failed
57 Collegati Connect
58 Collegati a un server Connect to a server
59 Colloca il Float
60 Come la linea o la flotta Same as line or fleet
61 Compagnia Company
62 Compagnia fallita: nessuna asta in corso. Bankrupt company: no auction running.
63 Compagnie Companies
64 Compagnie e borsa Companies and stock exchange
65 Componi Compose
66 Compra Buy
67 Compra veicoli Buy vehicles
68 Compravendita di azioni Share trading
69 Condizione Condition
70 Connessione persa Connection lost
71 Consuma Consumes
72 Continua come osservatore Continue as observer
73 Controllo Control
74 Controvalore Value
75 Convenzioni Agreements
76 Coperto dalla riserva Covered by reserve
77 Costi dell'anno Costs this year
78 Costo Cost
79 Costo dell'ammodernamento Upgrade cost
80 Costruisci Build
81 Crea linea Create line
82 Cronaca finale Final chronicle
83 Cronaca provvisoria Chronicle so far
84 Dati del gioco non trovati o non validi. Game data missing or invalid.
85 Dati insufficienti Not enough data
86 Debito Debt
87 Demolisci Demolish
88 Depositi e officine Depots and workshops
89 Deposito Depot
90 Deragliamento Derailment
91 Difese del bersaglio Target's defences
92 Disconnesso Disconnected
93 Dividendi (12 mesi) Dividends (12 months)
94 Dividendo Dividend
95 Dividendo per azione Dividend per share
96 Dividendo straordinario Extra dividend
97 Doppio binario Double track
98 Dove lavorano gli abitanti Where residents work
99 Efficienza Efficiency
100 Elettrificato Electrified
101 Esci Quit
102 Espansiva Expansive
103 Fallimento Bankruptcy
104 Fatti salienti Highlights
105 Fermo Shutdown
106 Fermo programmato Planned shutdown
107 Finanze Finance
108 Flotta, dal treno più usurato Fleet, most worn first
109 Fondatore (tu) Founder (you)
110 Fondatore privato Private founder
111 Fusione Merger
112 Galleria Tunnel
113 Gallerie Tunnels
114 Gestionale ferroviario dall'alto Top-down railway management
115 Gestisci l'industria Manage the industry
116 Grano Wheat
117 Guasti nell'anno Failures this year
118 Guasto Breakdown
119 Guasto grave Major failure
120 Guasto lieve Minor failure
121 Hai aderito con tutte le tue azioni. You tendered all your shares.
122 Il mondo continua: le compagnie IA giocano e puoi guardarle come osservatore, ma il server non accetta più i tuoi comandi. The world goes on: AI companies keep playing and you can watch as an observer, but the server no longer accepts your commands.
123 Il server non risponde più. La partita continua sul server. The server is not responding. The game goes on on the server.
124 Impegno massimo Maximum commitment
125 Impianti Plant
126 Impieghi Jobs
127 In amministrazione controllata compri anche dal controllante, con il premio di riscatto. In receivership you also buy from the controller, at the ransom premium.
128 In attesa del listino del giorno… Waiting for today's share list…
129 In vendita For sale
130 Incidente grave Serious accident
131 Incorpora la controllata Merge the subsidiary
132 Indica l'indirizzo del server Enter the server address
133 Indietro Back
134 Indirizzo (host:porta) Address (host:port)
135 Indirizzo non valido Invalid address
136 Industrie Industries
137 Km di binari Track km
138 Km di servizio al giorno Service km per day
139 L'acquisto di industrie si sblocca al livello Buying industries unlocks at level
140 La compagnia è stata scalata The company was taken over
141 La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://). The connection is not encrypted: over the Internet use a TLS reverse proxy (wss://).
142 La controlli da You have controlled it for
143 La partita è in corso: questa è la storia finora. La Cronaca finale arriva quando la tua compagnia esce di scena. The game is still running: this is the story so far. The final chronicle comes when your company leaves the stage.
144 La quotazione si sblocca al livello Listing unlocks at level
145 La storia della tua compagnia finora: grafici, primati, fatti salienti e prestigio. Your company's story so far: charts, records, highlights and prestige.
146 La tua compagnia Your company
147 La tua compagnia è il bersaglio. Difese: riacquisto del flottante con la cassa; dividendo straordinario del Your company is the target. Defences: buy back the free float with cash; extra dividend of
148 La tua offerta: gli azionisti aderiscono ogni giorno finché l'obiettivo non è raggiunto o l'offerta scade. Your bid: shareholders tender every day until the target is reached or the bid expires.
149 Lancia l'offerta Launch the bid
150 Lavoratori Workers
151 Lavoratori e personale Workers and staff
152 Le azioni tornano al fondatore e alzano la tua quota. Shares return to the founder and raise your stake.
153 Le scalate ostili si sbloccano al livello Hostile takeovers unlock at level
154 Libro dei soci Shareholder register
155 Linea Line
156 Linee Lines
157 Linee della compagnia Company lines
158 Listino Share list
159 Listino del Share list of
160 Liv. Lvl
161 Livello Level
162 Lo storico si forma alla fine di ogni mese History builds up at the end of each month
163 Locomotiva Locomotive
164 Lunghezza Length
165 Macchinari Machinery
166 Manda al deposito Send to depot
167 Manutenzione Maintenance
168 Manutenzione al giorno Maintenance per day
169 Mappa di calore della condizione Condition heat map
170 Margine Margin
171 Mercato Market
172 Mercato (flottante) Market (free float)
173 Merci e passeggeri in attesa Waiting goods and passengers
174 Miglior offerta Best offer
175 Minimappa Minimap
176 Nel bacino In the catchment
177 Nessun anno concluso: lo storico si scrive a fine anno. No year closed yet: history is written at year end.
178 Nessun anno registrato No year recorded
179 Nessun fermo finora No shutdowns so far
180 Nessun posto di lavoro servito dai tuoi treni. No workplace served by your trains.
181 Nessun tracciato No route
182 Nessun treno in officina No trains in the workshop
183 Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno. No agreements: industries offer one when your trains carry at least 20 commuters a day.
184 Nessuna linea No line
185 Nessuna offerta in corso. Un'offerta dura No open bids. A bid lasts
186 Nessuno None
187 Nome automatico Automatic name
188 Nome del treno Train name
189 Nome della linea Line name
190 Non quotata: le sue azioni non sono sul mercato. Not listed: its shares are not on the market.
191 Notizie News
192 Numero di azioni Number of shares
193 Nuova mappa con la difficoltà New map at difficulty
194 Nuova partita+ New game+
195 Nuova partita+ in preparazione Preparing New game+
196 Offerta pubblica di acquisto Takeover bid
197 Offerte pubbliche in corso Open takeover bids
198 Officine Workshops
199 Offri all'asta Bid at auction
200 Oggi il fondatore ha il The founder now holds
201 Ogni mese le città mandano i loro lavoratori alle industrie e ai depositi raggiungibili con i tuoi treni entro 60 minuti (personale: 90). Qui vedi da dove arrivano, quanti posti restano scoperti e perché. Every month towns send their workers to the industries and depots your trains reach within 60 minutes (staff: 90). Here you see where they come from, how many jobs stay vacant and why.
202 Operazioni Actions
203 Ordina Order
204 Ordina ricambi Order parts
205 Paga dividendo Pay dividend
206 Partita conclusa Game over
207 Partita conclusa: sei un osservatore. Il mondo va avanti e le compagnie IA continuano a giocare. Game over: you are an observer. The world goes on and the AI companies keep playing.
208 Partita locale Local game
209 Partita locale non avviata Local game not started
210 Patrimonio Net worth
211 Patrimonio netto Net worth
212 Patrimonio netto anno per anno Net worth year by year
213 Pausa Pause
214 Pendenza massima Max gradient
215 Personale Staff
218 Ponte Bridge
219 Ponti Bridges
220 Posti di lavoro Workplaces
221 Predatoria Predatory
222 Premio Premium
223 Prenotato Booked
224 Prestigio Prestige
225 Prestito Loan
226 Prezzi globali di oggi (la borsa arriva in seguito). Today's global prices (the stock market comes later).
227 Prezzo chiesto dai proprietari Asking price
228 Prezzo dell'azione a fine mese Month-end share price
229 Prezzo per azione Share price
230 Prezzo · var. Price · chg.
231 Primati Records
232 Produce Produces
233 Proprietari privati Private owners
234 Proprietà Owner
235 Prossimo intervento Next intervention
236 Prudente Prudent
237 Quota obiettivo Target stake
238 Quota rispetto al terreno Height above ground
239 Quotati in borsa Go public
240 Quotazione in borsa Stock market listing
241 Quote sulle Stakes of the
242 Raggio minimo Min radius
243 Rating Rating
244 Recupero Recovery
245 Recupero al giorno Recovery per day
246 Regione di Region of
247 Registro degli impieghi Employment register
248 Registro in arrivo dal server… Register on its way from the server…
249 Registro officina Workshop register
250 Resa impianti Plant output
251 Revisione Overhaul
252 Revisione programmata Overhaul scheduled
253 Riacquista Buy back
254 Riacquista almeno il Buy back at least
255 Riacquista azioni Buy back shares
256 Riacquisto Buyback
257 Riacquisto di azioni proprie Own share buyback
258 Ricambi Spare parts
259 Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee. Spare parts to order beyond the policy stock: they become explicit demand on your lines.
260 Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto. Spare parts exhausted: interventions are waiting. Bring parts by train from a machine factory or a port.
261 Ricambi extra Extra parts
262 Ricambi già destinati Parts already allocated
263 Ricavi Revenue
264 Rifiuta Reject
265 Rilevato Embankment
266 Riscatto non riuscito in tempo Buyback not completed in time
267 Rischio di fermo in un anno Breakdown risk within a year
268 Ritira l'adesione Withdraw acceptance
269 Ritmo di lavoro (manca personale) Work rate (staff shortage)
270 Rosso coppo Tile red
271 Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute. Pick an industry from the list or on the map. Plants wear out with use: the maintenance budget and the spare parts and machinery brought by train keep them healthy.
272 Scegli una compagnia nel listino Pick a company from the list
273 Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda. Pick a tool on the left or click a train, station, industry or town to see its card.
274 Scheda del proprietario Owner's card
275 Scheda in arrivo dal server… Card on its way from the server…
276 Scorta desiderata Target stock
277 Scorte Stock
278 Se la capacità manca per 30 giorni la convenzione salta con una penale. If capacity falls short for 30 days the agreement breaks with a penalty.
279 Segnali Signals
280 Seleziona i veicoli da comporre Select the vehicles to compose
281 Seleziona un treno Select a train
282 Seleziona un treno e un deposito Select a train and a depot
283 Sentiment del mercato Market sentiment
284 Serve un deposito A depot is required
285 Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH. Local server not found: build src/ViaFerrea.Server or set VF_SERVER_PATH.
286 Servizi Services
287 Servono almeno due fermate At least two stops are needed
288 Soddisfazione Satisfaction
289 Sopra il Above
290 Spesa di manutenzione nell'anno Maintenance spent this year
291 Spread Spread
292 Stalli Stalls
293 Stato Status
294 Stazione Station
295 Storico History
296 Storico annuale Yearly history
297 Storico dei fermi Shutdown history
298 Svuota Clear
299 Token Token
300 Token del server Server token
301 Torna al menu Back to menu
302 Torna alla partita Back to the game
303 Totale Total
304 Treni Trains
305 Treni della compagnia Company trains
306 Treno di riserva in deposito Reserve train in depot
307 Trincea Cutting
308 Tua quota Your stake
309 Usura al giorno Wear per day
310 Utile Profit
311 Utile annuo Annual profit
312 Veicoli Vehicles
313 Veicoli liberi nel deposito (selezione multipla, in ordine) Free vehicles in the depot (multiple selection, in order)
314 Velocità Speed
315 Vendi Sell
316 Verde Green
317 Via Ferrea Via Ferrea
318 a piedi on foot
319 abitanti inhabitants
320 agli azionisti; i dividendi alzano il sentiment del titolo. to shareholders; dividends raise the share's sentiment.
321 al 20% e si fermano più spesso. at 20% and stop more often.
322 al massimo il at most
323 al mese per month
324 altrimenti la partita finisce. Intanto versi il or the game ends. Meanwhile you pay
325 amministrazione controllata receivership
326 anni years
327 attende waiting for
328 attende i ricambi waiting for parts
329 attendi il pieno wait for full load
330 azioni shares
331 azioni in circolazione: oltre il outstanding shares: above
332 capacità delle carrozze insufficiente sulla not enough coach capacity on
333 capacità mancante da capacity short for
334 carica load
335 cavaliere bianco white knight
336 città senza servizi per il personale towns without services for staff
337 consumo use
338 controlla la compagnia controls the company
339 controllata da controlled by
340 copertura coverage
341 da from
342 degli utili come dividendo e non puoi chiedere prestiti. of profits as dividends and cannot take new loans.
343 dei ricavi of revenue
344 del capitale of the capital
345 del capitale per ordine. of the capital per order.
346 della cassa (il titolo sale); cavaliere bianco: un'alleata compra il flottante al prezzo dell'offerta più il of cash (the share price rises); white knight: an ally buys the free float at the bid price plus
347 delle azioni entro il of the shares by
348 di of
349 dividendo straordinario extra dividend
350 durata duration
351 e il and
352 e personale sufficiente and enough staff
353 fallita bankrupt
354 fallita, attivi all'asta bankrupt, assets at auction
355 ferma stopped
356 ferma fino al stopped until
357 fermo in linea stranded on the line
358 fermo in salita stalled on grade
359 g d
360 giorni days
361 giorni di fermo days of shutdown
362 giorni e liquida le minoranze al prezzo di mercato. days and buys out the minorities at market price.
363 giorni e offre un premio tra il days and offers a premium between
364 giorno day
365 gli impianti rendono pieno; sotto calano fino a plants run at full output; below they drop to
366 guasto broken down
367 guasto lieve minor failure
368 hub mercato mondiale world market hub
369 il fondatore ha the founder holds
370 impegnato committed
371 in arrivo arriving
372 in attesa waiting
373 in attesa di via libera waiting for clearance
375 in deposito in depot
376 in marcia running
377 in officina in the workshop
378 in scorta in stock
379 in servizio in service
380 in stazione at station
381 incasso stimato estimated proceeds
382 intervento prenotato intervention booked
383 la fusione è possibile dopo the merger is possible after
384 la tua compagnia your company
385 large Grande Large
386 lavoratori workers
387 lavori jobs
388 le città raggiungibili non hanno lavoratori liberi reachable towns have no free workers
389 linea line
390 livello level
391 macchinari machinery
392 macchinari per il prossimo lavoro machinery for the next job
393 macchinari per livello machinery per level
394 medium Medio Medium
395 mesi months
396 mila km thousand km
397 nessuna none
398 nessuna città raggiungibile entro no town reachable within
399 nessuna stazione serve il posto di lavoro no station serves the workplace
400 non quotata not listed
401 non è in vendita. not for sale.
402 obiettivo target
403 ordinati in più extra ordered
404 ore hours
405 per for
406 per azione per share
407 personale staff
408 personale almeno al staff at least at
409 portafoglio azioni share portfolio
410 possiedi you hold
411 posti al giorno garantiti guaranteed seats a day
412 privati private
413 punti al giorno points per day
414 quotata listed
415 respinta dal consiglio rejected by the board
416 riacquisto buyback
417 ricambi parts
418 ricambi al mese per livello spare parts per month per level
419 rimorchiato towed
420 riporta la condizione a 100. restores condition to 100.
421 riserva reserve
422 scade il expires on
423 scaduta overdue
424 scaduto overdue
425 scarica unload
426 scorta della politica policy stock
427 senza linea no line
428 senza percorso no route
429 servono needs
430 si controlla la compagnia. you control the company.
431 small Piccolo Small
432 soccorso tra rescue in
433 stallo stall
434 sul mercato on the market
435 sul prezzo di mercato. over the market price.
436 tecnici staff
437 tra in
438 treni trains
439 tu you
440 tua yours
441 ultimi last
442 vincitore winner
443 volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato. times annual profit, divided by the shares and multiplied by market sentiment.
444 ⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto. ⚠ Out of spare parts: plant recovery is halved. Bring them by train from a machinery factory or a port.
@@ -14,7 +14,9 @@ namespace ViaFerrea.Client.App;
/// <summary>
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): nella partita
/// locale costruisce stazioni, deposito e una linea con ponte usando l'anteprima, compra un treno,
/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo.
/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo; poi apre
/// officine e impieghi (F4), la scheda del proprietario di un'industria, «Compagnie e borsa» e la
/// Cronaca provvisoria (F5).
/// </summary>
public partial class AutoPilot : Node
{
@@ -73,6 +75,18 @@ public partial class AutoPilot : Node
return r.Created.Length > 0 ? r.Created[0] : -1;
}
/// <summary>Attende una condizione al massimo per il tempo indicato, senza fallire.</summary>
private async Task<bool> Wait(Func<bool> condition, double timeoutS)
{
ulong start = Time.GetTicksMsec();
while (!condition())
{
if (Time.GetTicksMsec() - start > timeoutS * 1000) return false;
await Frame();
}
return true;
}
private async Task Shot(string name, int settleFrames = 30)
{
for (int i = 0; i < settleFrames; i++) await Frame();
@@ -184,5 +198,46 @@ public partial class AutoPilot : Node
_game.UseTool(Tool.Employment);
await Until(() => World.Employment is not null, "registro degli impieghi", 30);
await Shot("11_impieghi", 30);
await IndustriesAndMarket(site.A);
}
/// <summary>F5: scheda del proprietario di un'industria, borsa con il libro dei soci, Cronaca provvisoria.</summary>
private async Task IndustriesAndMarket(Vec2 near)
{
int me = World.Summary!.CompanyId;
var anchor = MapScale.V(near);
var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0)
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First();
_game.OpenIndustry(industry.Id);
await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30);
// al livello iniziale il server rifiuta l'acquisto: il messaggio compare sulla mappa
var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation));
GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}");
_game.Map.CenterOn(MapScale.V(industry.Position));
_game.Map.SetZoom(0.3f);
await Shot("12_industria", 40);
_game.ScrollPanel(1);
await Shot("12b_industria_scorte", 20);
_game.ScrollPanel(0);
// borsa: azioni di una compagnia IA, qualche mese di prezzi, poi listino e libro dei soci
var ai = World.Companies.Values.Where(c => !c.IsPlayer && c.Listed && !c.Bankrupt).OrderBy(c => c.Id).FirstOrDefault();
if (ai is not null) await Ok(new BuySharesCommand(new CompanyId(ai.Id), 20_000, Money.Zero));
_game.OpenCompanies(ai?.Id ?? me);
Session.SetSpeed(8);
bool history = await Wait(() => ai is null || (World.CompanyCards.TryGetValue(ai.Id, out var card) && card.PriceHistory.Count >= 3), 200);
if (!history) GD.Print("autopilot: storico dei prezzi ancora corto");
Session.SetSpeed(1);
await Until(() => World.Tape is not null, "listino di borsa", 60);
await Shot("13_compagnie", 60);
_game.OpenCompanies(me);
await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
await Shot("14_compagnia_giocatore", 40);
// Cronaca provvisoria
_game.OpenChronicle();
await Until(() => _game.ChronicleVisible, "cronaca", 30);
await Shot("15_cronaca", 30);
}
}
+34 -3
View File
@@ -12,6 +12,15 @@ public static class UiTheme
public static Font BodyBold { get; private set; } = ThemeDB.FallbackFont;
public static Font Title { get; private set; } = ThemeDB.FallbackFont;
/// <summary>
/// Tema costruito da <see cref="Build"/>. Il tema della finestra non attraversa i nodi che non
/// sono Control (Main, CanvasLayer): ogni radice dell'interfaccia lo riceve con <see cref="Apply"/>.
/// </summary>
public static Theme? Current { get; private set; }
/// <summary>Assegna il tema a una radice dell'interfaccia (figlia di un nodo che non è un Control).</summary>
public static void Apply(Control root) => root.Theme = Current;
public static Theme Build()
{
Body = LoadFont("res://assets/fonts/IBMPlexSans-Regular.ttf");
@@ -35,22 +44,44 @@ public static class UiTheme
t.SetStylebox("pressed", "Button", Box(Palette.Amber, Palette.Amber, 8, 10));
t.SetStylebox("disabled", "Button", Box(Palette.AppBackground, Palette.Border, 8, 10));
t.SetStylebox("focus", "Button", Box(new Color(0, 0, 0, 0), Palette.AmberLight, 8, 10));
// pulsanti in IBM Plex Sans 600 come nell'immagine 05
t.SetFont("font", "Button", BodyBold);
t.SetColor("font_pressed_color", "Button", Palette.AppBackground);
t.SetColor("font_hover_color", "Button", Palette.Text);
t.SetColor("font_disabled_color", "Button", Palette.TextSecondary);
t.SetColor("font_hover_pressed_color", "Button", Palette.AppBackground);
// caselle e interruttori: niente riquadro da pulsante (altrimenti ereditano quello di Button)
var plain = new StyleBoxEmpty { ContentMarginLeft = 4, ContentMarginRight = 4, ContentMarginTop = 2, ContentMarginBottom = 2 };
foreach (string type in new[] { "CheckBox", "CheckButton" })
{
foreach (string state in new[] { "normal", "pressed", "hover", "hover_pressed", "disabled", "focus" }) t.SetStylebox(state, type, plain);
t.SetColor("font_pressed_color", type, Palette.Text);
t.SetColor("font_hover_color", type, Palette.Text);
t.SetColor("font_hover_pressed_color", type, Palette.Text);
t.SetFont("font", type, Body);
}
t.SetStylebox("normal", "LineEdit", Box(Palette.Inner, Palette.Border, 8, 8));
t.SetStylebox("focus", "LineEdit", Box(Palette.Inner, Palette.Amber, 8, 8));
t.SetColor("caret_color", "LineEdit", Palette.Amber);
t.SetStylebox("panel", "ItemList", Box(Palette.Inner, Palette.Border, 8, 6));
t.SetColor("font_selected_color", "ItemList", Palette.AppBackground);
t.SetStylebox("selected", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
t.SetStylebox("selected_focus", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
// selezione su ambra scuro: restano leggibili anche le voci colorate (condizione, proprietario)
t.SetColor("font_selected_color", "ItemList", Palette.AmberLight);
t.SetStylebox("selected", "ItemList", Box(Palette.AmberDark, Palette.Amber, 4, 4));
t.SetStylebox("selected_focus", "ItemList", Box(Palette.AmberDark, Palette.Amber, 4, 4));
// cursori: binario vuoto e parte piena in ambra
var track = Box(Palette.Border, Palette.Border, 3, 0);
track.ContentMarginTop = track.ContentMarginBottom = 3;
t.SetStylebox("slider", "HSlider", track);
t.SetStylebox("grabber_area", "HSlider", Box(Palette.Amber, Palette.Amber, 3, 0));
t.SetStylebox("grabber_area_highlight", "HSlider", Box(Palette.AmberLight, Palette.AmberLight, 3, 0));
t.SetStylebox("background", "ProgressBar", Box(Palette.Border, Palette.Border, 4, 0));
t.SetStylebox("fill", "ProgressBar", Box(Palette.Workers, Palette.Workers, 4, 0));
t.SetColor("font_color", "ProgressBar", Palette.Text);
Current = t;
return t;
}
+32 -8
View File
@@ -5,9 +5,12 @@ using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Market, Finance, Demolish }
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Finance, Demolish }
/// <summary>Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto.</summary>
/// <summary>
/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto. I pulsanti
/// sono compatti e la colonna scorre con la rotella se la finestra è più bassa della barra.
/// </summary>
public partial class Toolbar : PanelContainer
{
private readonly Dictionary<Tool, ToolButton> _buttons = [];
@@ -20,14 +23,22 @@ public partial class Toolbar : PanelContainer
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 6));
CustomMinimumSize = new Vector2(88, 0);
var scroll = new ScrollContainer
{
HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled,
VerticalScrollMode = ScrollContainer.ScrollMode.ShowNever,
SizeFlagsVertical = SizeFlags.ExpandFill,
};
AddChild(scroll);
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 6);
AddChild(col);
col.AddThemeConstantOverride("separation", 4);
scroll.AddChild(col);
foreach (var (tool, label) in new[]
{
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
(Tool.Market, "Mercato"), (Tool.Finance, "Finanze"), (Tool.Demolish, "Demolisci"),
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Finance, "Finanze"),
(Tool.Demolish, "Demolisci"),
})
{
var b = new ToolButton(tool, T(label));
@@ -55,7 +66,7 @@ public partial class Toolbar : PanelContainer
{
_tool = tool;
_label = label;
CustomMinimumSize = new Vector2(76, 72);
CustomMinimumSize = new Vector2(76, 56);
Flat = true;
TooltipText = label;
MouseEntered += QueueRedraw;
@@ -77,11 +88,11 @@ public partial class Toolbar : PanelContainer
if (_active) DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Inner, 8, 0), new Rect2(Vector2.Zero, Size));
else if (IsHovered()) DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
var color = _active ? Palette.Amber : Palette.Text;
var c = new Vector2(Size.X / 2, 26);
var c = new Vector2(Size.X / 2, 20);
DrawGlyph(c, color);
var font = _active ? UiTheme.BodyBold : UiTheme.Body;
var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 13);
DrawString(font, new Vector2((Size.X - dims.X) / 2, 60), _label, HorizontalAlignment.Left, -1, 13, color);
DrawString(font, new Vector2((Size.X - dims.X) / 2, 48), _label, HorizontalAlignment.Left, -1, 13, color);
}
private void DrawGlyph(Vector2 c, Color col)
@@ -131,6 +142,19 @@ public partial class Toolbar : PanelContainer
DrawArc(c + new Vector2(-6, 9), 7, MathF.PI, MathF.Tau, 12, col, w);
DrawArc(c + new Vector2(6, 9), 7, MathF.PI, MathF.Tau, 12, col, w);
break;
case Tool.Industries:
// fabbrica: tetto a shed e ciminiera
DrawPolyline([c + new Vector2(-11, 10), c + new Vector2(-11, -2), c + new Vector2(-5, -7), c + new Vector2(-5, -2),
c + new Vector2(1, -7), c + new Vector2(1, -2), c + new Vector2(7, -7), c + new Vector2(7, 10), c + new Vector2(-11, 10)], col, w);
DrawLine(c + new Vector2(10, 10), c + new Vector2(10, -11), col, w);
DrawLine(c + new Vector2(7, -11), c + new Vector2(10, -11), col, w);
break;
case Tool.Companies:
// palazzo della borsa: frontone, colonne e basamento
DrawPolyline([c + new Vector2(-11, -5), c + new Vector2(0, -11), c + new Vector2(11, -5), c + new Vector2(-11, -5)], col, w);
for (int i = -1; i <= 1; i++) DrawLine(c + new Vector2(i * 7, -3), c + new Vector2(i * 7, 7), col, w);
DrawLine(c + new Vector2(-11, 10), c + new Vector2(11, 10), col, w);
break;
case Tool.Market:
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
@@ -20,6 +20,9 @@ public sealed class GameSession : IAsyncDisposable
public ProtocolClient Connection { get; }
public ClientWorld World { get; }
public string ServerLabel { get; }
/// <summary>Preset di difficoltà della partita (dal Welcome; serve a «Nuova partita+»).</summary>
public string Difficulty { get; private set; } = "";
public LocalServerLauncher? LocalServer { get; set; }
/// <summary>Istante di arrivo (ms) dell'ultimo moto di ogni treno, per l'interpolazione.</summary>
@@ -52,7 +55,7 @@ public sealed class GameSession : IAsyncDisposable
}, ct);
var world = new ClientWorld(data);
world.Apply(welcome);
return new GameSession(connection, world, label);
return new GameSession(connection, world, label) { Difficulty = welcome.Difficulty };
}
catch
{
@@ -86,6 +89,9 @@ public sealed class GameSession : IAsyncDisposable
case DailyDigest digest when RequestedSpeed == digest.Speed:
RequestedSpeed = null;
break;
case Welcome welcome:
Difficulty = welcome.Difficulty;
break;
case Pong pong when pong.Nonce == _pingNonce:
LatencyMs = (long)Time.GetTicksMsec() - _pingSentMs;
break;
@@ -0,0 +1,946 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Compagnie e borsa (sezione 12, pannello a tutto schermo con palette e componenti dell'immagine
/// 05): listino delle compagnie, offerte pubbliche in corso con adesioni e difese, scheda della
/// compagnia scelta (libro dei soci, prezzo mensile, storico annuale) e operazioni: compravendita,
/// quotazione, dividendo, riacquisto, offerta pubblica, fusione, offerte alle aste delle fallite.
/// I dati arrivano dal listino giornaliero (MarketTape) e dalle schede chieste al server; ogni
/// operazione è un comando e l'esito (anche il rifiuto per livello) si mostra com'è.
/// </summary>
public partial class CompaniesPanel : VBoxContainer
{
private const float WPrice = 80, WCap = 86, WWorth = 86, WMine = 56;
private readonly GameSession _session;
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly VBoxContainer _banner = PanelKit.Column(6);
private readonly VBoxContainer _rows = PanelKit.Column(4);
private readonly VBoxContainer _bids = PanelKit.Column(8);
private readonly VBoxContainer _card = PanelKit.Column(8);
private readonly SeriesChart _chart = new(150);
private readonly Label _chartCaption = UiTheme.Text("", 14, bold: true);
private readonly VBoxContainer _register = PanelKit.Column(6);
private readonly VBoxContainer _history = PanelKit.Column(4);
private readonly VBoxContainer _actions = PanelKit.Column(8);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly Dictionary<int, CompanyRow> _rowById = [];
private readonly Dictionary<int, (Label Text, ProgressBar Bar)> _bidProgress = [];
private string _bidsKey = "", _actionsKey = "", _bannerKey = "", _rowsKey = "";
private int _selected = -1;
private int _tapeVersion = -1, _entityVersion = -1, _detailVersion = -1;
private double _requestSelected, _requestAll = double.MaxValue, _sinceRefresh = double.MaxValue;
private Action? _updateEstimates;
public event Action? CloseRequested;
public event Action? ChronicleRequested;
public CompaniesPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 14);
SizeFlagsVertical = SizeFlags.ExpandFill;
var header = PanelKit.Row(12);
var titles = PanelKit.Column(0);
titles.AddChild(UiTheme.TitleLabel(T("Compagnie e borsa"), 40));
titles.AddChild(_subtitle);
header.AddChild(titles);
var chronicle = new Button { Text = T("Cronaca provvisoria"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(0, 40) };
chronicle.TooltipText = T("La storia della tua compagnia finora: grafici, primati, fatti salienti e prestigio.");
chronicle.Pressed += () => ChronicleRequested?.Invoke();
header.AddChild(chronicle);
var close = new Button { Text = T("Chiudi"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(96, 40) };
close.Pressed += () => CloseRequested?.Invoke();
header.AddChild(close);
AddChild(header);
AddChild(_banner);
var body = PanelKit.Row(16);
body.SizeFlagsVertical = SizeFlags.ExpandFill;
AddChild(body);
var left = Column(body, 1.5f);
left.AddChild(UiTheme.Text(T("Listino"), 16, bold: true));
var sm = session.World.Data.Balance.StockMarket;
left.AddChild(Wrapped($"{T("Clic su una compagnia per la scheda, il libro dei soci e le operazioni. Prezzo per azione: il maggiore tra patrimonio netto e")} " +
$"{Fmt.Number(sm.EarningsMultiple, 0)} {T("volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.")}", 12, Palette.TextSecondary));
left.AddChild(TableHeader());
left.AddChild(_rows);
left.AddChild(PanelKit.Separator());
left.AddChild(UiTheme.Text(T("Offerte pubbliche in corso"), 16, bold: true));
left.AddChild(_bids);
var center = Column(body, 1f);
center.AddChild(_card);
center.AddChild(_chartCaption);
center.AddChild(_chart);
center.AddChild(UiTheme.Text(T("Libro dei soci"), 16, bold: true));
center.AddChild(_register);
var right = Column(body, 0.9f);
right.AddChild(UiTheme.Text(T("Storico annuale"), 16, bold: true));
right.AddChild(_history);
right.AddChild(PanelKit.Separator());
right.AddChild(UiTheme.Text(T("Operazioni"), 16, bold: true));
right.AddChild(_actions);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
right.AddChild(_status);
Select(session.World.Summary?.CompanyId ?? 0);
}
/// <summary>Compagnia della scheda (−1 se nessuna).</summary>
public int Selected => _selected;
public void Select(int company)
{
_selected = company;
_requestSelected = double.MaxValue;
_sinceRefresh = double.MaxValue;
_status.Text = "";
foreach (var (id, row) in _rowById) row.SetSelected(id == company);
}
private static VBoxContainer Column(HBoxContainer body, float ratio)
{
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 16));
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
frame.AddChild(scroll);
// margine destro: la barra di scorrimento non tocca i numeri allineati a destra
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 10);
scroll.AddChild(margin);
var col = PanelKit.Column(10);
margin.AddChild(col);
body.AddChild(frame);
return col;
}
public override void _Process(double delta)
{
var w = _session.World;
_requestSelected += delta;
_requestAll += delta;
_sinceRefresh += delta;
// tutte le schede ogni 5 s (quote del giocatore e soci dei bersagli), quella aperta ogni secondo
if (_requestAll >= 5)
{
_requestAll = 0;
_requestSelected = 0;
foreach (int id in w.Companies.Values.Where(c => !c.Merged).Select(c => c.Id).Order())
_session.Send(new RequestDetail { Kind = DetailKind.Company, Target = id });
}
else if (_requestSelected >= 1 && _selected >= 0)
{
_requestSelected = 0;
_session.Send(new RequestDetail { Kind = DetailKind.Company, Target = _selected });
}
bool changed = w.TapeVersion != _tapeVersion || w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion;
if (changed && _sinceRefresh >= 0.25) Refresh();
}
private void Result(CommandResultMessage r)
{
_status.Text = r.Message;
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.Ok : Palette.Danger);
_requestAll = double.MaxValue;
}
private void Refresh()
{
var w = _session.World;
_sinceRefresh = 0;
_tapeVersion = w.TapeVersion;
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
int me = Me(w);
double portfolio = w.Companies.Values.Where(c => c.Id != me && !c.Merged && !c.Bankrupt).Sum(c => Mine(w, c.Id) * PriceCents(w, c.Id));
_subtitle.Text = (w.Tape is { } tape ? $"{T("Listino del")} {Fmt.Date(w, tape.Day)}" : T("In attesa del listino del giorno…")) +
$" · {T("portafoglio azioni")} {Money.FromCentsRounded(portfolio)}";
RefreshBanner(w);
RefreshRows(w);
RefreshBids(w);
RefreshCard(w);
RefreshHistory(w);
RefreshActions(w);
_updateEstimates?.Invoke();
}
// ------------------------------------------------------------------ dati di comodo (solo lettura)
private static int Me(ClientWorld w) => w.Summary?.CompanyId ?? 0;
private static SharePrice? Quote(ClientWorld w, int id) => w.Tape?.Shares.FirstOrDefault(s => s.Company == id);
/// <summary>Prezzo per azione in centesimi: dal listino se c'è, altrimenti dalla scheda dell'entità.</summary>
private static double PriceCents(ClientWorld w, int id) =>
Quote(w, id) is { PriceCents: > 0 } q ? q.PriceCents : w.Companies.TryGetValue(id, out var c) ? c.SharePriceCents : 0;
private static long Outstanding(ClientWorld w, int id)
{
if (Quote(w, id) is { Outstanding: > 0 } q) return q.Outstanding;
if (w.CompanyCards.TryGetValue(id, out var card)) return card.TotalShares - card.Treasury;
return w.Data.Balance.StockMarket.Shares;
}
/// <summary>Azioni della compagnia del giocatore nella compagnia indicata (dal libro dei soci).</summary>
private static long Mine(ClientWorld w, int id)
{
int me = Me(w);
if (!w.CompanyCards.TryGetValue(id, out var card)) return 0;
return card.Holdings.Where(h => id == me ? h.Holder == HoldingInfo.Founder : h.Holder == me).Sum(h => h.Shares);
}
/// <summary>Vero/falso se il libro dei soci è noto, null se la scheda non è ancora arrivata.</summary>
private static bool? Holds(ClientWorld w, int id) => w.CompanyCards.ContainsKey(id) ? Mine(w, id) > 0 : null;
// ------------------------------------------------------------------ amministrazione controllata
private void RefreshBanner(ClientWorld w)
{
int me = Me(w);
var info = w.Companies.GetValueOrDefault(me);
long today = Fmt.Today(w);
string key = info is { Receivership: true } ? $"{info.ReceivershipUntilDay}|{info.ControlledBy}|{today}|{info.FounderShare:0.000}" : "";
if (key == _bannerKey) return;
_bannerKey = key;
foreach (var c in _banner.GetChildren()) c.QueueFree();
if (info is not { Receivership: true }) return;
var sm = w.Data.Balance.StockMarket;
var box = new PanelContainer();
box.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 14));
var row = PanelKit.Row(16);
box.AddChild(row);
var col = PanelKit.Column(4);
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
col.AddChild(UiTheme.Text($"{T("Amministrazione controllata")} · {T("controlla la compagnia")} {Fmt.Company(w, info.ControlledBy)}", 16, Palette.AmberLight, bold: true));
long left = Math.Max(0, info.ReceivershipUntilDay - today);
col.AddChild(Wrapped($"{T("Riacquista almeno il")} {Fmt.Pct(sm.RansomShare, 0)} {T("delle azioni entro il")} {Fmt.Date(w, info.ReceivershipUntilDay)} ({left} {T("giorni")}), " +
$"{T("altrimenti la partita finisce. Intanto versi il")} {Fmt.Pct(sm.ReceivershipDividend, 0)} {T("degli utili come dividendo e non puoi chiedere prestiti.")} " +
$"{T("Oggi il fondatore ha il")} {Fmt.Pct(info.FounderShare)}.", 13, Palette.Text));
row.AddChild(col);
var buy = UiTheme.Primary(T("Riacquista azioni"));
buy.SizeFlagsVertical = SizeFlags.ShrinkCenter;
buy.Pressed += () => Select(me);
row.AddChild(buy);
_banner.AddChild(box);
}
// ------------------------------------------------------------------ listino
private static Control TableHeader()
{
var row = PanelKit.Row(6);
var name = UiTheme.Text(T("Compagnia"), 12, Palette.TextSecondary);
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
name.CustomMinimumSize = new Vector2(24, 0);
row.AddChild(new Control { CustomMinimumSize = new Vector2(10, 0) });
row.AddChild(name);
foreach (var (text, width) in new[] { (T("Prezzo · var."), WPrice), (T("Capitalizz."), WCap), (T("Patrimonio"), WWorth), (T("Tua quota"), WMine) })
{
var l = UiTheme.Text(text, 12, Palette.TextSecondary);
l.CustomMinimumSize = new Vector2(width, 0);
l.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(l);
}
row.AddChild(new Control { CustomMinimumSize = new Vector2(4, 0) });
return row;
}
private void RefreshRows(ClientWorld w)
{
int me = Me(w);
var companies = w.Companies.Values.Where(c => !c.Merged)
.OrderBy(c => c.Id == me ? 0 : c.Bankrupt ? 2 : 1)
.ThenByDescending(c => PriceCents(w, c.Id) * Outstanding(w, c.Id))
.ThenBy(c => c.Id).ToList();
string key = string.Join(",", companies.Select(c => c.Id));
if (key != _rowsKey)
{
_rowsKey = key;
foreach (var c in _rows.GetChildren()) c.QueueFree();
_rowById.Clear();
foreach (var c in companies)
{
int id = c.Id;
var row = new CompanyRow();
row.Pressed += () => Select(id);
_rowById[id] = row;
_rows.AddChild(row);
row.SetSelected(id == _selected);
}
}
foreach (var c in companies)
{
var q = Quote(w, c.Id);
double price = PriceCents(w, c.Id);
long outstanding = Outstanding(w, c.Id);
var parts = new List<string>();
if (c.Id == me) parts.Add(T("la tua compagnia"));
if (c.Bankrupt)
{
parts.Add(T("fallita, attivi all'asta"));
}
else
{
parts.Add(Fmt.Tier(w, c.Tier));
if (c.Personality.Length > 0) parts.Add(Fmt.Personality(w, c.Personality));
if (!c.Listed) parts.Add(T("non quotata"));
if (c.ControlledBy >= 0) parts.Add($"{T("controllata da")} {Fmt.Company(w, c.ControlledBy)}");
if (c.Receivership) parts.Add(T("amministrazione controllata"));
}
double mine = c.Id == me ? c.FounderShare : outstanding > 0 && w.CompanyCards.ContainsKey(c.Id) ? (double)Mine(w, c.Id) / outstanding : -1;
_rowById[c.Id].Update(
Fmt.CompanyColor(w, c.Id), c.Name, string.Join(" · ", parts),
c.Bankrupt ? "—" : Fmt.Price(price), c.Listed && q is not null && !c.Bankrupt ? Fmt.Change(q.Change) : "—",
!c.Listed || q is null ? Palette.TextSecondary : q.Change > 0.0005f ? Palette.Ok : q.Change < -0.0005f ? Palette.Danger : Palette.TextSecondary,
c.Bankrupt ? "—" : Money.FromCentsRounded(price * outstanding).ToString("short"), c.NetWorth.ToString("short"),
mine < 0 ? "…" : mine <= 0 ? "—" : Fmt.Pct(mine), c.Listed && !c.Bankrupt, c.Bankrupt || c.Receivership);
}
}
/// <summary>Riga del listino: pulsante piatto con le colonne allineate.</summary>
private sealed partial class CompanyRow : Button
{
private readonly ColorRect _swatch = new() { CustomMinimumSize = new Vector2(10, 28), SizeFlagsVertical = SizeFlags.ShrinkCenter };
private readonly Label _name = UiTheme.Text("", 14, bold: true);
private readonly Label _sub = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly Label _price = UiTheme.Text("", 14, bold: true);
private readonly Label _change = UiTheme.Text("", 12);
private readonly Label _cap = UiTheme.Text("", 13);
private readonly Label _worth = UiTheme.Text("", 13);
private readonly Label _mine = UiTheme.Text("", 13, Palette.AmberLight, bold: true);
public CompanyRow()
{
CustomMinimumSize = new Vector2(0, 50);
FocusMode = FocusModeEnum.None;
AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.Border, 8, 8));
AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8));
SetSelected(false);
var row = new HBoxContainer { MouseFilter = MouseFilterEnum.Ignore };
row.AddThemeConstantOverride("separation", 6);
row.SetAnchorsPreset(LayoutPreset.FullRect);
row.OffsetLeft = 8;
row.OffsetRight = -8;
AddChild(row);
row.AddChild(_swatch);
var names = new VBoxContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ShrinkCenter, MouseFilter = MouseFilterEnum.Ignore };
names.AddThemeConstantOverride("separation", -2);
foreach (var l in new[] { _name, _sub })
{
l.ClipText = true;
l.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
l.CustomMinimumSize = new Vector2(24, 0);
names.AddChild(l);
}
row.AddChild(names);
// prezzo con la variazione del giorno sotto
var price = new VBoxContainer { CustomMinimumSize = new Vector2(WPrice, 0), SizeFlagsVertical = SizeFlags.ShrinkCenter, MouseFilter = MouseFilterEnum.Ignore };
price.AddThemeConstantOverride("separation", -2);
foreach (var l in new[] { _price, _change })
{
l.HorizontalAlignment = HorizontalAlignment.Right;
price.AddChild(l);
}
row.AddChild(price);
foreach (var (l, width) in new[] { (_cap, WCap), (_worth, WWorth), (_mine, WMine) })
{
l.CustomMinimumSize = new Vector2(width, 0);
l.HorizontalAlignment = HorizontalAlignment.Right;
l.SizeFlagsVertical = SizeFlags.ShrinkCenter;
row.AddChild(l);
}
foreach (var l in new[] { _name, _sub, _price, _change, _cap, _worth, _mine }) l.MouseFilter = MouseFilterEnum.Ignore;
_swatch.MouseFilter = MouseFilterEnum.Ignore;
}
public void SetSelected(bool on)
{
AddThemeStyleboxOverride("normal", on ? UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8) : UiTheme.Box(Palette.Panel, Palette.Panel, 8, 8));
}
public void Update(Color color, string name, string sub, string price, string change, Color changeColor, string cap, string worth, string mine, bool listed, bool alarm)
{
_swatch.Color = color;
_name.Text = name;
_sub.Text = sub;
TooltipText = $"{name}\n{sub}";
_sub.AddThemeColorOverride("font_color", alarm ? Palette.Danger : Palette.TextSecondary);
_price.Text = price;
_price.AddThemeColorOverride("font_color", listed ? Palette.Text : Palette.TextSecondary);
_change.Text = change;
_change.AddThemeColorOverride("font_color", changeColor);
_cap.Text = cap;
_worth.Text = worth;
_mine.Text = mine;
}
}
// ------------------------------------------------------------------ offerte pubbliche
private void RefreshBids(ClientWorld w)
{
int me = Me(w);
var bids = w.Tape?.Bids ?? [];
string key = string.Join(";", bids.Select(b => $"{b.Bid},{b.Defenses},{b.Knight},{b.Accepted},{Holds(w, b.Target)}")) + "|" + string.Join(",", w.Companies.Values.Where(c => c.Bankrupt || c.Merged).Select(c => c.Id).Order());
if (key != _bidsKey)
{
_bidsKey = key;
_bidProgress.Clear();
foreach (var c in _bids.GetChildren()) c.QueueFree();
if (bids.Count == 0)
{
var sm = w.Data.Balance.StockMarket;
_bids.AddChild(Wrapped($"{T("Nessuna offerta in corso. Un'offerta dura")} {sm.BidDurationDays} {T("giorni e offre un premio tra il")} {Fmt.Pct(sm.BidPremiumMin, 0)} " +
$"{T("e il")} {Fmt.Pct(sm.BidPremiumMax, 0)} {T("sul prezzo di mercato.")}", 13, Palette.TextSecondary));
}
foreach (var b in bids) _bids.AddChild(BidBox(w, b, me));
}
long today = Fmt.Today(w);
foreach (var b in bids)
{
if (!_bidProgress.TryGetValue(b.Bid, out var p)) continue;
p.Text.Text = $"{T("impegnato")} {Fmt.Pct(b.CommittedShare)} {T("di")} {Fmt.Pct(b.TargetShare, 0)} · {T("scade il")} {Fmt.Date(w, b.ExpiresDay)} ({Math.Max(0, b.ExpiresDay - today)} {T("giorni")})";
p.Bar.MaxValue = Math.Max(0.0001, b.TargetShare);
p.Bar.Value = Math.Min(b.CommittedShare, b.TargetShare);
}
}
private Control BidBox(ClientWorld w, BidInfo b, int me)
{
bool mine = b.Target == me || b.Bidder == me;
var box = new PanelContainer();
box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, mine ? Palette.Amber : Palette.Border, 8, 12));
var col = PanelKit.Column(6);
box.AddChild(col);
col.AddChild(Wrapped($"{Fmt.Company(w, b.Bidder)} → {Fmt.Company(w, b.Target)}", 15, null, bold: true));
double market = PriceCents(w, b.Target);
string premium = market > 0 ? $" ({Fmt.Change(b.PricePerShare.Cents / market - 1)} {T("sul mercato")})" : "";
col.AddChild(Wrapped($"{Fmt.Price(b.PricePerShare.Cents)} {T("per azione")}{premium} · {T("obiettivo")} {Fmt.Pct(b.TargetShare, 0)}", 13, null));
var bar = new ProgressBar { ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 3, 0));
col.AddChild(bar);
var progress = UiTheme.Text("", 12, Palette.TextSecondary);
col.AddChild(progress);
_bidProgress[b.Bid] = (progress, bar);
if (DefenseText(w, b) is { Length: > 0 } defenses) col.AddChild(Wrapped(defenses, 12, Palette.AmberLight));
int bidId = b.Bid;
if (b.Target == me)
{
var sm = w.Data.Balance.StockMarket;
col.AddChild(Wrapped($"{T("La tua compagnia è il bersaglio. Difese: riacquisto del flottante con la cassa; dividendo straordinario del")} {Fmt.Pct(sm.ExtraDividendCashShare, 0)} " +
$"{T("della cassa (il titolo sale); cavaliere bianco: un'alleata compra il flottante al prezzo dell'offerta più il")} {Fmt.Pct(sm.WhiteKnightPremium, 0)}.", 12, Palette.TextSecondary));
var row = PanelKit.Row(6);
var buyback = new Button { Text = T("Riacquisto"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
buyback.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.Buyback }, Result);
row.AddChild(buyback);
var dividend = new Button { Text = T("Dividendo straordinario"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
dividend.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.ExtraDividend }, Result);
row.AddChild(dividend);
col.AddChild(row);
var knightRow = PanelKit.Row(6);
var knights = new OptionButton { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
var knightIds = w.Companies.Values.Where(c => c.Id != me && c.Id != b.Bidder && !c.Bankrupt && !c.Merged).OrderBy(c => c.Id).Select(c => c.Id).ToList();
foreach (int k in knightIds) knights.AddItem(Fmt.Company(w, k));
knightRow.AddChild(knights);
var knight = new Button { Text = T("Cavaliere bianco"), Disabled = knightIds.Count == 0 };
knight.Pressed += () =>
{
if (knights.Selected < 0 || knights.Selected >= knightIds.Count) return;
_session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.WhiteKnight, Knight = new CompanyId(knightIds[knights.Selected]) }, Result);
};
knightRow.AddChild(knight);
col.AddChild(knightRow);
}
else if (b.Bidder == me)
{
col.AddChild(Wrapped(T("La tua offerta: gli azionisti aderiscono ogni giorno finché l'obiettivo non è raggiunto o l'offerta scade."), 12, Palette.TextSecondary));
}
else if (Holds(w, b.Target) != false)
{
var respond = b.Accepted ? new Button { Text = T("Ritira l'adesione") } : UiTheme.Primary(T("Aderisci con le tue azioni"));
bool accept = !b.Accepted;
respond.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), accept), Result);
col.AddChild(respond);
if (b.Accepted) col.AddChild(UiTheme.Text(T("Hai aderito con tutte le tue azioni."), 12, Palette.Ok));
}
return box;
}
private static string DefenseText(ClientWorld w, BidInfo b)
{
var parts = new List<string>();
if ((b.Defenses & (1 << (int)BidDefense.None)) != 0) parts.Add(T("respinta dal consiglio"));
if ((b.Defenses & (1 << (int)BidDefense.Buyback)) != 0) parts.Add(T("riacquisto"));
if ((b.Defenses & (1 << (int)BidDefense.ExtraDividend)) != 0) parts.Add(T("dividendo straordinario"));
if ((b.Defenses & (1 << (int)BidDefense.WhiteKnight)) != 0) parts.Add($"{T("cavaliere bianco")} {Fmt.Company(w, b.Knight)}");
return parts.Count == 0 ? "" : $"{T("Difese del bersaglio")}: {string.Join(", ", parts)}";
}
// ------------------------------------------------------------------ scheda della compagnia
private void RefreshCard(ClientWorld w)
{
foreach (var c in _card.GetChildren()) c.QueueFree();
foreach (var c in _register.GetChildren()) c.QueueFree();
int me = Me(w);
if (_selected < 0 || !w.Companies.TryGetValue(_selected, out var info))
{
_chartCaption.Text = "";
_chart.Show([], [], v => "", SeriesChart.Style.Line, Palette.Amber, T("Scegli una compagnia nel listino"));
return;
}
var card = w.CompanyCards.GetValueOrDefault(_selected);
var head = PanelKit.Row(10);
var swatch = new ColorRect { Color = Fmt.CompanyColor(w, info.Id), CustomMinimumSize = new Vector2(12, 34), SizeFlagsVertical = SizeFlags.ShrinkCenter };
head.AddChild(swatch);
var title = UiTheme.TitleLabel(info.Name, 30);
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
head.AddChild(title);
_card.AddChild(head);
var badges = new HFlowContainer();
badges.AddThemeConstantOverride("h_separation", 6);
badges.AddThemeConstantOverride("v_separation", 6);
badges.AddChild(UiTheme.Badge(Fmt.Tier(w, info.Tier)));
if (info.Id == me) badges.AddChild(Tag(T("la tua compagnia"), Palette.AmberLight));
if (info.Personality.Length > 0) badges.AddChild(Tag(Fmt.Personality(w, info.Personality), Palette.Staff));
badges.AddChild(Tag(info.Listed ? T("quotata") : T("non quotata"), info.Listed ? Palette.Ok : Palette.TextSecondary));
if (info.ControlledBy >= 0) badges.AddChild(Tag($"{T("controllata da")} {Fmt.Company(w, info.ControlledBy)}", Palette.Amber));
if (info.Receivership) badges.AddChild(Tag(T("amministrazione controllata"), Palette.Danger));
if (info.Bankrupt) badges.AddChild(Tag(T("fallita"), Palette.Danger));
_card.AddChild(badges);
double price = PriceCents(w, info.Id);
var stats1 = PanelKit.Row(8);
stats1.AddChild(PanelKit.Stat(T("Prezzo per azione"), PanelKit.Value(info.Bankrupt ? "—" : Fmt.Price(price))));
stats1.AddChild(PanelKit.Stat(T("Capitalizzazione"), PanelKit.Value(card?.MarketCap.ToString("short") ?? Money.FromCentsRounded(price * Outstanding(w, info.Id)).ToString("short"))));
stats1.AddChild(PanelKit.Stat(T("Patrimonio netto"), PanelKit.Value(info.NetWorth.ToString("short"))));
_card.AddChild(stats1);
var stats2 = PanelKit.Row(8);
var profit = PanelKit.Value(info.AnnualProfit.ToString("short"));
if (info.AnnualProfit.IsNegative) profit.AddThemeColorOverride("font_color", Palette.Danger);
stats2.AddChild(PanelKit.Stat(T("Utile annuo"), profit));
stats2.AddChild(PanelKit.Stat(T("Dividendi (12 mesi)"), PanelKit.Value(card?.DividendsYear.ToString("short") ?? "—")));
stats2.AddChild(PanelKit.Stat(T("Debito"), PanelKit.Value(card?.Debt.ToString("short") ?? "—")));
_card.AddChild(stats2);
_card.AddChild(PanelKit.Pair(T("Cassa"), PanelKit.Value(info.Cash.ToString())));
_card.AddChild(PanelKit.Pair(T("Sentiment del mercato"), PanelKit.Value("×" + Fmt.Number(info.Sentiment, 2))));
if (card is { ControlDays: >= 0 } && info.ControlledBy >= 0)
_card.AddChild(PanelKit.Pair(T("Controllo"), PanelKit.Value($"{Fmt.Company(w, info.ControlledBy)} · {card.ControlDays} {T("giorni")}")));
var prices = card?.PriceHistory ?? [];
_chartCaption.Text = prices.Count > 0 ? $"{T("Prezzo dell'azione a fine mese")} · {T("ultimi")} {prices.Count} {T("mesi")}" : T("Prezzo dell'azione a fine mese");
_chart.Show(prices, [], Fmt.PricePrecise, SeriesChart.Style.Line, Fmt.CompanyColor(w, info.Id),
card is null ? T("Scheda in arrivo dal server…") : T("Lo storico si forma alla fine di ogni mese"));
BuildRegister(w, info, card);
}
private void BuildRegister(ClientWorld w, CompanyInfo info, CompanyCard? card)
{
if (card is null)
{
_register.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
int me = Me(w);
long outstanding = Math.Max(1, card.TotalShares - card.Treasury);
var holders = card.Holdings.Where(h => h.Shares > 0)
.OrderBy(h => h.Holder == HoldingInfo.Founder ? 0 : h.Holder == HoldingInfo.Market ? 2 : 1)
.ThenByDescending(h => h.Shares).ThenBy(h => h.Holder).ToList();
// barra a segmenti delle quote
var bar = new HBoxContainer { CustomMinimumSize = new Vector2(0, 14) };
bar.AddThemeConstantOverride("separation", 2);
foreach (var h in holders)
bar.AddChild(new ColorRect { Color = HolderColor(w, h.Holder), SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = Math.Max(0.002f, h.Shares / (float)card.TotalShares) });
if (card.Treasury > 0)
bar.AddChild(new ColorRect { Color = Palette.Border, SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = card.Treasury / (float)card.TotalShares });
_register.AddChild(bar);
double control = w.Data.Balance.StockMarket.ControlShare;
foreach (var h in holders)
{
double share = (double)h.Shares / outstanding;
string name = h.Holder switch
{
HoldingInfo.Founder => info.Id == me ? T("Fondatore (tu)") : T("Fondatore privato"),
HoldingInfo.Market => T("Mercato (flottante)"),
_ => Fmt.Company(w, h.Holder) + (h.Holder == me ? " (" + T("tu") + ")" : ""),
};
var row = PanelKit.Row(8);
row.AddChild(new ColorRect { Color = HolderColor(w, h.Holder), CustomMinimumSize = new Vector2(10, 10), SizeFlagsVertical = SizeFlags.ShrinkCenter });
var n = UiTheme.Text(name, 13, h.Holder == me || (h.Holder == HoldingInfo.Founder && info.Id == me) ? Palette.AmberLight : Palette.Text);
n.SizeFlagsHorizontal = SizeFlags.ExpandFill;
n.ClipText = true;
n.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
n.CustomMinimumSize = new Vector2(40, 0);
row.AddChild(n);
var count = UiTheme.Text(Fmt.Shares(h.Shares), 13, Palette.TextSecondary);
count.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(count);
var pct = UiTheme.Text(Fmt.Pct(share), 13, share > control && h.Holder != HoldingInfo.Market ? Palette.Amber : Palette.Text, bold: true);
pct.CustomMinimumSize = new Vector2(64, 0);
pct.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(pct);
_register.AddChild(row);
}
if (card.Treasury > 0)
_register.AddChild(PanelKit.Pair(T("Azioni proprie (non votano)"), PanelKit.Value(Fmt.Shares(card.Treasury))));
_register.AddChild(Wrapped($"{T("Quote sulle")} {Fmt.Shares(outstanding)} {T("azioni in circolazione: oltre il")} {Fmt.Pct(control, 0)} {T("si controlla la compagnia.")}", 12, Palette.TextSecondary));
}
private static Color HolderColor(ClientWorld w, int holder) => holder switch
{
HoldingInfo.Founder => Palette.Amber,
HoldingInfo.Market => Palette.TextSecondary,
_ => Fmt.CompanyColor(w, holder),
};
// ------------------------------------------------------------------ storico annuale
private void RefreshHistory(ClientWorld w)
{
foreach (var c in _history.GetChildren()) c.QueueFree();
var card = _selected >= 0 ? w.CompanyCards.GetValueOrDefault(_selected) : null;
if (card is null || card.History.Count == 0)
{
_history.AddChild(Wrapped(card is null ? T("Scheda in arrivo dal server…") : T("Nessun anno concluso: lo storico si scrive a fine anno."), 13, Palette.TextSecondary));
return;
}
var grid = new GridContainer { Columns = 5, SizeFlagsHorizontal = SizeFlags.ExpandFill };
grid.AddThemeConstantOverride("h_separation", 12);
grid.AddThemeConstantOverride("v_separation", 4);
foreach (string h in new[] { T("Anno"), T("Patrimonio"), T("Utile"), T("Treni"), T("Liv.") })
{
var l = UiTheme.Text(h, 12, Palette.TextSecondary);
l.HorizontalAlignment = h == T("Anno") ? HorizontalAlignment.Left : HorizontalAlignment.Right;
if (h == T("Patrimonio")) l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
grid.AddChild(l);
}
foreach (var y in Enumerable.Reverse(card.History).Take(8))
{
grid.AddChild(UiTheme.Text($"{y.Year}", 13, bold: true));
foreach (var (text, color) in new[]
{
(y.NetWorth.ToString("short"), Palette.Text),
(y.Profit.ToString("short"), y.Profit.IsNegative ? Palette.Danger : Palette.Text),
($"{y.Trains}", Palette.Text),
($"{y.Tier}", Palette.Text),
})
{
var l = UiTheme.Text(text, 13, color);
l.HorizontalAlignment = HorizontalAlignment.Right;
grid.AddChild(l);
}
}
_history.AddChild(grid);
}
// ------------------------------------------------------------------ operazioni
private void RefreshActions(ClientWorld w)
{
int me = Me(w);
if (_selected < 0 || !w.Companies.TryGetValue(_selected, out var info))
{
if (_actionsKey.Length > 0) Clear(_actions);
_actionsKey = "";
return;
}
var card = w.CompanyCards.GetValueOrDefault(_selected);
var meInfo = w.Companies.GetValueOrDefault(me);
bool auction = card is { AuctionEndDay: >= 0 };
bool bidOpen = w.Tape?.Bids.Any(b => b.Target == _selected) == true;
string key = $"{_selected}|{info.Listed}|{info.Bankrupt}|{info.Merged}|{info.ControlledBy == me}|{auction}|{bidOpen}|{meInfo?.Listed}|{meInfo?.Receivership}|{card is null}";
if (key == _actionsKey) return;
_actionsKey = key;
Clear(_actions);
_updateEstimates = null;
if (card is null)
{
_actions.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
if (info.Id == me) BuildOwnActions(w, info);
else if (info.Bankrupt) BuildAuction(w, info, card);
else BuildTradeActions(w, info, bidOpen);
}
private static void Clear(Container c)
{
foreach (var child in c.GetChildren()) child.QueueFree();
}
/// <summary>Operazioni sulla compagnia del giocatore: quotazione, dividendo, riacquisto.</summary>
private void BuildOwnActions(ClientWorld w, CompanyInfo me)
{
var sm = w.Data.Balance.StockMarket;
var updates = new List<Action>();
if (!me.Listed)
{
_actions.AddChild(UiTheme.Text(T("Quotazione in borsa"), 14, bold: true));
var slider = new HSlider { MinValue = 1, MaxValue = Math.Round(sm.IpoMaxShare * 100), Step = 1, Value = Math.Round(sm.IpoMaxShare * 100 / 2), SizeFlagsHorizontal = SizeFlags.ExpandFill };
var label = UiTheme.Text("", 13);
label.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(slider);
_actions.AddChild(label);
void Estimate()
{
long shares = (long)Math.Round(sm.Shares * slider.Value / 100);
label.Text = $"{T("Colloca il")} {Fmt.Number(slider.Value, 0)}% {T("del capitale")} ({Fmt.Shares(shares)} {T("azioni")}): {T("incasso stimato")} ≈ {Money.FromCentsRounded(shares * PriceCents(_session.World, me.Id))}";
}
slider.ValueChanged += _ => Estimate();
updates.Add(Estimate);
var ipo = UiTheme.Primary(T("Quotati in borsa"));
ipo.Pressed += () => _session.Command(new IpoCommand(slider.Value / 100), Result);
_actions.AddChild(ipo);
if (Fmt.UnlockTier(w, u => u.Ipo) is { } tier)
_actions.AddChild(Wrapped($"{T("La quotazione si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
else
{
_actions.AddChild(UiTheme.Text(T("Dividendo"), 14, bold: true));
var row = PanelKit.Row(6);
var perShare = new SpinBox { MinValue = 0.01, MaxValue = 1000, Step = 0.01, Value = 0.01, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
perShare.TooltipText = T("Dividendo per azione");
row.AddChild(perShare);
var pay = new Button { Text = T("Paga dividendo") };
pay.Pressed += () => _session.Command(new PayDividendCommand(new Money((long)Math.Round(perShare.Value * 100))), Result);
row.AddChild(pay);
_actions.AddChild(row);
var total = UiTheme.Text("", 12, Palette.TextSecondary);
total.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(total);
void Estimate() => total.Text = $"{T("Totale")} {new Money((long)Math.Round(perShare.Value * 100) * Outstanding(_session.World, me.Id))} {T("agli azionisti; i dividendi alzano il sentiment del titolo.")}";
perShare.ValueChanged += _ => Estimate();
updates.Add(Estimate);
}
if (me.Listed || me.Receivership)
{
_actions.AddChild(PanelKit.Separator());
_actions.AddChild(UiTheme.Text(T("Riacquisto di azioni proprie"), 14, bold: true));
updates.Add(QuantityRow(w, me.Id, T("Riacquista"), null, n => new BuySharesCommand(new CompanyId(me.Id), n, Money.Zero), null,
me.Receivership ? T("In amministrazione controllata compri anche dal controllante, con il premio di riscatto.") : T("Le azioni tornano al fondatore e alzano la tua quota.")));
}
_updateEstimates = () => { foreach (var u in updates) u(); };
}
/// <summary>Compravendita, offerta pubblica e fusione per le altre compagnie.</summary>
private void BuildTradeActions(ClientWorld w, CompanyInfo target, bool bidOpen)
{
var sm = w.Data.Balance.StockMarket;
int me = Me(w);
var updates = new List<Action>();
int id = target.Id;
if (target.Listed)
{
_actions.AddChild(UiTheme.Text(T("Compravendita di azioni"), 14, bold: true));
updates.Add(QuantityRow(w, id, T("Compra"), T("Vendi"),
n => new BuySharesCommand(new CompanyId(id), n, Money.Zero),
n => new SellSharesCommand(new CompanyId(id), n, Money.Zero),
$"{T("Spread")} {Fmt.Pct(sm.Spread, 0)}; {T("al massimo il")} {Fmt.Pct(sm.MaxDailyTradeShare, 0)} {T("del capitale per ordine.")}"));
}
else
{
_actions.AddChild(Wrapped(T("Non quotata: le sue azioni non sono sul mercato."), 13, Palette.TextSecondary));
}
if (target.ControlledBy == me)
{
_actions.AddChild(PanelKit.Separator());
_actions.AddChild(UiTheme.Text(T("Fusione"), 14, bold: true));
var info = UiTheme.Text("", 12, Palette.TextSecondary);
info.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(info);
updates.Add(() =>
{
long days = _session.World.CompanyCards.GetValueOrDefault(id)?.ControlDays ?? 0;
info.Text = $"{T("La controlli da")} {Math.Max(0, days)} {T("giorni")}; {T("la fusione è possibile dopo")} {sm.MergeAfterDays} {T("giorni e liquida le minoranze al prezzo di mercato.")}";
});
var merge = UiTheme.Primary(T("Incorpora la controllata"));
merge.Pressed += () => _session.Command(new MergeCompanyCommand(new CompanyId(id)), Result);
_actions.AddChild(merge);
}
else if (target.Listed)
{
_actions.AddChild(PanelKit.Separator());
_actions.AddChild(UiTheme.Text(T("Offerta pubblica di acquisto"), 14, bold: true));
if (bidOpen)
{
_actions.AddChild(Wrapped(T("C'è già un'offerta in corso su questa compagnia: la trovi nell'elenco a sinistra."), 12, Palette.TextSecondary));
}
else
{
double pMin = sm.BidPremiumMin * 100, pMax = sm.BidPremiumMax * 100;
var premiumLabel = UiTheme.Text("", 13);
var premium = new HSlider { MinValue = pMin, MaxValue = pMax, Step = 1, Value = pMin, SizeFlagsHorizontal = SizeFlags.ExpandFill };
_actions.AddChild(premiumLabel);
_actions.AddChild(premium);
var shareLabel = UiTheme.Text("", 13);
double minTarget = Math.Floor(sm.ControlShare * 100) + 1;
var share = new HSlider { MinValue = minTarget, MaxValue = 100, Step = 1, Value = minTarget, SizeFlagsHorizontal = SizeFlags.ExpandFill };
_actions.AddChild(shareLabel);
_actions.AddChild(share);
var cost = UiTheme.Text("", 12, Palette.TextSecondary);
cost.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(cost);
long Cents() => BidCents(PriceCents(_session.World, id), premium.Value / 100, sm.BidPremiumMin, sm.BidPremiumMax);
void Estimate()
{
var world = _session.World;
double market = PriceCents(world, id);
long cents = Cents();
string effective = market > 0 ? Fmt.Change(cents / market - 1) : "—";
premiumLabel.Text = $"{T("Premio")} {Fmt.Number(premium.Value, 0)}% · {Fmt.Price(cents)} {T("per azione")} ({effective} {T("sul mercato")}: {Fmt.PricePrecise(market)})";
shareLabel.Text = $"{T("Quota obiettivo")} {Fmt.Number(share.Value, 0)}%";
long outstanding = Outstanding(world, id);
long needed = Math.Max(0, (long)Math.Ceiling(share.Value / 100 * outstanding) - Mine(world, id));
cost.Text = $"{T("Impegno massimo")} {new Money(needed * cents)} {T("per")} {Fmt.Shares(needed)} {T("azioni")}; {T("durata")} {sm.BidDurationDays} {T("giorni")}.";
}
premium.ValueChanged += _ => Estimate();
share.ValueChanged += _ => Estimate();
updates.Add(Estimate);
var launch = UiTheme.Primary(T("Lancia l'offerta"));
launch.Pressed += () => _session.Command(new LaunchBidCommand(new CompanyId(id), new Money(Cents()), share.Value / 100), Result);
_actions.AddChild(launch);
if (Fmt.UnlockTier(w, u => u.HostileTakeover) is { } tier)
_actions.AddChild(Wrapped($"{T("Le scalate ostili si sbloccano al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
}
_updateEstimates = () => { foreach (var u in updates) u(); };
}
/// <summary>Offerta all'asta degli attivi di una compagnia fallita (offerta = prezzo per azione × azioni).</summary>
private void BuildAuction(ClientWorld w, CompanyInfo seller, CompanyCard card)
{
if (card.AuctionEndDay < 0)
{
_actions.AddChild(Wrapped(T("Compagnia fallita: nessuna asta in corso."), 13, Palette.TextSecondary));
return;
}
int id = seller.Id;
long total = Math.Max(1, card.TotalShares);
_actions.AddChild(UiTheme.Text(T("Asta degli attivi"), 14, bold: true));
var best = PanelKit.Value();
var closing = PanelKit.Value();
var minimum = PanelKit.Value();
_actions.AddChild(PanelKit.Pair(T("Base d'asta"), minimum));
_actions.AddChild(PanelKit.Pair(T("Miglior offerta"), best));
_actions.AddChild(PanelKit.Pair(T("Chiusura"), closing));
var row = PanelKit.Row(6);
// l'offerta si esprime in lire; il protocollo la trasmette come prezzo per azione intero in centesimi
double step = total / 100.0;
var offer = new SpinBox { MinValue = step, MaxValue = 1e12, Step = step, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
row.AddChild(offer);
var bid = UiTheme.Primary(T("Offri all'asta"));
bid.Pressed += () =>
{
long perShare = (long)Math.Ceiling(offer.Value * 100 / total - 1e-9);
_session.Command(new LaunchBidCommand(new CompanyId(id), new Money(perShare), 1), Result);
};
row.AddChild(bid);
_actions.AddChild(row);
_actions.AddChild(Wrapped(T("Chi offre di più alla chiusura compra treni, binari, stazioni e industrie della compagnia fallita."), 12, Palette.TextSecondary));
bool initialized = false;
_updateEstimates = () =>
{
var world = _session.World;
var c = world.CompanyCards.GetValueOrDefault(id);
if (c is null || c.AuctionEndDay < 0) return;
minimum.Text = c.AuctionMin.ToString();
best.Text = c.AuctionBestBidder >= 0 ? $"{c.AuctionBest} · {Fmt.Company(world, c.AuctionBestBidder)}" : T("nessuna");
closing.Text = $"{Fmt.Date(world, c.AuctionEndDay)} ({Math.Max(0, c.AuctionEndDay - Fmt.Today(world))} {T("giorni")})";
double floor = Math.Max(c.AuctionMin.Cents, c.AuctionBest.Cents + 1) / 100.0;
double next = Math.Ceiling(floor / step) * step;
if (!initialized || (offer.Value < next && !offer.GetLineEdit().HasFocus()))
{
initialized = true;
offer.SetValueNoSignal(next);
}
};
}
/// <summary>Riga quantità di azioni + pulsanti, con la stima del controvalore e delle azioni possedute.</summary>
private Action QuantityRow(ClientWorld w, int company, string first, string? second,
Func<long, GameCommand> firstCommand, Func<long, GameCommand>? secondCommand, string note)
{
var sm = w.Data.Balance.StockMarket;
long max = Math.Max(1, (long)(sm.Shares * sm.MaxDailyTradeShare));
var row = PanelKit.Row(6);
var qty = new SpinBox { MinValue = 1, MaxValue = max, Step = 1, CustomArrowStep = 1000, Rounded = true, Value = Math.Min(10_000, max), SizeFlagsHorizontal = SizeFlags.ExpandFill };
qty.TooltipText = T("Numero di azioni");
row.AddChild(qty);
var a = UiTheme.Primary(first);
a.Pressed += () => _session.Command(firstCommand((long)qty.Value), Result);
row.AddChild(a);
if (second is not null && secondCommand is not null)
{
var b = new Button { Text = second };
b.Pressed += () => _session.Command(secondCommand((long)qty.Value), Result);
row.AddChild(b);
}
_actions.AddChild(row);
var estimate = UiTheme.Text("", 12, Palette.TextSecondary);
estimate.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(estimate);
_actions.AddChild(Wrapped(note, 12, Palette.TextSecondary));
void Estimate()
{
var world = _session.World;
long held = Mine(world, company);
long outstanding = Math.Max(1, Outstanding(world, company));
long free = Quote(world, company)?.FreeFloat ?? 0;
estimate.Text = $"{T("Controvalore")} ≈ {Money.FromCentsRounded(qty.Value * PriceCents(world, company))} · " +
$"{(company == Me(world) ? T("il fondatore ha") : T("possiedi"))} {Fmt.Shares(held)} {T("azioni")} ({Fmt.Pct((double)held / outstanding)}) · {T("sul mercato")} {Fmt.Shares(free)}";
}
qty.ValueChanged += _ => Estimate();
return Estimate;
}
/// <summary>
/// Prezzo intero (centesimi) dell'offerta per il premio scelto, tenuto dentro i limiti del premio
/// nonostante l'arrotondamento al centesimo.
/// </summary>
private static long BidCents(double market, double premium, double min, double max)
{
double basis = Math.Max(1e-6, market);
long cents = (long)Math.Round(basis * (1 + premium));
if (cents / basis - 1 < min) cents = (long)Math.Ceiling(basis * (1 + min) - 1e-9);
if (cents / basis - 1 > max) cents = (long)Math.Floor(basis * (1 + max) + 1e-9);
return Math.Max(1, cents);
}
// ------------------------------------------------------------------ mattoni
private static PanelContainer Tag(string text, Color color)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, color, 4, 6));
p.AddChild(UiTheme.Text(text, 12, color, bold: true));
return p;
}
private static Label Wrapped(string text, int size, Color? color, bool bold = false)
{
var l = UiTheme.Text(text, size, color, bold);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -0,0 +1 @@
uid://bxbrrccdi8qun
@@ -0,0 +1,86 @@
using System.Globalization;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Formati numerici dell'interfaccia (immagine 05): separatore delle migliaia con il punto,
/// decimali con la virgola, prezzi delle azioni in lire con i centesimi.
/// </summary>
public static class Fmt
{
/// <summary>Numero con i decimali indicati e la virgola («12,4»).</summary>
public static string Number(double value, int decimals = 1)
{
string text = value.ToString(decimals <= 0 ? "0" : "0." + new string('0', decimals), CultureInfo.InvariantCulture);
int dot = text.IndexOf('.');
string integer = dot < 0 ? text : text[..dot];
bool negative = integer.StartsWith('-');
if (negative) integer = integer[1..];
string grouped = ulong.TryParse(integer, NumberStyles.None, CultureInfo.InvariantCulture, out ulong n) ? Money.GroupThousands(n) : integer;
return (negative ? "−" : "") + grouped + (dot < 0 ? "" : "," + text[(dot + 1)..]);
}
/// <summary>Quota (0–1) in percentuale («12,4%»).</summary>
public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
/// <summary>Variazione con il segno («+1,2%», «−0,8%»).</summary>
public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
/// <summary>Prezzo per azione dai centesimi frazionari («₤ 0,25»).</summary>
public static string Price(double cents) => Money.FromCentsRounded(cents).ToString("it2");
/// <summary>Prezzo per azione con i decimali che servono a leggere le variazioni sotto il centesimo («₤ 0,2534»).</summary>
public static string PricePrecise(double cents) => cents >= 10_000 ? Price(cents) : "₤ " + Number(cents / 100, cents >= 100 ? 2 : 4);
/// <summary>Numero di azioni con il punto delle migliaia.</summary>
public static string Shares(long shares) => shares < 0 ? "−" + Money.GroupThousands((ulong)(-shares)) : Money.GroupThousands((ulong)shares);
/// <summary>Giorno corrente della partita (dal resoconto giornaliero o dal tick).</summary>
public static long Today(ClientWorld w) =>
w.LastDigest?.Day ?? (w.Calendar is { } c ? w.Tick / c.TicksPerDay : 0);
/// <summary>Data di calendario di un giorno della partita.</summary>
public static string Date(ClientWorld w, long day) =>
w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).ToString() : $"{T("giorno")} {day}";
/// <summary>Nome di una compagnia (o «—» se sconosciuta).</summary>
public static string Company(ClientWorld w, int id) =>
w.Companies.TryGetValue(id, out var c) ? c.Name : id >= 0 ? $"#{id}" : "—";
/// <summary>Nome del livello della compagnia nella lingua dell'interfaccia.</summary>
public static string Tier(ClientWorld w, int tier)
{
var tiers = w.Data.Tiers.Tiers;
var def = tiers[Math.Clamp(tier, 1, tiers.Count) - 1];
return Godot.TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
}
/// <summary>
/// Livello che sblocca una funzione, se la compagnia del giocatore non ce l'ha ancora (solo per
/// il suggerimento: è il server a decidere).
/// </summary>
public static int? UnlockTier(ClientWorld w, Func<Core.Data.TierUnlocks, bool> unlock)
{
int tier = w.Companies.TryGetValue(w.Summary?.CompanyId ?? 0, out var me) ? me.Tier : 1;
var tiers = w.Data.Tiers.Tiers;
if (unlock(tiers[Math.Clamp(tier, 1, tiers.Count) - 1].Unlocks)) return null;
return tiers.FirstOrDefault(t => unlock(t.Unlocks))?.Level;
}
/// <summary>Carattere di una compagnia IA (id di ai.json); vuoto per il giocatore.</summary>
public static string Personality(ClientWorld w, string id) => id switch
{
"" => "",
"expansive" => T("Espansiva"),
"prudent" => T("Prudente"),
"predatory" => T("Predatoria"),
_ => w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == id)?.NameIt ?? id,
};
/// <summary>Colore di una compagnia dalla stringa esadecimale, con l'ambra in mancanza.</summary>
public static Godot.Color CompanyColor(ClientWorld w, int id) =>
w.Companies.TryGetValue(id, out var c) && Godot.Color.HtmlIsValid(c.Color) ? new Godot.Color(c.Color) : App.Palette.Amber;
}
@@ -0,0 +1 @@
uid://u5pgogq2sft1
@@ -0,0 +1,367 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di
/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato»,
/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista».
/// La scheda del proprietario arriva su richiesta dal server (IndustryCard).
/// </summary>
public partial class IndustryPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly ItemList _list = new() { CustomMinimumSize = new Vector2(0, 150) };
private readonly List<int> _ids = [];
private readonly VBoxContainer _header = PanelKit.Column(8);
private readonly VBoxContainer _controls = PanelKit.Column(8);
private readonly VBoxContainer _details = PanelKit.Column(6);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<Button> _budgetButtons = [];
private SpinBox? _partsOrder;
private int _industry = -1;
private (int Industry, int Owner) _controlsKey = (-2, -2);
private int _entityVersion = -1, _detailVersion = -1;
private double _request, _sinceRefresh;
public IndustryPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Industrie"), 34));
var help = UiTheme.Text(T("Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(_list);
AddChild(PanelKit.Separator());
AddChild(_header);
AddChild(_controls);
AddChild(_details);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_list.ItemSelected += i => Select(_ids[(int)i]);
RefreshList();
}
/// <summary>Industria mostrata (−1 se nessuna).</summary>
public int Industry => _industry;
public void Select(int id)
{
if (id == _industry) return;
_industry = id;
_status.Text = "";
SyncSelection();
Request();
Refresh();
}
private void Request()
{
if (_industry >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Industry, Target = _industry });
}
public override void _Process(double delta)
{
// la scheda aperta si aggiorna una volta al secondo; il pannello al massimo quattro volte
_request += delta;
_sinceRefresh += delta;
if (_request >= 1)
{
_request = 0;
Request();
}
var w = _session.World;
if ((w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) && _sinceRefresh >= 0.25) Refresh();
}
private void Result(CommandResultMessage r)
{
_status.Text = r.Message;
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
Request();
}
private void Refresh()
{
var w = _session.World;
_sinceRefresh = 0;
if (w.EntityVersion != _entityVersion) RefreshList();
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
foreach (var c in _header.GetChildren()) c.QueueFree();
foreach (var c in _details.GetChildren()) c.QueueFree();
if (_industry < 0 || !w.Industries.TryGetValue(_industry, out var ind))
{
BuildControls(null);
return;
}
var card = w.IndustryCards.GetValueOrDefault(_industry);
BuildHeader(w, ind, card);
BuildControls(ind);
UpdateControls(ind, card);
BuildDetails(w, ind, card);
}
// ------------------------------------------------------------------ elenco
/// <summary>Elenco: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
private void RefreshList()
{
var w = _session.World;
int me = w.Summary?.CompanyId ?? 0;
long today = Fmt.Today(w);
var ordered = w.Industries.Values.Where(i => !i.Closed)
.OrderBy(i => i.Owner == me ? 0 : i.Owner < 0 ? 1 : 2).ThenBy(i => i.Name, StringComparer.Ordinal).ThenBy(i => i.Id).ToList();
bool same = ordered.Count == _ids.Count && ordered.Select(i => i.Id).SequenceEqual(_ids);
if (!same)
{
_ids.Clear();
_list.Clear();
}
for (int n = 0; n < ordered.Count; n++)
{
var ind = ordered[n];
string owner = ind.Owner == me ? T("tua") : ind.Owner < 0 ? T("privati") : Fmt.Company(w, ind.Owner);
string stop = ind.StoppedUntilDay >= today ? " · " + T("ferma") : "";
string text = $"{ind.Name} · {Fmt.Number(ind.Condition, 0)}% · {owner}{stop}";
if (!same)
{
_ids.Add(ind.Id);
_list.AddItem(text);
}
else if (_list.GetItemText(n) != text)
{
_list.SetItemText(n, text);
}
_list.SetItemCustomFgColor(n, ind.Owner == me ? Palette.AmberLight : MaintenancePanel.ConditionColor((int)ind.Condition));
}
if (!same) SyncSelection();
}
private void SyncSelection()
{
int index = _ids.IndexOf(_industry);
if (index < 0)
{
_list.DeselectAll();
return;
}
if (!_list.IsSelected(index)) _list.Select(index);
_list.EnsureCurrentIsVisible();
}
// ------------------------------------------------------------------ scheda
private void BuildHeader(ClientWorld w, IndustryInfo ind, IndustryCard? card)
{
int me = w.Summary?.CompanyId ?? 0;
var title = UiTheme.TitleLabel(ind.Name, 30);
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_header.AddChild(title);
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
_header.AddChild(UiTheme.Text($"{def?.NameIt ?? ind.Type} · {T("livello")} {ind.Level}", 14, Palette.TextSecondary));
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
_header.AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
long today = Fmt.Today(w);
if (ind.StoppedUntilDay >= today)
_header.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
else if (ind.PendingWork != 0)
_header.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
(ind.PendingWork == 1 ? " " + T("e personale sufficiente") : "")));
if (ind.PartsShort)
_header.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
var stats = PanelKit.Row(8);
stats.AddChild(PanelKit.Stat(T("Condizione"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", MaintenancePanel.ConditionColor((int)ind.Condition))));
stats.AddChild(PanelKit.Stat(T("Resa impianti"), PanelKit.Value(card is null ? "—" : "×" + Fmt.Number(card.ConditionMultiplier, 2))));
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value(Fmt.Pct(ind.Efficiency, 0))));
_header.AddChild(stats);
var bar = new ProgressBar { MaxValue = 100, Value = ind.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
var color = MaintenancePanel.ConditionColor((int)ind.Condition);
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
_header.AddChild(bar);
var m = w.Data.Balance.IndustryMaintenance;
_header.AddChild(Wrapped($"{T("Sopra il")} {Fmt.Number(m.EfficiencyFullAbove, 0)}% {T("gli impianti rendono pieno; sotto calano fino a")} ×{Fmt.Number(m.EfficiencyAt20, 1)} {T("al 20% e si fermano più spesso.")}", 12, Palette.TextSecondary));
}
/// <summary>Comandi del proprietario o dell'acquirente: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
private void BuildControls(IndustryInfo? ind)
{
var key = ind is null ? (-1, -1) : (ind.Id, ind.Owner);
if (key == _controlsKey) return;
_controlsKey = key;
foreach (var c in _controls.GetChildren()) c.QueueFree();
_budgetButtons.Clear();
_partsOrder = null;
if (ind is null) return;
var w = _session.World;
int me = w.Summary?.CompanyId ?? 0;
int id = ind.Id;
if (ind.Owner == me)
{
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
var row = PanelKit.Row(6);
var group = new ButtonGroup();
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
{
var p = w.Data.Balance.IndustryMaintenance.For(budget);
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
_budgetButtons.Add(b);
row.AddChild(b);
}
_controls.AddChild(row);
var order = PanelKit.Row(6);
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
caption.MouseFilter = MouseFilterEnum.Pass;
order.AddChild(caption);
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
order.AddChild(_partsOrder);
var orderButton = new Button { Text = T("Ordina ricambi") };
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
order.AddChild(orderButton);
_controls.AddChild(order);
var actions = PanelKit.Row(6);
var m = w.Data.Balance.IndustryMaintenance;
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(overhaul);
var upgrade = UiTheme.Primary(T("Ammoderna"));
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(upgrade);
_controls.AddChild(actions);
}
else if (ind.Owner < 0)
{
_controls.AddChild(UiTheme.Text(T("In vendita"), 14, bold: true));
var price = PanelKit.Value("—");
price.Name = "Price";
_controls.AddChild(PanelKit.Pair(T("Prezzo chiesto dai proprietari"), price));
var buy = UiTheme.Primary(T("Acquista"));
buy.Pressed += () =>
{
if (_session.World.IndustryCards.TryGetValue(id, out var c))
_session.Command(new BuyIndustryCommand(new IndustryId(id), c.Valuation), Result);
else
Request();
};
_controls.AddChild(buy);
if (Fmt.UnlockTier(w, u => u.BuyIndustry) is { } tier)
_controls.AddChild(Wrapped($"{T("L'acquisto di industrie si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
else
{
_controls.AddChild(Wrapped($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 13, Palette.TextSecondary));
}
}
private void UpdateControls(IndustryInfo ind, IndustryCard? card)
{
for (int i = 0; i < _budgetButtons.Count; i++) _budgetButtons[i].SetPressedNoSignal(i == ind.Budget);
if (_partsOrder is not null && card is not null && !_partsOrder.GetLineEdit().HasFocus()) _partsOrder.SetValueNoSignal(card.PartsOrdered);
if (_controls.FindChild("Price", true, false) is Label price) price.Text = card?.Valuation.ToString() ?? "—";
}
private void BuildDetails(ClientWorld w, IndustryInfo ind, IndustryCard? card)
{
if (card is null)
{
_details.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
int me = w.Summary?.CompanyId ?? 0;
_details.AddChild(UiTheme.Text(T("Impianti"), 14, bold: true));
_details.AddChild(PanelKit.Pair(T("Usura al giorno"), PanelKit.Value("−" + Fmt.Number(card.WearPerDay, 3))));
_details.AddChild(PanelKit.Pair(T("Recupero al giorno"), PanelKit.Value("+" + Fmt.Number(card.RecoveryPerDay, 3))));
_details.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
_details.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
if (ind.Owner == me)
{
_details.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
_details.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
_details.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
_details.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
}
_details.AddChild(PanelKit.Separator());
_details.AddChild(UiTheme.Text(T("Scorte"), 14, bold: true));
_details.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
_details.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
_details.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
_details.AddChild(UiTheme.Text($"{T("servono")} {card.MachineryRequired} {T("macchinari per il prossimo lavoro")}", 12, Palette.TextSecondary));
_details.AddChild(PanelKit.Separator());
_details.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
if (card.Stops.Count == 0) _details.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
foreach (var s in Enumerable.Reverse(card.Stops).Take(8))
{
var l = UiTheme.Text($"{Fmt.Date(w, s.Day)} · {StopName(s.Kind)} · {s.Days} {T("giorni")}", 13, s.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary);
_details.AddChild(l);
}
}
private static Control StockRow(string caption, int have, int target, Color color)
{
var row = PanelKit.Row(8);
var name = UiTheme.Text(caption, 13, Palette.TextSecondary);
name.CustomMinimumSize = new Vector2(96, 0);
row.AddChild(name);
var bar = new ProgressBar { MaxValue = Math.Max(1, Math.Max(have, target)), Value = have, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10), SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ShrinkCenter };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 3, 0));
row.AddChild(bar);
row.AddChild(UiTheme.Text($"{have} / {target}", 13, bold: true));
return row;
}
// ------------------------------------------------------------------ testi
public static string StopName(byte kind) => kind switch
{
1 => T("Guasto"),
2 => T("Incidente grave"),
3 => T("Revisione"),
4 => T("Ammodernamento"),
_ => T("Fermo"),
};
private static string WorkName(byte work) => work switch
{
1 => T("Revisione programmata"),
2 => T("Ammodernamento programmato"),
_ => "",
};
private static Label ColoredValue(string text, Color color)
{
var l = PanelKit.Value(text);
l.AddThemeColorOverride("font_color", color);
return l;
}
private static Label Wrapped(string text, int size, Color? color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -0,0 +1 @@
uid://j8ci61w6roh6
@@ -18,6 +18,7 @@ public partial class InfoPanel : VBoxContainer
private double _refresh;
public event Action<int>? MaintenanceRequested;
public event Action<int>? IndustryRequested;
public InfoPanel(GameSession session)
{
@@ -141,6 +142,16 @@ public partial class InfoPanel : VBoxContainer
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
}
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
// pannello del proprietario (sezione 11): manutenzione degli impianti o acquisto
int me = w.Summary?.CompanyId ?? 0;
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
if (ind.StoppedUntilDay >= Fmt.Today(w))
AddChild(UiTheme.Notice($"{IndustryPanel.StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)}"));
int industryId = ind.Id;
var ownerButton = new Button { Text = ind.Owner == me ? T("Gestisci l'industria") : T("Scheda del proprietario") };
ownerButton.Pressed += () => IndustryRequested?.Invoke(industryId);
AddChild(ownerButton);
// dal Registro degli impieghi: presenze, posti scoperti e provenienza dei pendolari
if (w.Employment?.Rows.FirstOrDefault(r => r.Kind == 0 && r.Industry == ind.Id) is { } row)
{
@@ -0,0 +1,119 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni,
/// barre per il patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
/// </summary>
public partial class SeriesChart : Control
{
public enum Style { Line, Bars }
private IReadOnlyList<double> _values = [];
private IReadOnlyList<string> _labels = [];
private Func<double, string> _format = v => Fmt.Number(v, 0);
private Style _style;
private Color _color = Palette.Amber;
private string _empty = "";
public SeriesChart(float height = 150)
{
CustomMinimumSize = new Vector2(0, height);
MouseFilter = MouseFilterEnum.Ignore;
}
/// <summary>Imposta la serie: valori, etichette dell'asse orizzontale (facoltative) e formato dei valori.</summary>
public void Show(IReadOnlyList<double> values, IReadOnlyList<string> labels, Func<double, string> format, Style style, Color color, string empty)
{
_values = values;
_labels = labels;
_format = format;
_style = style;
_color = color;
_empty = empty;
QueueRedraw();
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
var font = UiTheme.Body;
const int fontSize = 11;
if (_values.Count == 0 || (_style == Style.Line && _values.Count < 2))
{
string text = _empty.Length > 0 ? _empty : T("Dati insufficienti");
var dims = font.GetStringSize(text, HorizontalAlignment.Left, -1, 13);
DrawString(font, new Vector2((Size.X - dims.X) / 2, Size.Y / 2 + 4), text, HorizontalAlignment.Left, -1, 13, Palette.TextSecondary);
return;
}
double min = _values.Min(), max = _values.Max();
if (_style == Style.Bars) min = Math.Min(0, min);
if (max - min < 1e-9)
{
max += Math.Max(1, Math.Abs(max) * 0.1);
if (_style == Style.Line) min -= Math.Max(1, Math.Abs(min) * 0.1);
}
string maxText = _format(max), minText = _format(min);
float left = 12 + Math.Max(font.GetStringSize(maxText, HorizontalAlignment.Left, -1, fontSize).X, font.GetStringSize(minText, HorizontalAlignment.Left, -1, fontSize).X) + 8;
bool hasLabels = _labels.Count == _values.Count;
var area = new Rect2(left, 12, Size.X - left - 14, Size.Y - (hasLabels ? 34 : 22));
float Y(double v) => area.End.Y - (float)((v - min) / (max - min)) * area.Size.Y;
// griglia: massimo, metà, minimo
foreach (double v in new[] { min, (min + max) / 2, max })
DrawLine(new Vector2(area.Position.X, Y(v)), new Vector2(area.End.X, Y(v)), Palette.WithAlpha(Palette.Border, 0.9f), 1);
DrawString(font, new Vector2(10, Y(max) + 4), maxText, HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
DrawString(font, new Vector2(10, Y(min) + 4), minText, HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
int n = _values.Count;
if (_style == Style.Bars)
{
float slot = area.Size.X / n;
float width = Math.Max(2, Math.Min(42, slot * 0.7f));
for (int i = 0; i < n; i++)
{
float x = area.Position.X + slot * (i + 0.5f);
float y0 = Y(Math.Max(min, 0)), y1 = Y(_values[i]);
var color = _values[i] < 0 ? Palette.Danger : i == n - 1 ? Palette.AmberLight : _color;
DrawRect(new Rect2(x - width / 2, Math.Min(y0, y1), width, Math.Max(1, Math.Abs(y1 - y0))), color);
}
DrawLabels(area, n, slot, font, fontSize, centered: true);
return;
}
float step = area.Size.X / (n - 1);
var points = new Vector2[n];
for (int i = 0; i < n; i++) points[i] = new Vector2(area.Position.X + step * i, Y(_values[i]));
var fill = new List<Vector2>(points) { new(area.End.X, area.End.Y), new(area.Position.X, area.End.Y) };
DrawColoredPolygon(fill.ToArray(), Palette.WithAlpha(_color, 0.18f));
DrawPolyline(points, _color, 2.5f, true);
DrawCircle(points[^1], 4, Palette.AmberLight);
string last = _format(_values[^1]);
var lastDims = font.GetStringSize(last, HorizontalAlignment.Left, -1, 12);
float lx = Math.Min(points[^1].X - lastDims.X / 2, Size.X - lastDims.X - 6);
float ly = points[^1].Y - 8 < area.Position.Y + 10 ? points[^1].Y + 18 : points[^1].Y - 8;
DrawString(UiTheme.BodyBold, new Vector2(lx, ly), last, HorizontalAlignment.Left, -1, 12, Palette.AmberLight);
DrawLabels(area, n, step, font, fontSize, centered: false);
}
/// <summary>Etichette dell'asse orizzontale, diradate per non sovrapporsi.</summary>
private void DrawLabels(Rect2 area, int n, float step, Font font, int fontSize, bool centered)
{
if (_labels.Count != n) return;
float widest = _labels.Max(l => font.GetStringSize(l, HorizontalAlignment.Left, -1, fontSize).X) + 10;
int every = Math.Max(1, (int)Math.Ceiling(widest / Math.Max(1, step)));
for (int i = 0; i < n; i++)
{
// l'ultima etichetta si aggiunge solo se non tocca la precedente
bool show = i % every == 0 || (i == n - 1 && (n - 1) % every * step >= widest);
if (!show) continue;
var dims = font.GetStringSize(_labels[i], HorizontalAlignment.Left, -1, fontSize);
float x = area.Position.X + step * (centered ? i + 0.5f : i) - dims.X / 2;
x = Math.Clamp(x, area.Position.X - 4, Size.X - dims.X - 4);
DrawString(font, new Vector2(x, area.End.Y + 16), _labels[i], HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
}
}
}
@@ -0,0 +1 @@
uid://cvus3vxujok5q
@@ -34,7 +34,9 @@ public partial class TrackPanel : VBoxContainer
_world = world;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Binari"), 34));
AddChild(UiTheme.Text(T("Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare."), 13, Palette.TextSecondary));
var help = UiTheme.Text(T("Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
foreach (var cls in world.Data.Eras.TrackClasses)
{
_class.AddItem($"{cls.NameIt}", cls.Index);
@@ -0,0 +1,220 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Panels;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Screens;
/// <summary>
/// Cronaca finale (12.3), a tutto schermo sopra la partita: storia della compagnia anno per anno
/// (patrimonio netto), primati, fatti salienti e prestigio, con «Continua come osservatore» e
/// «Nuova partita+». A partita in corso la stessa schermata è la Cronaca provvisoria.
/// Mostra solo ciò che manda il server (messaggio Chronicle).
/// </summary>
public partial class ChronicleScreen : Control
{
private readonly ClientWorld _world;
private readonly Chronicle _chronicle;
private readonly string _nextDifficulty;
/// <summary>Chiusura: continua come osservatore (o torna alla partita, se provvisoria).</summary>
public event Action? Closed;
/// <summary>Nuova partita+ con la difficoltà successiva.</summary>
public event Action? NewGamePlus;
public ChronicleScreen(ClientWorld world, Chronicle chronicle, string nextDifficulty)
{
_world = world;
_chronicle = chronicle;
_nextDifficulty = nextDifficulty;
}
public bool Final => _chronicle.GameOver;
public override void _Ready()
{
// già nell'albero: ancore e margini insieme, altrimenti resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
MouseFilter = MouseFilterEnum.Stop;
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var margin = new MarginContainer();
margin.SetAnchorsPreset(LayoutPreset.FullRect);
foreach (string side in new[] { "left", "right" }) margin.AddThemeConstantOverride("margin_" + side, 48);
foreach (string side in new[] { "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 28);
AddChild(margin);
var root = PanelKit.Column(16);
margin.AddChild(root);
var c = _chronicle;
var header = PanelKit.Row(24);
var titles = PanelKit.Column(2);
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
titles.AddChild(UiTheme.TitleLabel(c.GameOver ? T("Cronaca finale") : T("Cronaca provvisoria"), 60));
int lastYear = c.History.Count > 0 ? c.History[^1].Year : c.FoundedYear;
titles.AddChild(UiTheme.Text($"{c.Company} · {c.FoundedYear}–{lastYear} · {Fmt.Date(_world, c.Day)}", 20, Palette.TextSecondary, bold: true));
header.AddChild(titles);
var prestige = new PanelContainer { SizeFlagsVertical = SizeFlags.ShrinkCenter };
prestige.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 18));
var prestigeCol = PanelKit.Column(0);
prestigeCol.AddChild(UiTheme.Text(T("Prestigio"), 14, Palette.AmberLight));
prestigeCol.AddChild(UiTheme.TitleLabel(Fmt.Number(c.Prestige, 0), 48, Palette.AmberLight));
prestige.AddChild(prestigeCol);
header.AddChild(prestige);
root.AddChild(header);
if (c.GameOver)
{
var reason = new PanelContainer();
reason.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 16));
var col = PanelKit.Column(2);
col.AddChild(UiTheme.Text(ReasonTitle(c.Reason) + (c.Winner >= 0 ? $" · {T("vincitore")}: {Fmt.Company(_world, c.Winner)}" : ""), 17, Palette.AmberLight, bold: true));
if (c.Text.Length > 0) col.AddChild(Wrapped(c.Text, 14, Palette.Text));
col.AddChild(Wrapped(T("Il mondo continua: le compagnie IA giocano e puoi guardarle come osservatore, ma il server non accetta più i tuoi comandi."), 13, Palette.TextSecondary));
reason.AddChild(col);
root.AddChild(reason);
}
else
{
root.AddChild(UiTheme.Notice(T("La partita è in corso: questa è la storia finora. La Cronaca finale arriva quando la tua compagnia esce di scena.")));
}
var body = PanelKit.Row(20);
body.SizeFlagsVertical = SizeFlags.ExpandFill;
root.AddChild(body);
// sinistra: grafico e tabella anno per anno
var left = Frame(body, 1.7f);
left.AddChild(UiTheme.Text(T("Patrimonio netto anno per anno"), 16, bold: true));
var chart = new SeriesChart(240);
chart.Show(c.History.Select(y => (double)y.NetWorth.Cents).ToList(), c.History.Select(y => $"{y.Year}").ToList(),
v => Core.Common.Money.FromCentsRounded(v).ToString("short"), SeriesChart.Style.Bars, Palette.Amber, T("Nessun anno registrato"));
left.AddChild(chart);
left.AddChild(YearTable(c.History));
// destra: primati e fatti salienti
var right = Frame(body, 1f);
right.AddChild(UiTheme.Text(T("Primati"), 16, bold: true));
var records = new GridContainer { Columns = 2, SizeFlagsHorizontal = SizeFlags.ExpandFill };
records.AddThemeConstantOverride("h_separation", 8);
records.AddThemeConstantOverride("v_separation", 8);
foreach (var r in c.Records)
{
var value = PanelKit.Value(r.Value);
value.ClipText = true;
value.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
var stat = PanelKit.Stat($"{r.Title} ({r.Year})", value);
stat.TooltipText = $"{r.Title}: {r.Value} ({r.Year})";
records.AddChild(stat);
}
right.AddChild(records);
right.AddChild(PanelKit.Separator());
right.AddChild(UiTheme.Text(T("Fatti salienti"), 16, bold: true));
if (c.Highlights.Count == 0) right.AddChild(UiTheme.Text(T("Ancora nessun fatto da raccontare."), 13, Palette.TextSecondary));
foreach (string h in c.Highlights) right.AddChild(Wrapped("• " + h, 13, Palette.Text));
// pulsanti
var buttons = PanelKit.Row(12);
buttons.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
if (c.GameOver)
{
var hint = UiTheme.Text($"{T("Nuova mappa con la difficoltà")} «{_nextDifficulty}»", 14, Palette.TextSecondary);
hint.SizeFlagsVertical = SizeFlags.ShrinkCenter;
buttons.AddChild(hint);
var observe = new Button { Text = T("Continua come osservatore"), CustomMinimumSize = new Vector2(0, 48) };
observe.Pressed += () => Closed?.Invoke();
buttons.AddChild(observe);
var again = UiTheme.Primary(T("Nuova partita+"));
again.CustomMinimumSize = new Vector2(200, 48);
again.Pressed += () => NewGamePlus?.Invoke();
buttons.AddChild(again);
}
else
{
var back = UiTheme.Primary(T("Torna alla partita"));
back.CustomMinimumSize = new Vector2(200, 48);
back.Pressed += () => Closed?.Invoke();
buttons.AddChild(back);
}
root.AddChild(buttons);
}
public override void _UnhandledKeyInput(InputEvent e)
{
if (e is InputEventKey { Pressed: true, Keycode: Key.Escape })
{
Closed?.Invoke();
GetViewport().SetInputAsHandled();
}
}
private static VBoxContainer Frame(HBoxContainer body, float ratio)
{
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 18));
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
frame.AddChild(scroll);
// margine destro: la barra di scorrimento non tocca i numeri allineati a destra
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 12);
scroll.AddChild(margin);
var col = PanelKit.Column(10);
margin.AddChild(col);
body.AddChild(frame);
return col;
}
private static Control YearTable(List<CompanyYearInfo> history)
{
var grid = new GridContainer { Columns = 7, SizeFlagsHorizontal = SizeFlags.ExpandFill };
grid.AddThemeConstantOverride("h_separation", 18);
grid.AddThemeConstantOverride("v_separation", 4);
string[] heads = [T("Anno"), T("Patrimonio"), T("Cassa"), T("Ricavi"), T("Utile"), T("Treni"), T("Km di binari")];
for (int i = 0; i < heads.Length; i++)
{
var l = UiTheme.Text(heads[i], 12, Palette.TextSecondary);
l.HorizontalAlignment = i == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
l.SizeFlagsHorizontal = i == 0 ? SizeFlags.Fill : SizeFlags.ExpandFill;
grid.AddChild(l);
}
foreach (var y in Enumerable.Reverse(history).Take(12))
{
grid.AddChild(UiTheme.Text($"{y.Year}", 13, bold: true));
foreach (var (text, color) in new[]
{
(y.NetWorth.ToString("short"), Palette.Text),
(y.Cash.ToString("short"), Palette.Text),
(y.Revenue.ToString("short"), Palette.Text),
(y.Profit.ToString("short"), y.Profit.IsNegative ? Palette.Danger : Palette.Ok),
($"{y.Trains}", Palette.Text),
(Fmt.Number(y.TrackKm, 1), Palette.Text),
})
{
var l = UiTheme.Text(text, 13, color);
l.HorizontalAlignment = HorizontalAlignment.Right;
grid.AddChild(l);
}
}
return grid;
}
private static string ReasonTitle(byte reason) => reason switch
{
1 => T("Fallimento"),
2 => T("La compagnia è stata scalata"),
3 => T("Riscatto non riuscito in tempo"),
_ => T("Partita conclusa"),
};
private static Label Wrapped(string text, int size, Color color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -0,0 +1 @@
uid://ck3hivvfy7bdr
@@ -21,7 +21,9 @@ public partial class ConnectScreen : Control
public override void _Ready()
{
SetAnchorsPreset(LayoutPreset.FullRect);
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
@@ -6,6 +6,7 @@ using ViaFerrea.Client.Net;
using ViaFerrea.Client.Panels;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
@@ -38,6 +39,18 @@ public partial class GameScreen : Node
private LinesPanel? _linesPanel;
private InfoPanel? _info;
private MaintenancePanel? _maintenance;
private IndustryPanel? _industryPanel;
private CompaniesPanel? _companies;
// pannelli a tutto schermo (Compagnie e borsa): coprono mappa e pannello destro, la barra resta
private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false };
private Control? _mapArea;
private Control? _side;
// Cronaca finale (o provvisoria) sopra tutta la partita e avviso dell'osservatore
private readonly CanvasLayer _overlay = new() { Layer = 3 };
private readonly PanelContainer _observer = new() { Visible = false };
private ChronicleScreen? _chronicleScreen;
private Protocol.Messages.Chronicle? _seenChronicle;
private bool _wantChronicle, _finalShown;
private bool _heatMap;
private readonly List<Vector2> _trackPoints = [];
private Vector2? _mouse;
@@ -81,6 +94,29 @@ public partial class GameScreen : Node
_maintenance?.SelectDepot(depot);
}
/// <summary>Apre il pannello Industrie sull'industria indicata (scheda del proprietario).</summary>
public void OpenIndustry(int industry)
{
if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries);
_industryPanel?.Select(industry);
}
/// <summary>Apre «Compagnie e borsa» a tutto schermo sulla compagnia indicata.</summary>
public void OpenCompanies(int company)
{
if (_tool != Tool.Companies) _toolbar.Select(Tool.Companies);
_companies?.Select(company);
}
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
public void OpenChronicle()
{
_wantChronicle = true;
_session.Send(new RequestDetail { Kind = DetailKind.Chronicle, Target = 0 });
}
public bool ChronicleVisible => _chronicleScreen is not null;
/// <summary>Mappa di calore della condizione dei treni.</summary>
public void SetHeatMap(bool on)
{
@@ -112,6 +148,7 @@ public partial class GameScreen : Node
var hud = new CanvasLayer { Layer = 2 };
AddChild(hud);
var root = new VBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
UiTheme.Apply(root);
root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
root.AddThemeConstantOverride("separation", 0);
hud.AddChild(root);
@@ -122,6 +159,7 @@ public partial class GameScreen : Node
middle.AddChild(_toolbar);
var mapArea = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
middle.AddChild(mapArea);
_mapArea = mapArea;
_toasts.SetAnchorsPreset(Control.LayoutPreset.TopWide);
_toasts.OffsetLeft = 16;
_toasts.OffsetRight = -16;
@@ -131,11 +169,19 @@ public partial class GameScreen : Node
var side = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
side.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 18));
middle.AddChild(side);
_side = side;
_full.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AppBackground, Palette.Border, 0, 20));
middle.AddChild(_full);
BuildObserverBanner(mapArea);
var sideCol = new VBoxContainer();
sideCol.AddThemeConstantOverride("separation", 12);
side.AddChild(sideCol);
sideCol.AddChild(_scroll);
_scroll.AddChild(_content);
// margine destro: la barra di scorrimento non copre i valori allineati a destra
var contentMargin = new MarginContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
contentMargin.AddThemeConstantOverride("margin_right", 12);
_scroll.AddChild(contentMargin);
contentMargin.AddChild(_content);
var miniHeader = new HBoxContainer();
var miniTitle = UiTheme.Text(T("Minimappa"), 13, Palette.TextSecondary);
miniTitle.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
@@ -146,6 +192,7 @@ public partial class GameScreen : Node
root.AddChild(_ticker);
BuildDisconnectedOverlay(hud);
AddChild(_overlay);
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
@@ -165,9 +212,37 @@ public partial class GameScreen : Node
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
/// <summary>Avviso permanente dopo la fine della partita: si guarda il mondo, la Cronaca resta a portata.</summary>
private void BuildObserverBanner(Control mapArea)
{
_observer.SetAnchorsPreset(Control.LayoutPreset.BottomWide);
_observer.OffsetLeft = 16;
_observer.OffsetRight = -16;
_observer.OffsetTop = -70;
_observer.OffsetBottom = -16;
_observer.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AmberDark, Palette.Amber, 8, 14));
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 14);
var text = UiTheme.Text(T("Partita conclusa: sei un osservatore. Il mondo va avanti e le compagnie IA continuano a giocare."), 14, Palette.AmberLight, bold: true);
text.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
text.SizeFlagsVertical = Control.SizeFlags.ShrinkCenter;
text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
row.AddChild(text);
var open = UiTheme.Primary(T("Cronaca finale"));
open.Pressed += () =>
{
if (_session.World.Chronicle is { } c) ShowChronicle(c);
else OpenChronicle();
};
row.AddChild(open);
_observer.AddChild(row);
mapArea.AddChild(_observer);
}
private void BuildDisconnectedOverlay(CanvasLayer hud)
{
_disconnected.SetAnchorsPreset(Control.LayoutPreset.FullRect);
UiTheme.Apply(_disconnected);
_disconnected.Visible = false;
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.55f) };
shade.SetAnchorsPreset(Control.LayoutPreset.FullRect);
@@ -202,7 +277,12 @@ public partial class GameScreen : Node
// nuova partita o caricamento: si ricomincia dalla copia locale vuota
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
CloseChronicle();
_seenChronicle = null;
_wantChronicle = _finalShown = false;
_toolbar.Select(Tool.None);
SendViewport(force: true);
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
break;
case DailyDigest d:
foreach (var e in d.Events.Where(e => e.Severity >= 2)) _ticker.Add(e);
@@ -214,6 +294,7 @@ public partial class GameScreen : Node
{
_session.Poll();
_disconnected.Visible = !_session.IsOpen;
UpdateChronicle();
SendViewport(force: false);
_sincePreview += delta;
if (_previewDirty && _sincePreview > 0.12)
@@ -282,6 +363,13 @@ public partial class GameScreen : Node
_linesPanel = null;
_info = null;
_maintenance = null;
_industryPanel = null;
_companies = null;
foreach (var c in _full.GetChildren()) c.QueueFree();
bool full = tool == Tool.Companies;
_full.Visible = full;
if (_mapArea is not null) _mapArea.Visible = !full;
if (_side is not null) _side.Visible = !full;
Control panel;
switch (tool)
{
@@ -331,6 +419,16 @@ public partial class GameScreen : Node
case Tool.Employment:
panel = new EmploymentPanel(_session);
break;
case Tool.Industries:
panel = _industryPanel = new IndustryPanel(_session);
break;
case Tool.Companies:
_companies = new CompaniesPanel(_session);
_companies.CloseRequested += () => _toolbar.Select(Tool.None);
_companies.ChronicleRequested += OpenChronicle;
_full.AddChild(_companies);
panel = NewInfoPanel();
break;
case Tool.Market:
panel = new MarketPanel(_session);
break;
@@ -338,14 +436,21 @@ public partial class GameScreen : Node
panel = new FinancePanel(_session);
break;
default:
panel = _info = new InfoPanel(_session);
_info.MaintenanceRequested += OpenMaintenance;
panel = NewInfoPanel();
break;
}
panel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
_content.AddChild(panel);
}
private InfoPanel NewInfoPanel()
{
_info = new InfoPanel(_session);
_info.MaintenanceRequested += OpenMaintenance;
_info.IndustryRequested += OpenIndustry;
return _info;
}
private void OnMapHovered(Vector2 world)
{
_mouse = world;
@@ -394,6 +499,9 @@ public partial class GameScreen : Node
case Tool.Lines when _linesPanel is not null:
if (NearestStation(world) is { } station) _linesPanel.AddStop(station);
break;
case Tool.Industries when _industryPanel is not null:
if (IndustryAt(world) is { } industry) _industryPanel.Select(industry);
break;
default:
SelectAt(world);
break;
@@ -568,13 +676,10 @@ public partial class GameScreen : Node
_map.Entities.SelectedStation = -1;
_map.Entities.QueueRedraw();
double cs = w.Summary?.CellSizeM ?? 100;
foreach (var ind in w.Industries.Values)
if (IndustryAt(world) is { } industry)
{
if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6))
{
_info.Select(InfoPanel.Kind.Industry, ind.Id);
return;
}
_info.Select(InfoPanel.Kind.Industry, industry);
return;
}
foreach (var town in w.Towns.Values)
{
@@ -587,6 +692,72 @@ public partial class GameScreen : Node
_info.Select(InfoPanel.Kind.None, -1);
}
private int? IndustryAt(Vector2 world)
{
double cs = _session.World.Summary?.CellSizeM ?? 100;
foreach (var ind in _session.World.Industries.Values)
{
if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6)) return ind.Id;
}
return null;
}
// ------------------------------------------------------------------ Cronaca finale e osservatore
/// <summary>Mostra la Cronaca quando arriva: subito se la partita è finita, oppure se l'ha chiesta il giocatore.</summary>
private void UpdateChronicle()
{
var chronicle = _session.World.Chronicle;
if (!ReferenceEquals(chronicle, _seenChronicle))
{
_seenChronicle = chronicle;
if (chronicle is not null && ((chronicle.GameOver && !_finalShown) || _wantChronicle))
{
_wantChronicle = false;
if (chronicle.GameOver) _finalShown = true;
ShowChronicle(chronicle);
}
}
_observer.Visible = chronicle?.GameOver == true && _chronicleScreen is null;
}
private void ShowChronicle(Protocol.Messages.Chronicle chronicle)
{
CloseChronicle();
var next = NextDifficulty();
string name = TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt;
var screen = new ChronicleScreen(_session.World, chronicle, name);
screen.Closed += CloseChronicle;
screen.NewGamePlus += StartNewGamePlus;
_overlay.AddChild(screen);
_chronicleScreen = screen;
}
private void CloseChronicle()
{
_chronicleScreen?.QueueFree();
_chronicleScreen = null;
}
/// <summary>Difficoltà successiva a quella della partita (l'ultima resta l'ultima).</summary>
private DifficultyDef NextDifficulty()
{
var file = _session.World.Data.Difficulty;
int i = file.Presets.FindIndex(p => p.Id == _session.Difficulty);
if (i < 0) i = file.Presets.FindIndex(p => p.Id == file.Default);
return file.Presets[Math.Clamp(i + 1, 0, file.Presets.Count - 1)];
}
/// <summary>Nuova partita+: mappa nuova (seme successivo, stessa dimensione) con la difficoltà superiore.</summary>
private void StartNewGamePlus()
{
var summary = _session.World.Summary;
var next = NextDifficulty();
_session.Send(new NewGame { Seed = (summary?.Seed ?? 0) + 1, SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = next.Id });
CloseChronicle();
Toast($"{T("Nuova partita+ in preparazione")}: {(TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt)}");
}
/// <summary>Messaggio temporaneo in alto sulla mappa.</summary>
private void Toast(string text, bool error = false)
{
@@ -14,7 +14,9 @@ public partial class MenuScreen : Control
public override void _Ready()
{
SetAnchorsPreset(LayoutPreset.FullRect);
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB