Skip to main content
Verticopolis engine

verticopolis_engine/
build.rs

1//! Placing and selling: [`Simulation::build`] for floors, lobbies and rooms,
2//! [`Simulation::build_transport`] for elevators, stairs and escalators, and
3//! [`Simulation::sell_at`]. Each build has a dry run
4//! ([`Simulation::can_build`], [`Simulation::can_build_transport`]) that
5//! answers with the same refusal and the full price, for a placement ghost.
6//!
7//! A refused command changes nothing and says why in a sentence a player can
8//! read. A placed one charges the money, logs the purchase and emits its
9//! gameplay events.
10
11use crate::facilities::*;
12use crate::gameplay::GameplayEvent;
13use crate::rules::RentModel;
14use crate::sim::{LogKind, Simulation};
15use crate::tower::UnitState;
16
17/// What a build did.
18pub struct BuildResult {
19    /// Whether it was placed.
20    pub ok: bool,
21    /// Why it was refused, ready to show a player. `None` when placed.
22    pub reason: Option<String>,
23}
24
25impl BuildResult {
26    fn fail(reason: impl Into<String>) -> BuildResult {
27        BuildResult {
28            ok: false,
29            reason: Some(reason.into()),
30        }
31    }
32}
33
34/// The answer to a dry run: what the build would do, and its price.
35pub struct CanBuild {
36    /// Whether the build would be placed.
37    pub ok: bool,
38    /// Why it would be refused. `None` when it would be placed.
39    pub reason: Option<String>,
40    /// The full price, in dollars, floors and bridged tiles included. It is
41    /// set even when the build would be refused.
42    pub cost: f64,
43}
44
45/// Whether a tile of `kind` placed where there is no floor yet also pays for
46/// the floor it lays. A lobby does, as in the original: a bare lobby tile
47/// costs the lobby's price plus the floor's, and a lobby over a floor tile
48/// the lobby's price alone. The catalog publishes this as `paysForFloor`.
49pub fn pays_for_floor(kind: Kind) -> bool {
50    kind == Kind::Lobby
51}
52
53/// The price of one bridged substrate tile: a lobby tile `stories` high when
54/// the placement is a lobby, a floor tile otherwise. A bridge fills only
55/// empty tiles, so a bridged tile of a kind that pays for its floor
56/// ([`pays_for_floor`]) adds the floor's price. Read from the facility table,
57/// the same prices the catalog quotes.
58pub(crate) fn substrate_cost(kind: Kind, stories: i64) -> f64 {
59    if kind == Kind::Lobby {
60        bare_tile_cost(Kind::Lobby, stories)
61    } else {
62        bare_tile_cost(Kind::Floor, 1)
63    }
64}
65
66/// The price of a tile of `kind`, `stories` high, placed where there is no
67/// floor yet. A tall lobby pays the lobby's price once for each story it
68/// covers (#308: the original's 2-story lobby costs twice the 1-story one,
69/// and its 3-story lobby three times), and for one floor tile under it.
70fn bare_tile_cost(kind: Kind, stories: i64) -> f64 {
71    let tile = kind.facility().cost * stories as f64;
72    if pays_for_floor(kind) {
73        tile + Kind::Floor.facility().cost
74    } else {
75        tile
76    }
77}
78
79/// Classic's refusal for any room but the wedding hall on the top floor.
80pub(crate) fn classic_top_floor_reason(top_floor: i64) -> String {
81    format!("Only the wedding hall can be built on floor {top_floor}.")
82}
83
84/// The buried-treasure log line.
85pub(crate) fn treasure_message(gold: f64) -> String {
86    format!(
87        "๐Ÿ’ฐ Excavation crews unearthed buried treasure worth ${}!",
88        crate::services::with_thousands(gold)
89    )
90}
91
92impl Simulation {
93    /// Turns automatic floor bridging off or on, and returns the new setting.
94    /// Only a Modern game can turn it off; a Classic game always bridges and
95    /// this returns `true`.
96    pub fn toggle_auto_bridge(&mut self) -> bool {
97        if self.mode.bridging_toggleable() {
98            self.auto_bridge = !self.auto_bridge;
99        }
100        self.auto_bridge
101    }
102
103    #[doc(hidden)]
104    pub fn is_unlocked(&self, kind: Kind) -> bool {
105        let f = kind.facility();
106        f.available_in(self.mode) && self.star >= f.min_star
107    }
108
109    /// The price of the tile a structural placement lays at `(floor, x)`: a
110    /// lobby placed where there is no floor yet pays for that floor too
111    /// ([`pays_for_floor`]); a lobby over a floor tile turns it into lobby
112    /// for the lobby's price alone.
113    /// A sky bridge tile, a lobby tile over open air, costs
114    /// `SKYBRIDGE_PRICE_FACTOR` times a lobby tile on a story.
115    fn structure_tile_cost(&self, kind: Kind, floor: i64, x: i64, stories: i64) -> f64 {
116        if self.tower.has_structure(floor, x) {
117            kind.facility().cost * stories as f64
118        } else if kind == Kind::Lobby && self.tower.lays_skybridge_at(floor, x) {
119            bare_tile_cost(kind, stories) * crate::tower::SKYBRIDGE_PRICE_FACTOR
120        } else {
121            bare_tile_cost(kind, stories)
122        }
123    }
124
125    /// The dry run [`build`](Simulation::build) makes first: whether a
126    /// `kind` at `(floor, x)` would be placed, why not, and its full price.
127    /// Changes nothing.
128    ///
129    /// ```
130    /// use verticopolis_engine::clock::GameMode;
131    /// use verticopolis_engine::facilities::Kind;
132    /// use verticopolis_engine::sim::Simulation;
133    ///
134    /// let sim = Simulation::new_game(1, GameMode::Classic);
135    /// let quote = sim.can_build(Kind::Lobby, 1, 100);
136    /// assert!(quote.ok);
137    /// assert!(quote.cost > 0.0);
138    /// ```
139    pub fn can_build(&self, kind: Kind, floor: i64, x: i64) -> CanBuild {
140        let kind = ground_floor_structure_kind(kind, floor);
141        let f = kind.facility();
142        if let Some(reason) = self.edit_refusal() {
143            return CanBuild {
144                ok: false,
145                reason: Some(reason.into()),
146                cost: f.cost,
147            };
148        }
149        if !self.is_unlocked(kind) {
150            let reason = if !f.available_in(self.mode) {
151                format!("{} is a Modern-only facility.", f.name)
152            } else {
153                format!("{} unlocks at {}โ˜….", f.name, f.min_star)
154            };
155            return CanBuild {
156                ok: false,
157                reason: Some(reason),
158                cost: f.cost,
159            };
160        }
161        let money_check = |cost: f64| CanBuild {
162            ok: self.money >= cost,
163            reason: if self.money >= cost {
164                None
165            } else {
166                Some("Not enough money.".into())
167            },
168            cost,
169        };
170        // `!isRoomKind(kind)`: floor, lobby and every transport kind take the
171        // structural branch, where `canPlace` refuses a transport by name.
172        if !kind.is_room() {
173            if !self.auto_bridge {
174                let c = self.tower.can_place(kind, floor, x);
175                if !c.ok {
176                    return CanBuild {
177                        ok: false,
178                        reason: c.reason,
179                        cost: f.cost,
180                    };
181                }
182                let stories = self.tile_stories(kind, floor, x);
183                return money_check(self.structure_tile_cost(kind, floor, x, stories));
184            }
185            let plan = self.tower.bridge_fill_plan(kind, floor, x, 1, 1);
186            let c = self.tower.can_place(kind, floor, x);
187            if !c.ok {
188                let horizontal = if kind == Kind::Lobby {
189                    floor == 1
190                } else {
191                    floor < 2
192                };
193                let rescued = horizontal
194                    && !plan.is_empty()
195                    && self
196                        .tower
197                        .can_place_structure_ignoring_support(kind, floor, x)
198                        .ok;
199                if !rescued {
200                    return CanBuild {
201                        ok: false,
202                        reason: c.reason,
203                        cost: f.cost,
204                    };
205                }
206            }
207            let laid = self.bridged_tile(kind, floor, x, &plan);
208            return money_check(
209                self.structure_tile_cost(kind, floor, x, laid.stories) + laid.bridge_cost,
210            );
211        }
212        let pre = self.tower.can_place_room_ignoring_floor(kind, floor, x);
213        if !pre.ok {
214            return CanBuild {
215                ok: false,
216                reason: pre.reason,
217                cost: f.cost,
218            };
219        }
220        // Floor slabs end at the lot's top floor: the wedding hall's upper
221        // stories stand above them.
222        let lot = self.tower.lot();
223        let hgt = lot.slab_stories(kind, floor);
224        let missing = self.tower.missing_floor_count(floor, x, f.width, hgt);
225        if missing > 0 && !self.tower.span_connects(floor, x, f.width, hgt) {
226            let reason = if floor >= 2 {
227                "Rooms must sit on the floor below: no floating overhangs."
228            } else {
229                "Build next to the tower. You can't build in midair."
230            };
231            return CanBuild {
232                ok: false,
233                reason: Some(reason.into()),
234                cost: f.cost,
235            };
236        }
237        // Classic keeps the top floor for the wedding hall alone. This sits
238        // after every shared refusal reason, so the TypeScript reasons still
239        // win where both engines refuse.
240        if self
241            .mode
242            .refuses_room_on_reserved_top_floor(lot, kind, floor)
243        {
244            return CanBuild {
245                ok: false,
246                reason: Some(classic_top_floor_reason(lot.top_floor())),
247                cost: f.cost,
248            };
249        }
250        let bridge = if self.auto_bridge {
251            self.tower
252                .bridge_fill_plan(kind, floor, x, f.width, hgt)
253                .len() as i64
254        } else {
255            0
256        };
257        money_check(f.cost + ((missing + bridge) as f64) * Kind::Floor.facility().cost)
258    }
259
260    /// Places a floor tile, a lobby tile or a room with its left edge at
261    /// tile `x` and its bottom on `floor`, and charges for it.
262    ///
263    /// A room needs a floor under each of its tiles or bridges the gap when
264    /// [`auto_bridge`](Simulation::auto_bridge) is on, paying for the floor it
265    /// lays. Floors and lobbies are laid one tile at a time; to lay a run, call
266    /// [`paint_brush`](Simulation::paint_brush). A refused build changes
267    /// nothing. Floor 1 is the ground floor and basements are 0 and below.
268    ///
269    /// ```
270    /// use verticopolis_engine::clock::GameMode;
271    /// use verticopolis_engine::facilities::Kind;
272    /// use verticopolis_engine::sim::Simulation;
273    ///
274    /// let mut sim = Simulation::new_game(1, GameMode::Classic);
275    /// assert!(sim.build(Kind::Lobby, 1, 100).ok);
276    ///
277    /// // Offices open at one star, but not on a bare lot five floors up.
278    /// let refused = sim.build(Kind::Office, 5, 300);
279    /// assert!(!refused.ok);
280    /// println!("{}", refused.reason.unwrap());
281    /// ```
282    pub fn build(&mut self, kind: Kind, floor: i64, x: i64) -> BuildResult {
283        let kind = ground_floor_structure_kind(kind, floor);
284        let can = self.can_build(kind, floor, x);
285        if !can.ok {
286            return BuildResult {
287                ok: false,
288                reason: can.reason,
289            };
290        }
291        let f = kind.facility();
292        let lot = self.tower.lot();
293        let hgt = lot.slab_stories(kind, floor);
294        let quoted_bridge = if self.auto_bridge {
295            let plan = self.tower.bridge_fill_plan(kind, floor, x, f.width, hgt);
296            self.bridged_tile(kind, floor, x, &plan).bridge_cost
297        } else {
298            0.0
299        };
300        if kind.is_room() {
301            if let Err(reason) = self.tower.ensure_floor_under(floor, x, f.width, hgt) {
302                return BuildResult::fail(reason);
303            }
304        }
305        let laid_bridge = if self.auto_bridge {
306            self.tower.fill_bridge(kind, floor, x, f.width, hgt)
307        } else {
308            Vec::new()
309        };
310        let res = self.tower.place(kind, floor, x);
311        if !res.ok {
312            self.tower.remove_units(&laid_bridge);
313            return BuildResult {
314                ok: false,
315                reason: res.reason,
316            };
317        }
318        let laid_cost: f64 = (laid_bridge.iter().filter_map(|&id| self.tower.get_unit(id)))
319            .map(|u| substrate_cost(kind, self.tower.unit_stories(u)))
320            .sum();
321        let price = can.cost - quoted_bridge + laid_cost;
322        self.money -= price;
323        self.note_edit_cash(-price);
324        if let Some(id) = res.unit_id {
325            if let Some(list) = kind.subtype_list() {
326                let name = *self.rng.pick(list);
327                self.tower.set_unit_subtype(id, Some(name));
328            }
329            if let Some(RentModel::Ladder(ladder)) = self.mode.rent_model(kind) {
330                let cfg = crate::econ::rent_config(kind).unwrap();
331                let v = ladder[crate::rent::AVERAGE_RUNG];
332                self.tower.get_unit_mut(id).unwrap().rent =
333                    if v == cfg.default { None } else { Some(v) };
334            }
335            let dur = kind.build_minutes();
336            if dur > 0.0 {
337                let (u, at) = self.tower.marked_by_id(id).unwrap();
338                u.set_state(at, UnitState::Construction);
339                u.extras_mut().complete_at = Some(self.clock.minutes + dur);
340                self.constructing.insert(id);
341            }
342            if kind == Kind::WeddingHall {
343                self.emit(
344                    "Wedding Hall built! A VIP will inspect your tower soon.",
345                    LogKind::Good,
346                );
347                self.edit_vip_visit_day((self.clock.day() + 3) as f64);
348            }
349            if floor <= 0 && kind.is_room() {
350                let mut fresh = false;
351                for fl in floor..floor + hgt {
352                    for i in 0..f.width {
353                        let key = format!("{fl}:{}", x + i);
354                        if !self.excavated.contains(&key) {
355                            fresh = true;
356                            self.excavated.push(key);
357                        }
358                    }
359                }
360                // A search the player could undo would be free.
361                if fresh && self.treasures_found < 3.0 {
362                    self.note_treasure_search();
363                }
364                if fresh && self.treasures_found < 3.0 && self.rng.chance(0.18) {
365                    self.treasures_found += 1.0;
366                    let gold = 400_000.0 + self.rng.int(0, 200_000) as f64;
367                    self.money += gold;
368                    self.emit(&treasure_message(gold), LogKind::Money);
369                    // `triggerTreasure(floor, x + Math.floor(f.width / 2))`.
370                    self.fx.treasure = crate::sim::PointFx {
371                        floor,
372                        x: (x + f.width.div_euclid(2)) as f64,
373                        seq: self.fx.treasure.seq + 1,
374                    };
375                }
376            }
377        }
378        self.gameplay.push(GameplayEvent::FacilityPlaced {
379            kind,
380            floor: lot.highest_slab_story(floor, hgt),
381            count: 1,
382        });
383        BuildResult {
384            ok: true,
385            reason: None,
386        }
387    }
388
389    /// The dry run [`build_transport`](Simulation::build_transport) makes
390    /// first: whether a shaft of `kind` at `x` spanning `bottom..=top` would
391    /// be placed, why not, and its full price. Changes nothing.
392    ///
393    /// An elevator costs the catalog `cost` plus `transportFloorCost` for
394    /// each floor past its first; stairs and escalators cost the catalog
395    /// `cost`. Refusals come in the build's order: not unlocked yet, then
396    /// money, then placement. The price is only a shaft's price for a
397    /// transport kind with `top` above `bottom`; anything else is refused.
398    pub fn can_build_transport(&self, kind: Kind, x: i64, bottom: i64, top: i64) -> CanBuild {
399        let f = kind.facility();
400        // Saturating, as are the placement checks, so an out-of-range span
401        // from a native host prices without overflowing: an elevator's price
402        // then outruns any ordinary balance, so the money check refuses it
403        // (failing that, the span rule does), and a fixed-price shaft reaches
404        // the placement rules. Any span the tower can hold is exact.
405        let span = top.saturating_sub(bottom);
406        let extra = if kind.is_elevator() {
407            span as f64 * crate::charges::TRANSPORT_FLOOR_COST
408        } else {
409            0.0
410        };
411        let cost = f.cost + extra;
412        let refuse = |reason: String| CanBuild {
413            ok: false,
414            reason: Some(reason),
415            cost,
416        };
417        if let Some(reason) = self.edit_refusal() {
418            return refuse(reason.into());
419        }
420        if !self.is_unlocked(kind) {
421            return refuse(format!("{} unlocks at {}โ˜….", f.name, f.min_star));
422        }
423        if self.money < cost {
424            return refuse("Not enough money.".into());
425        }
426        let v = self.tower.validate_transport(kind, x, bottom, top);
427        if !v.ok {
428            return CanBuild {
429                ok: false,
430                reason: v.reason,
431                cost,
432            };
433        }
434        CanBuild {
435            ok: true,
436            reason: None,
437            cost,
438        }
439    }
440
441    /// Places an elevator, stairs or an escalator with its left edge at tile
442    /// `x`, serving floors `bottom` to `top`, and charges for it. A new
443    /// elevator starts with one car for every six floors it serves, up to its
444    /// kind's limit; [`add_car`](Simulation::add_car) adds more. Stairs and
445    /// escalators span exactly two floors.
446    ///
447    /// ```
448    /// use verticopolis_engine::clock::GameMode;
449    /// use verticopolis_engine::facilities::Kind;
450    /// use verticopolis_engine::sim::Simulation;
451    ///
452    /// let mut sim = Simulation::new_game(1, GameMode::Classic);
453    /// for x in 100..124 {
454    ///     sim.build(Kind::Lobby, 1, x);
455    /// }
456    /// for floor in 2..=4 {
457    ///     for x in 100..124 {
458    ///         sim.build(Kind::Floor, floor, x);
459    ///     }
460    /// }
461    /// let shaft = sim.build_transport(Kind::ElevatorStandard, 110, 1, 4);
462    /// assert!(shaft.ok, "{:?}", shaft.reason);
463    /// ```
464    pub fn build_transport(&mut self, kind: Kind, x: i64, bottom: i64, top: i64) -> BuildResult {
465        let quote = self.can_build_transport(kind, x, bottom, top);
466        if !quote.ok {
467            return BuildResult {
468                ok: false,
469                reason: quote.reason,
470            };
471        }
472        let res = self.tower.place_transport(kind, x, bottom, top);
473        if !res.ok {
474            return BuildResult {
475                ok: false,
476                reason: res.reason,
477            };
478        }
479        self.money -= quote.cost;
480        self.note_edit_cash(-quote.cost);
481        self.gameplay.push(GameplayEvent::FacilityPlaced {
482            kind,
483            floor: top,
484            count: 1,
485        });
486        BuildResult {
487            ok: true,
488            reason: None,
489        }
490    }
491}
492
493#[path = "build_capacity.rs"]
494mod capacity;
495
496#[cfg(test)]
497#[path = "build_tests.rs"]
498mod tests;