forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

economy.rs261 lines, 8.5 KiBHistoryRawDownload
1//! Game clock, home-front production and consumption, and the weekly budget.
2
3use std::collections::HashMap;
4
5use bevy::input::ButtonInput;
6use bevy::prelude::*;
7use bevy::time::{Real, Time};
8
9use crate::menu::Menu;
10use crate::model::{
11 Good, HourTick, Network, NodeKind, Notify, Outcome, SECS_PER_HOUR, SimClock, Train, Treasury,
12};
13use crate::seasons::SeasonState;
14
15/// Stock cap per good per node.
16const STOCK_CAP: f32 = 200.0;
17/// Food eaten per hour by Capital and City.
18const FOOD_PER_HOUR: f32 = 0.5;
19/// Hunger relief per hour when fed, and gain per hour when starving.
20const HUNGER_RECOVER: f32 = 0.02;
21const HUNGER_GAIN: f32 = 0.03;
22/// Hunger level at which a city's production warning fires.
23const HUNGER_ALARM: f32 = 0.5;
24/// Minimum game hours between two bread-line warnings for the same city.
25const ALARM_COOLDOWN_HOURS: u32 = 24;
26/// Wounded treated per hour per hospital node.
27const TREAT_PER_HOUR: f32 = 1.0;
28/// Troops returned per wounded treated.
29const TROOPS_PER_TREATED: f32 = 0.5;
30/// Weekly budget period in game hours.
31const WEEK_HOURS: u32 = 24 * 7;
32const BASE_INCOME: i64 = 2000;
33const FRONT_LINE_BONUS: i64 = 500;
34
35pub struct EconomyPlugin;
36
37impl Plugin for EconomyPlugin {
38 fn build(&self, app: &mut App) {
39 app.add_systems(Update, (clock_controls, advance_clock).chain())
40 .add_systems(Update, economy_tick.after(advance_clock));
41 }
42}
43
44/// Space toggles pause (restoring the previous speed on unpause).
45/// Digit1/2/3 select speed 1, 2 or 4.
46fn clock_controls(
47 keys: Res<ButtonInput<KeyCode>>,
48 menu: Res<Menu>,
49 mut clock: ResMut<SimClock>,
50 mut prev_speed: Local<u32>,
51) {
52 if menu.is_open() {
53 return;
54 }
55 if keys.just_pressed(KeyCode::Space) {
56 if clock.speed == 0 {
57 clock.speed = if *prev_speed == 0 { 1 } else { *prev_speed };
58 } else {
59 *prev_speed = clock.speed;
60 clock.speed = 0;
61 }
62 }
63 let digits = [
64 (KeyCode::Digit1, 1),
65 (KeyCode::Digit2, 2),
66 (KeyCode::Digit3, 4),
67 ];
68 for (key, speed) in digits {
69 if keys.just_pressed(key) {
70 clock.speed = speed;
71 }
72 }
73}
74
75/// Advances game time by real time times speed, emitting one `HourTick` per whole hour.
76pub fn advance_clock(
77 time: Res<Time<Real>>,
78 outcome: Res<Outcome>,
79 mut clock: ResMut<SimClock>,
80 mut ticks: MessageWriter<HourTick>,
81) {
82 if *outcome != Outcome::Ongoing {
83 return;
84 }
85 clock.acc += time.delta_secs() * clock.speed as f32;
86 while clock.acc >= SECS_PER_HOUR {
87 clock.acc -= SECS_PER_HOUR;
88 clock.hour += 1;
89 ticks.write(HourTick);
90 }
91}
92
93/// Runs the hourly production, consumption and budget for every `HourTick` read this frame.
94/// Ticks are ordered after `advance_clock`, so the tick hours are the last `n` hours of the clock.
95#[allow(clippy::too_many_arguments, reason = "bevy system parameters")]
96pub(crate) fn economy_tick(
97 mut ticks: MessageReader<HourTick>,
98 clock: Res<SimClock>,
99 season: Res<SeasonState>,
100 mut net: ResMut<Network>,
101 mut treasury: ResMut<Treasury>,
102 trains: Query<&Train>,
103 mut notes: MessageWriter<Notify>,
104 mut alarm_hours: Local<HashMap<usize, u32>>,
105) {
106 let n = ticks.read().count() as u32;
107 if n == 0 {
108 return;
109 }
110 let first_hour = (clock.hour + 1).saturating_sub(n);
111 for k in 0..n {
112 let hour = first_hour + k;
113 for text in run_hour(&mut net.nodes, hour, season.season.food_mult(), &mut alarm_hours) {
114 notes.write(Notify(text));
115 }
116 if is_budget_hour(hour) {
117 let front_lines = net
118 .nodes
119 .iter()
120 .filter(|node| node.front.is_some_and(|f| f.line > 0.0))
121 .count();
122 let upkeep: i64 = trains.iter().map(|t| t.upkeep_per_week()).sum();
123 let income = budget_income(front_lines);
124 treasury.0 += income - upkeep;
125 notes.write(Notify(format!(
126 "War Ministry allocation: +${income}, upkeep -${upkeep}"
127 )));
128 }
129 }
130}
131
132/// One hour of home-front simulation. Returns the news lines to publish.
133fn run_hour(
134 nodes: &mut [crate::model::Node],
135 hour: u32,
136 food_mult: f32,
137 alarm_hours: &mut HashMap<usize, u32>,
138) -> Vec<String> {
139 let mut news = Vec::new();
140
141 let (hunger_sum, hunger_count) = nodes
142 .iter()
143 .filter(|n| !n.captured && matches!(n.kind, NodeKind::Capital | NodeKind::City))
144 .fold((0.0_f32, 0_usize), |(s, c), n| (s + n.hunger, c + 1));
145 let avg_hunger = if hunger_count > 0 {
146 hunger_sum / hunger_count as f32
147 } else {
148 0.0
149 };
150 let p = productivity(avg_hunger);
151
152 for (i, node) in nodes.iter_mut().enumerate() {
153 // Captured sites are gone; evacuating sites produce nothing until the evacuation ends.
154 if node.captured {
155 continue;
156 }
157 let before = node.hunger;
158 let output = if node.evac.is_some() { 0.0 } else { node.output };
159 match node.kind {
160 NodeKind::Factory => {
161 add_capped(&mut node.stock[Good::Ammo.idx()], 2.0 * p * output);
162 }
163 NodeKind::Farm => {
164 add_capped(&mut node.stock[Good::Food.idx()], 3.0 * output);
165 }
166 NodeKind::Capital => {
167 add_capped(&mut node.stock[Good::Troops.idx()], 0.8 * p * output);
168 }
169 NodeKind::City => {
170 add_capped(&mut node.stock[Good::Troops.idx()], city_troops(before) * output);
171 }
172 NodeKind::Depot | NodeKind::Front => {}
173 }
174
175 if matches!(node.kind, NodeKind::Capital | NodeKind::City) {
176 let (hunger, eaten) = feed(before, node.stock[Good::Food.idx()], FOOD_PER_HOUR * food_mult);
177 node.stock[Good::Food.idx()] = (node.stock[Good::Food.idx()] - eaten).max(0.0);
178 node.hunger = hunger;
179
180 let wounded = node.stock[Good::Wounded.idx()];
181 let treated = wounded.min(TREAT_PER_HOUR);
182 node.stock[Good::Wounded.idx()] = (wounded - treated).max(0.0);
183 add_capped(
184 &mut node.stock[Good::Troops.idx()],
185 treated * TROOPS_PER_TREATED,
186 );
187
188 if node.kind == NodeKind::City
189 && before < HUNGER_ALARM
190 && node.hunger >= HUNGER_ALARM
191 && alarm_due(alarm_hours, i, hour)
192 {
193 news.push(format!("Bread lines in {}: production falling", node.name));
194 }
195 }
196 }
197 news
198}
199
200/// Returns true and records `hour` when the city's warning is off cooldown.
201/// A last warning later than `hour` came from before a restart, so it does not count.
202fn alarm_due(alarm_hours: &mut HashMap<usize, u32>, node: usize, hour: u32) -> bool {
203 match alarm_hours.get(&node) {
204 Some(&last) if hour >= last && hour - last < ALARM_COOLDOWN_HOURS => false,
205 _ => {
206 alarm_hours.insert(node, hour);
207 true
208 }
209 }
210}
211
212/// Output multiplier from average city hunger: 1.0 when fed, 0.4 at full hunger.
213pub fn productivity(avg_hunger: f32) -> f32 {
214 1.0 - 0.6 * avg_hunger
215}
216
217/// Troops a city adds per hour, scaled by its own hunger.
218pub fn city_troops(hunger: f32) -> f32 {
219 0.3 * (1.0 - hunger)
220}
221
222/// One hour of eating a `ration`. Returns (new hunger, food consumed).
223pub fn feed(hunger: f32, food: f32, ration: f32) -> (f32, f32) {
224 if food >= ration {
225 ((hunger - HUNGER_RECOVER).max(0.0), ration)
226 } else {
227 ((hunger + HUNGER_GAIN).min(1.0), 0.0)
228 }
229}
230
231/// Adds `amount` to a stock, clamped to the per-node cap.
232pub fn add_capped(stock: &mut f32, amount: f32) {
233 *stock = (*stock + amount).min(STOCK_CAP);
234}
235
236pub fn is_budget_hour(hour: u32) -> bool {
237 hour > 0 && hour.is_multiple_of(WEEK_HOURS)
238}
239
240pub fn budget_income(front_lines_advancing: usize) -> i64 {
241 BASE_INCOME + FRONT_LINE_BONUS * front_lines_advancing as i64
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn feed_eats_when_fed_and_starves_without_food() {
250 // Enough food: eat one hour's ration and recover hunger.
251 let (h, eaten) = feed(0.5, 1.0, FOOD_PER_HOUR);
252 assert!((h - 0.48).abs() < 1e-6);
253 assert_eq!(eaten, FOOD_PER_HOUR);
254 // No food: eat nothing and hunger rises, capped at 1.
255 let (h, eaten) = feed(0.5, 0.49, FOOD_PER_HOUR);
256 assert!((h - 0.53).abs() < 1e-6);
257 assert_eq!(eaten, 0.0);
258 let (h, _) = feed(0.99, 0.0, FOOD_PER_HOUR);
259 assert_eq!(h, 1.0);
260 }
261}