Skip to main content
Verticopolis engine

verticopolis_engine/
charges.rs

1//! Commands that cost or refund money after a build: elevator cars
2//! ([`Simulation::add_car`], [`Simulation::remove_car`]), stretching a shaft
3//! ([`Simulation::extend_transport`]) and removing a room or a shaft
4//! ([`Simulation::remove_facility`]).
5//!
6//! Each one checks, changes the tower and moves the money in one step and
7//! reports the amount, so a frontend sends the command and never writes
8//! money itself.
9
10use crate::churn::household_price;
11use crate::econ::rent_config;
12use crate::facilities::Kind;
13use crate::gameplay::{GameplayEvent, RemovalMethod};
14use crate::services::with_thousands;
15use crate::sim::{LogKind, Simulation};
16use crate::tower::UnitState;
17
18/// The price of one more elevator car.
19pub const ADD_CAR_COST: f64 = 40_000.0;
20/// The price of each floor an elevator is built or extended past its first.
21pub const TRANSPORT_FLOOR_COST: f64 = 5_000.0;
22
23#[doc(hidden)]
24pub const NOT_ENOUGH_MONEY: &str = "Not enough money.";
25#[doc(hidden)]
26pub const ELEVATOR_GONE: &str = "That elevator is gone.";
27#[doc(hidden)]
28pub const ONLY_ELEVATOR_CARS: &str = "Only elevators have cars.";
29#[doc(hidden)]
30pub const ONLY_ELEVATOR_EXTEND: &str = "Only elevators can be extended.";
31#[doc(hidden)]
32pub const CAR_LIMIT: &str = "This elevator has all the cars it can hold.";
33#[doc(hidden)]
34pub const LAST_CAR: &str = "An elevator needs at least one car.";
35#[doc(hidden)]
36pub const FACILITY_GONE: &str = "That facility is gone.";
37#[doc(hidden)]
38pub const HOUSEKEEPING_PERMANENT: &str =
39    "Housekeeping rooms are permanent. The 1994 game does not let you remove them.";
40#[doc(hidden)]
41/// Classic never lets the wedding hall be sold or bulldozed.
42pub const CLASSIC_WEDDING_HALL_KEPT: &str = "The wedding hall can't be removed.";
43#[doc(hidden)]
44pub const SECURITY_PERMANENT: &str =
45    "Security offices are permanent. The 1994 game does not let you remove them.";
46#[doc(hidden)]
47pub const RECYCLING_PERMANENT: &str =
48    "Recycling centers are permanent. The 1994 game does not let you remove them.";
49#[doc(hidden)]
50pub const CINEMA_PERMANENT: &str =
51    "Movie theaters are permanent. The 1994 game does not let you remove them.";
52
53/// The refusal for a Classic room `GameMode::room_is_permanent` keeps.
54fn permanent_room_refusal(kind: Kind) -> &'static str {
55    match kind {
56        Kind::Security => SECURITY_PERMANENT,
57        Kind::Recycling => RECYCLING_PERMANENT,
58        Kind::Cinema => CINEMA_PERMANENT,
59        Kind::WeddingHall => CLASSIC_WEDDING_HALL_KEPT,
60        _ => HOUSEKEEPING_PERMANENT,
61    }
62}
63/// The refusal for a malformed command, such as a brush with too many tiles.
64/// The JavaScript binding also gives it for an id or floor that is not a
65/// whole number, or an unknown name; a Rust host passes typed values and
66/// never sees those cases.
67pub const INVALID_REQUEST: &str = "That request is not valid.";
68
69#[doc(hidden)]
70/// A whole number a command may take, as TypeScript's `Number.isSafeInteger`
71/// reads it: finite, no fraction, within 2^53 - 1. NaN and infinities fail.
72pub fn whole(x: f64) -> Option<i64> {
73    (x.fract() == 0.0 && x.abs() <= 9_007_199_254_740_991.0).then_some(x as i64)
74}
75
76#[doc(hidden)]
77/// `carResaleRefund()`: half the add-car cost.
78pub fn car_resale_refund() -> f64 {
79    (ADD_CAR_COST * 0.5).floor()
80}
81
82/// What a charged command did.
83#[derive(Clone, Debug, PartialEq)]
84pub struct ChargeResult {
85    /// Whether it was carried out.
86    pub ok: bool,
87    /// Why it was refused, ready to show a player. `None` when carried out.
88    pub reason: Option<String>,
89    /// The change to the player's money: negative for a charge, positive for
90    /// a refund, 0 when refused.
91    pub delta: f64,
92}
93
94impl ChargeResult {
95    pub(crate) fn refuse(reason: impl Into<String>) -> ChargeResult {
96        ChargeResult {
97            ok: false,
98            reason: Some(reason.into()),
99            delta: 0.0,
100        }
101    }
102
103    pub(crate) fn paid(delta: f64) -> ChargeResult {
104        ChargeResult {
105            ok: true,
106            reason: None,
107            delta,
108        }
109    }
110}
111
112/// What an extension did: the charge, and the shaft's span afterwards.
113#[derive(Clone, Debug, PartialEq)]
114pub struct ExtendResult {
115    /// The money moved, or the refusal.
116    pub charge: ChargeResult,
117    /// The shaft's lowest floor afterwards.
118    pub bottom: i64,
119    /// The shaft's highest floor afterwards.
120    pub top: i64,
121    /// How many floors this call billed.
122    pub added: i64,
123}
124
125/// Which end of a shaft an extension moves.
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub enum ExtendEnd {
128    /// Move the top floor.
129    Up,
130    /// Move the bottom floor.
131    Down,
132}
133
134impl ExtendEnd {
135    /// `up` or `down`.
136    pub fn parse(s: &str) -> Option<ExtendEnd> {
137        match s {
138            "up" => Some(ExtendEnd::Up),
139            "down" => Some(ExtendEnd::Down),
140            _ => None,
141        }
142    }
143}
144
145#[doc(hidden)]
146/// `extendBill`: one step of budget-clamped billing for an elevator extend.
147/// Returns the new ends and the count of floors past the high-water mark.
148pub fn extend_bill(
149    cur: (i64, i64),
150    hwm: (i64, i64),
151    end: ExtendEnd,
152    target_floor: i64,
153    money: f64,
154    per_floor: f64,
155) -> (i64, i64, i64) {
156    let (mut nb, mut nt) = cur;
157    match end {
158        ExtendEnd::Up => nt = (cur.0 + 1).max(target_floor),
159        ExtendEnd::Down => nb = (cur.1 - 1).min(target_floor),
160    }
161    let budget = (money / per_floor).floor().max(0.0);
162    // The budget is a whole count of floors; a balance too large for i64
163    // saturates, which still pays for any span the tower can hold.
164    let budget = if budget > i64::MAX as f64 {
165        i64::MAX
166    } else {
167        budget as i64
168    };
169    if nt > hwm.1 {
170        nt = hwm.1 + (nt - hwm.1).min(budget);
171    }
172    if nb < hwm.0 {
173        nb = hwm.0 - (hwm.0 - nb).min(budget);
174    }
175    let added = (nt - hwm.1).max(0) + (hwm.0 - nb).max(0);
176    (nb, nt, added)
177}
178
179impl Simulation {
180    /// The shaft behind an elevator command: `(kind, cars, bottom, top)`, or
181    /// the refusal to return.
182    fn elevator(&self, id: i64, not_elevator: &str) -> Result<(Kind, i64, i64, i64), ChargeResult> {
183        let Some(t) = self.tower.get_transport(id) else {
184            return Err(ChargeResult::refuse(ELEVATOR_GONE));
185        };
186        if !t.kind.is_elevator() {
187            return Err(ChargeResult::refuse(not_elevator));
188        }
189        Ok((t.kind, t.cars, t.bottom, t.top))
190    }
191
192    /// Buys one more car for elevator `id` at [`ADD_CAR_COST`]. Refused at the
193    /// elevator's car limit, when the money is short and during a bomb
194    /// search ([`edit_refusal`](Simulation::edit_refusal)).
195    pub fn add_car(&mut self, id: i64) -> ChargeResult {
196        if let Some(reason) = self.edit_refusal() {
197            return ChargeResult::refuse(reason);
198        }
199        let (kind, cars, _, _) = match self.elevator(id, ONLY_ELEVATOR_CARS) {
200            Ok(t) => t,
201            Err(r) => return r,
202        };
203        if cars >= kind.max_cars() {
204            return ChargeResult::refuse(CAR_LIMIT);
205        }
206        if self.money < ADD_CAR_COST {
207            return ChargeResult::refuse(NOT_ENOUGH_MONEY);
208        }
209        if !self.set_cars(id, cars + 1) {
210            return ChargeResult::refuse(CAR_LIMIT);
211        }
212        self.money -= ADD_CAR_COST;
213        self.note_edit_cash(-ADD_CAR_COST);
214        ChargeResult::paid(-ADD_CAR_COST)
215    }
216
217    /// Sells one car of elevator `id` back for half of [`ADD_CAR_COST`].
218    /// Refused on the last car and during a bomb search.
219    pub fn remove_car(&mut self, id: i64) -> ChargeResult {
220        if let Some(reason) = self.edit_refusal() {
221            return ChargeResult::refuse(reason);
222        }
223        let (_, cars, _, _) = match self.elevator(id, ONLY_ELEVATOR_CARS) {
224            Ok(t) => t,
225            Err(r) => return r,
226        };
227        if cars <= 1 || !self.set_cars(id, cars - 1) {
228            return ChargeResult::refuse(LAST_CAR);
229        }
230        let refund = car_resale_refund();
231        self.money += refund;
232        self.note_edit_cash(refund);
233        ChargeResult::paid(refund)
234    }
235
236    /// Starts a drag that stretches elevator `id`. Until
237    /// [`end_extend`](Simulation::end_extend), the
238    /// [`extend_transport`](Simulation::extend_transport) calls bill each floor
239    /// once, however far the player drags back and forth. Returns `false`
240    /// when `id` is not an elevator.
241    pub fn begin_extend(&mut self, id: i64) -> bool {
242        self.extend_gesture = None;
243        match self.elevator(id, ONLY_ELEVATOR_EXTEND) {
244            Ok((_, _, bottom, top)) => {
245                self.extend_gesture = Some((id, bottom, top));
246                true
247            }
248            Err(_) => false,
249        }
250    }
251
252    /// A host handing over its open gesture with a load (#990): kept as given
253    /// when `id` names an elevator (the shafts `beginExtend` accepts), and
254    /// widened to the span at use like any gesture. Not a binding command:
255    /// a caller that can hand over a mark here can hand over a whole save.
256    #[cfg_attr(not(feature = "wasm"), allow(dead_code))]
257    pub(crate) fn restore_extend(&mut self, id: i64, bottom: i64, top: i64) {
258        self.extend_gesture = self
259            .elevator(id, ONLY_ELEVATOR_EXTEND)
260            .ok()
261            .map(|_| (id, bottom, top));
262    }
263
264    /// Ends the drag [`begin_extend`](Simulation::begin_extend) started.
265    pub fn end_extend(&mut self) {
266        self.extend_gesture = None;
267    }
268
269    /// Moves one end of elevator `id` toward `target_floor`, charging
270    /// [`TRANSPORT_FLOOR_COST`] for each new floor. It grows only as far as
271    /// the money pays for. During a drag, a floor already paid for is not
272    /// billed again.
273    ///
274    /// ```
275    /// use verticopolis_engine::charges::ExtendEnd;
276    /// use verticopolis_engine::clock::GameMode;
277    /// use verticopolis_engine::facilities::Kind;
278    /// use verticopolis_engine::sim::Simulation;
279    ///
280    /// let mut sim = Simulation::new_game(1, GameMode::Classic);
281    /// for floor in 1..=6 {
282    ///     let kind = if floor == 1 { Kind::Lobby } else { Kind::Floor };
283    ///     for x in 100..124 {
284    ///         sim.build(kind, floor, x);
285    ///     }
286    /// }
287    /// sim.build_transport(Kind::ElevatorStandard, 110, 1, 3);
288    /// let id = sim.tower.transports[0].id;
289    ///
290    /// sim.begin_extend(id);
291    /// let grown = sim.extend_transport(id, ExtendEnd::Up, 6);
292    /// sim.end_extend();
293    /// assert_eq!((grown.bottom, grown.top, grown.added), (1, 6, 3));
294    /// ```
295    pub fn extend_transport(&mut self, id: i64, end: ExtendEnd, target_floor: i64) -> ExtendResult {
296        let found = match self.edit_refusal() {
297            Some(reason) => Err(ChargeResult::refuse(reason)),
298            None => self.elevator(id, ONLY_ELEVATOR_EXTEND),
299        };
300        let (_, _, bottom, top) = match found {
301            Ok(t) => t,
302            Err(charge) => {
303                let (bottom, top) = self
304                    .tower
305                    .get_transport(id)
306                    .map_or((0, 0), |t| (t.bottom, t.top));
307                return ExtendResult {
308                    charge,
309                    bottom,
310                    top,
311                    added: 0,
312                };
313            }
314        };
315        let gesture = self
316            .extend_gesture
317            .filter(|&(gid, _, _)| gid == id)
318            .map(|(_, b, t)| (b, t));
319        let (hb, ht) = gesture.unwrap_or((bottom, top));
320        let mark = (hb.min(bottom), ht.max(top));
321        let (nb, nt, added) = extend_bill(
322            (bottom, top),
323            mark,
324            end,
325            target_floor,
326            self.money,
327            TRANSPORT_FLOOR_COST,
328        );
329        let unchanged = |charge: ChargeResult| ExtendResult {
330            charge,
331            bottom,
332            top,
333            added: 0,
334        };
335        if nb == bottom && nt == top {
336            let wanted = match end {
337                ExtendEnd::Up => target_floor > mark.1,
338                ExtendEnd::Down => target_floor < mark.0,
339            };
340            return unchanged(if wanted {
341                ChargeResult::refuse(NOT_ENOUGH_MONEY)
342            } else {
343                ChargeResult::paid(0.0)
344            });
345        }
346        let r = self.resize_transport(id, nb, nt);
347        if !r.ok {
348            return unchanged(ChargeResult {
349                ok: false,
350                reason: r.reason,
351                delta: 0.0,
352            });
353        }
354        let cost = added as f64 * TRANSPORT_FLOOR_COST;
355        self.money -= cost;
356        self.note_edit_cash(-cost);
357        if gesture.is_some() {
358            self.extend_gesture = Some((id, mark.0.min(nb), mark.1.max(nt)));
359        }
360        ExtendResult {
361            charge: ChargeResult::paid(if cost == 0.0 { 0.0 } else { -cost }),
362            bottom: nb,
363            top: nt,
364            added,
365        }
366    }
367
368    /// Sells whatever stands at a tile: a room first, then a shaft, then the
369    /// floor or lobby tile. Returns whether anything was sold. The refund and
370    /// the refusals are [`remove_facility`](Simulation::remove_facility)'s
371    /// with [`RemovalMethod::Sell`].
372    pub fn sell_at(&mut self, floor: i64, x: i64) -> bool {
373        let t = self.tower.transport_at(floor, x).map(|t| t.id);
374        let u = self.tower.unit_at(floor, x).map(|u| (u.id, u.kind));
375        let id = match (u, t) {
376            (Some((id, kind)), _) if !kind.is_structural() => id,
377            (_, Some(id)) => id,
378            (Some((id, _)), None) => id,
379            (None, None) => return false,
380        };
381        self.remove_facility(id, RemovalMethod::Sell).ok
382    }
383
384    /// Removes room or shaft `id` and refunds half its build price (nothing
385    /// for a room a fire gutted). `method` says whether the player sold it or
386    /// bulldozed it, for the gameplay event. Refused during a bomb search
387    /// ([`edit_refusal`](Simulation::edit_refusal)), for a burning room and
388    /// for a room the mode keeps for good. Rooms and shafts share one id
389    /// sequence, so `id` names exactly one thing.
390    pub fn remove_facility(&mut self, id: i64, method: RemovalMethod) -> ChargeResult {
391        if let Some(reason) = self.edit_refusal() {
392            return ChargeResult::refuse(reason);
393        }
394        if let Some(u) = self.tower.get_unit(id) {
395            if let Some(cols) = self.tower.skybridge_of(u) {
396                return self.remove_skybridge(u.floor, cols, method);
397            }
398            let (kind, state) = (u.kind, u.state);
399            if state == UnitState::Fire {
400                return ChargeResult::refuse(format!(
401                    "You can't {} a burning unit. Call fire rescue or let it burn out.",
402                    method.as_str()
403                ));
404            }
405            if let Some(reason) = self.tower.removal_reason(id) {
406                return ChargeResult::refuse(reason);
407            }
408            if self.stays_for_good(kind, state) {
409                return ChargeResult::refuse(permanent_room_refusal(kind));
410            }
411            let refund = if state == UnitState::Gutted {
412                0.0
413            } else {
414                self.tower.sale_refund(u)
415            };
416            // A sold condo belongs to its household: removing it buys the
417            // unit back at the price it sold for, as an owner leaving does
418            // (`vacate`), before the shell's resale refund (#713).
419            let buyback = self.sold_condo_buyback(id, state);
420            if buyback > 0.0 && self.money + refund < buyback {
421                return ChargeResult::refuse(format!(
422                    "You can't {} this condo without buying it back for ${}.",
423                    method.as_str(),
424                    with_thousands(buyback)
425                ));
426            }
427            let floor = self.tower.get_unit(id).map(|u| u.floor).unwrap_or(0);
428            self.tower.remove_unit(id);
429            if buyback > 0.0 {
430                let msg = format!(
431                    "You bought back Condominium on {} for ${} to remove it.",
432                    self.floor_label(floor),
433                    with_thousands(buyback)
434                );
435                self.emit(&msg, LogKind::Money);
436            }
437            let refund = refund - buyback;
438            self.money += refund;
439            self.note_edit_cash(refund);
440            if kind == Kind::WeddingHall
441                && self.tower.built_wedding_hall != Some(true)
442                && self.evaluated_tower != Some(true)
443            {
444                self.edit_vip_visit_day(-1.0);
445            }
446            self.gameplay
447                .push(GameplayEvent::FacilityRemoved { kind, method });
448            return ChargeResult::paid(refund);
449        }
450        let Some(kind) = self.tower.get_transport(id).map(|t| t.kind) else {
451            return ChargeResult::refuse(FACILITY_GONE);
452        };
453        self.tower.remove_transport(id);
454        let refund = kind.resale_refund();
455        self.money += refund;
456        self.note_edit_cash(refund);
457        self.gameplay
458            .push(GameplayEvent::FacilityRemoved { kind, method });
459        ChargeResult::paid(refund)
460    }
461
462    /// What removing unit `id` costs to buy back: the price a sold condo's
463    /// household paid (scaled by its size, as `vacate` buys it back), or
464    /// nothing for any other room, an unsold condo or a gutted shell.
465    fn sold_condo_buyback(&self, id: i64, state: UnitState) -> f64 {
466        match self.tower.get_unit(id) {
467            Some(u) if u.kind == Kind::Condo && u.ever_occupied && state != UnitState::Gutted => {
468                let sale_price = u
469                    .rent
470                    .unwrap_or_else(|| rent_config(Kind::Condo).map(|c| c.default).unwrap_or(0.0));
471                household_price(sale_price, u.residents)
472            }
473            _ => 0.0,
474        }
475    }
476
477    /// Whether the tower keeps a room of `kind` in `state` for good, so no
478    /// removal takes it: a Classic permanent room stays unless a fire gutted
479    /// it, as a burned-out shell can still be cleared and the tile is not
480    /// lost.
481    pub(crate) fn stays_for_good(&self, kind: Kind, state: UnitState) -> bool {
482        state != UnitState::Gutted && self.mode.room_is_permanent(kind)
483    }
484}
485
486#[cfg(test)]
487#[path = "charges_tests.rs"]
488mod tests;
489
490#[cfg(test)]
491#[path = "charges_removal_tests.rs"]
492mod removal_tests;
493
494#[cfg(test)]
495#[path = "charges_floor_end_tests.rs"]
496pub(crate) mod floor_end_tests;
497
498#[cfg(test)]
499#[path = "charges_schedule_tests.rs"]
500mod schedule_tests;