1use indexmap::IndexSet;
10use serde_json::{json, Value};
11
12use crate::facilities::Kind;
13use crate::gameplay::{EmergencyDecision, EmergencyKind, EmergencySource, GameplayEvent};
14use crate::rng::Rng;
15use crate::services::with_thousands;
16use crate::sim::{LogKind, Simulation};
17use crate::tower::UnitState;
18
19#[path = "events_fire.rs"]
20mod fire;
21pub use fire::FireRescueRefusal;
22
23#[path = "events_bomb.rs"]
24#[doc(hidden)]
25pub mod bomb;
26#[path = "events_stairs.rs"]
27#[doc(hidden)]
28pub mod stairs;
29#[path = "events_thief.rs"]
30mod thief;
31pub use crate::economy::films::FilmRefusal;
34use crate::economy::films::FilmTier;
35use crate::economy::screens::{put_screens, screens};
36#[doc(hidden)]
37pub use bomb::{BombSearch, Guard};
38
39#[derive(Clone, Debug)]
41pub struct PendingChoice {
42 pub kind: &'static str,
45 pub cost: f64,
47 pub message: String,
49}
50
51pub struct EventSystem {
54 #[doc(hidden)]
55 pub active: IndexSet<i64>,
57 #[doc(hidden)]
58 pub fires_started: i64,
62 #[doc(hidden)]
63 pub fires_gut_rooms: i64,
64 #[doc(hidden)]
65 pub bombs_detonated: i64,
66 #[doc(hidden)]
67 pub extra: Rng,
69 #[doc(hidden)]
70 pub last_santa_year: f64,
73 pub pending: Option<PendingChoice>,
75 #[doc(hidden)]
76 pub bomb: Option<BombSearch>,
78}
79
80const SECURITY_RADIUS: i64 = 8;
81const MEDICAL_RADIUS: i64 = 12;
82const THIEF_DAILY_CHANCE: f64 = 0.025;
83
84impl EventSystem {
85 #[doc(hidden)]
86 pub fn new(seed: u32) -> EventSystem {
87 EventSystem {
88 active: IndexSet::new(),
89 fires_started: 0,
90 fires_gut_rooms: 0,
91 bombs_detonated: 0,
92 extra: Rng::new(seed ^ 0x5a17a),
93 last_santa_year: -1.0,
94 pending: None,
95 bomb: None,
96 }
97 }
98
99 #[doc(hidden)]
100 pub fn save_state(&self) -> Value {
105 let pending = match &self.pending {
106 Some(p) => json!({ "kind": p.kind, "cost": p.cost, "message": p.message }),
107 None => Value::Null,
108 };
109 let mut state = json!({ "lastSantaYear": self.last_santa_year, "rngState": self.extra.seed(), "pending": pending });
110 if let Some(b) = &self.bomb {
111 state["bomb"] = b.save_state();
112 }
113 state
114 }
115
116 #[doc(hidden)]
117 pub fn count(&self) -> usize {
118 self.active.len()
119 }
120}
121
122impl Simulation {
123 #[doc(hidden)]
124 pub fn maybe_random_event(&mut self) {
126 if self.events.pending.is_some() {
127 self.resolve_choice_from(false, EmergencySource::Timeout);
128 }
129 self.process_fires();
130 self.maybe_santa();
131 self.maybe_thief();
132 if self.star < 2 {
133 return;
134 }
135 let roll = self.rng.next();
136 let fire_chance = self.fire_chance();
137 let fire_allowed = || !self.mode.fire_needs_security() || self.has_any(Kind::Security);
139 if roll < fire_chance && self.events.active.is_empty() && fire_allowed() {
140 self.start_fire();
141 if !self.events.active.is_empty() {
142 self.offer_fire_rescue();
143 }
144 return;
145 }
146 let ransom_allowed = self.events.bomb.is_none()
147 && (!self.mode.ransom_needs_security() || self.has_any(Kind::Security));
148 if self.star >= 4 && roll < fire_chance + 0.05 && ransom_allowed {
149 let message = "๐ฃ A caller demands a $300,000 ransom or a bomb detonates. Pay, or have Security search the tower.".to_string();
150 self.events.pending = Some(PendingChoice {
151 kind: "bombThreat",
152 cost: 300_000.0,
153 message: message.clone(),
154 });
155 self.emit(&message, LogKind::Bad);
156 return;
157 }
158 if self.rng.chance(0.15) {
159 if self.rng.chance(0.5) {
160 self.emit(
161 "A local newspaper praised your tower's design.",
162 LogKind::Good,
163 );
164 } else {
165 self.emit("Tenants are happy with the tower today.", LogKind::Info);
166 }
167 }
168 }
169
170 pub fn resolve_choice(&mut self, accept: bool) {
175 self.outside_the_gesture(|s| s.resolve_choice_from(accept, EmergencySource::Player));
176 }
177
178 #[doc(hidden)]
179 pub fn resolve_choice_from(&mut self, accept: bool, source: EmergencySource) {
182 let Some(p) = self.events.pending.take() else {
183 return;
184 };
185 let paid = accept && self.money >= p.cost;
188 let kind = EmergencyKind::parse(p.kind).unwrap_or(EmergencyKind::BombThreat);
191 self.gameplay.push(GameplayEvent::EmergencyResolved {
192 kind,
193 decision: if paid {
194 EmergencyDecision::Accept
195 } else {
196 EmergencyDecision::Decline
197 },
198 source,
199 });
200 if kind == EmergencyKind::FireRescue {
201 if paid {
202 self.money -= p.cost;
203 self.extinguish_all();
204 self.emit(&format!("๐ Fire-rescue crews saved the tower for ${}. The rooms that were ablaze are gutted. Bulldoze and rebuild them.", with_thousands(p.cost)), LogKind::Money);
205 }
206 return;
207 }
208 if paid {
209 self.money -= p.cost;
210 self.emit(
211 &format!(
212 "๐ฃ You paid the ${} ransom; the threat passed quietly.",
213 with_thousands(p.cost)
214 ),
215 LogKind::Money,
216 );
217 } else {
218 self.start_bomb_search();
219 }
220 }
221
222 fn gut(&mut self, i: usize) {
223 let mode = self.tower.mode;
224 let (u, at) = self.tower.marked(i);
225 u.set_state(at, UnitState::Gutted);
226 u.set_occupants(at, 0);
227 u.ever_occupied = false;
228 u.set_residents(at, None);
229 u.set_visitors_yest(at, None);
231 u.satisfaction = 0.0;
232 u.pending_income = 0.0;
233 {
234 let mut extras = u.extras_mut();
235 extras.patronage_today = None;
236 extras.patronage_yest = None;
237 extras.profit_today = None;
238 extras.profit_yest = None;
239 extras.dirty_days = None;
240 }
241 if u.kind == Kind::Cinema {
242 let mut films = screens(mode, u);
245 for film in &mut films {
246 film.tier = FilmTier::New;
247 film.days = None;
248 }
249 put_screens(mode, u, films);
250 }
251 let name = u.kind.facility().name;
252 self.tower.set_unit_label_at(i, name.to_string());
253 }
254
255 fn extinguish_all(&mut self) {
256 let ids: Vec<i64> = self.events.active.iter().copied().collect();
257 let mut gutted = 0;
258 for id in ids {
259 if let Some(idx) = self.tower.units.iter().position(|u| u.id == id) {
260 if self.tower.units[idx].state == UnitState::Fire {
261 self.gut(idx);
262 self.events.fires_gut_rooms += 1;
263 gutted += 1;
264 }
265 }
266 }
267 self.events.active.clear();
268 self.note_gutted(gutted);
269 }
270
271 fn note_gutted(&mut self, rooms: i64) {
273 if rooms > 0 {
274 self.gameplay.push(GameplayEvent::FireGutted { rooms });
275 }
276 }
277
278 #[doc(hidden)]
279 pub fn fire_chance(&self) -> f64 {
280 let mut chance = 0.025;
281 if self.has_operational(Kind::Security) {
282 chance *= 0.45;
283 }
284 if self.has_operational(Kind::Medical) {
285 chance *= 0.5;
286 }
287 chance
288 }
289
290 pub(crate) fn fire_rescue_cost(&self) -> f64 {
291 (150_000.0 + ((self.star - 2).max(0) as f64) * 120_000.0).min(500_000.0)
292 }
293
294 fn flammable_units(&self) -> Vec<usize> {
296 (0..self.tower.units.len())
297 .filter(|&i| {
298 let u = &self.tower.units[i];
299 !u.kind.is_structural()
300 && u.state != UnitState::Construction
301 && u.state != UnitState::Fire
302 && u.state != UnitState::Gutted
303 })
304 .collect()
305 }
306
307 #[doc(hidden)]
308 pub fn start_fire(&mut self) {
310 let candidates = self.flammable_units();
311 if candidates.is_empty() {
312 return;
313 }
314 let i = *self.rng.pick(&candidates);
315 self.ignite(i);
316 }
317
318 fn service_within(&self, kind: Kind, floor: i64, radius: i64) -> bool {
319 self.tower
320 .units
321 .iter()
322 .any(|u| u.kind == kind && u.is_operational() && (u.floor - floor).abs() <= radius)
323 }
324
325 #[doc(hidden)]
326 pub fn control_chance(&self, floor: i64) -> f64 {
327 let sec = self.service_within(Kind::Security, floor, SECURITY_RADIUS);
328 let med = self.service_within(Kind::Medical, floor, MEDICAL_RADIUS);
329 0.5 + (if sec { 0.2 } else { 0.0 }) + (if med { 0.3 } else { 0.0 })
330 }
331
332 fn spread_fire_to(&mut self, target: Option<i64>) {
333 let Some(tid) = target else { return };
334 let Some(idx) = self.tower.units.iter().position(|u| u.id == tid) else {
335 return;
336 };
337 if !self.tower.units[idx].is_operational() {
338 return;
339 }
340 let kind = self.tower.units[idx].kind;
341 let mut ops = 0;
342 for x in &self.tower.units {
343 if x.kind == kind && x.is_operational() {
344 ops += 1;
345 if ops > 1 {
346 break;
347 }
348 }
349 }
350 if ops <= 1 {
351 return;
352 }
353 let (u, at) = self.tower.marked(idx);
354 u.set_state(at, UnitState::Fire);
355 u.set_occupants(at, 0);
356 let (id, name, floor) = (u.id, kind.facility().name, u.floor);
357 self.events.active.insert(id);
358 let msg = format!(
359 "The fire spread to {} on {}!",
360 name,
361 self.floor_label(floor)
362 );
363 self.emit(&msg, LogKind::Bad);
364 }
365
366 fn process_fires(&mut self) {
367 if self.events.active.is_empty() {
368 return;
369 }
370 let ids: Vec<i64> = self.events.active.iter().copied().collect();
371 let mut gutted = 0;
372 for id in ids {
373 let Some(idx) = self.tower.units.iter().position(|u| u.id == id) else {
374 self.events.active.shift_remove(&id);
375 continue;
376 };
377 if self.tower.units[idx].state != UnitState::Fire {
378 self.events.active.shift_remove(&id);
379 continue;
380 }
381 let (floor, x, width, name) = {
382 let u = &self.tower.units[idx];
383 (u.floor, u.x, u.width, u.kind.facility().name)
384 };
385 let control = self.control_chance(floor);
386 if self.rng.chance(control) {
387 self.gut(idx);
388 self.events.fires_gut_rooms += 1;
389 gutted += 1;
390 self.events.active.shift_remove(&id);
391 let msg = format!("๐ฅ The {} on {} burned down. Only a gutted shell remains. Bulldoze the rubble and rebuild.", name, self.floor_label(floor));
392 self.emit(&msg, LogKind::Bad);
393 } else {
394 let adjacent = self
395 .tower
396 .room_at(floor, x - 1)
397 .or_else(|| self.tower.room_at(floor, x + width))
398 .map(|u| u.id);
399 self.spread_fire_to(adjacent);
400 let above = self.tower.room_at(floor + 1, x).map(|u| u.id);
401 self.spread_fire_to(above);
402 }
403 }
404 self.note_gutted(gutted);
405 if !self.events.active.is_empty() {
406 for u in self.tower.units.iter_mut() {
407 if u.is_tenanted() || u.state == UnitState::Asleep {
408 u.satisfaction = (u.satisfaction - 0.05).max(0.0);
409 }
410 }
411 }
412 }
413
414 fn maybe_santa(&mut self) {
415 let cal = self.clock.calendar;
416 let year = self.clock.year();
417 let day_of_year = ((self.clock.day() % cal.year_days) + cal.year_days) % cal.year_days;
418 let holiday_start = cal.year_days
419 - (crate::jsmath::round((cal.year_days as f64 * 20.0) / 360.0) as i64).max(1);
420 if day_of_year < holiday_start
421 || self.star < 3
422 || year as f64 == self.events.last_santa_year
423 {
424 return;
425 }
426 if !self.events.extra.chance(0.4) {
427 return;
428 }
429 self.events.last_santa_year = year as f64;
430 self.emit(
431 "๐
Santa was spotted crossing the sky above your tower for the holidays!",
432 LogKind::Good,
433 );
434 self.fx.santa_seq += 1;
435 }
436}