Skip to main content
Verticopolis engine

verticopolis_engine/economy/
screens.rs

1//! A theater's screens (#1950). SimTower's theater shows one film; a Modern
2//! theater's two floors are two screens with half the seats each, and each
3//! screen has its own film, age and Auto-rebook choice. The ticket price
4//! stays the theater's.
5//!
6//! The first screen keeps the fields a theater always had (`film_days`,
7//! `film_classic`, `film_blockbuster`, `film_policy`). The second is stored
8//! only while it differs from the first: a theater whose screens show the
9//! same film at the same age, as every theater from before #1950 does, saves
10//! exactly as it did.
11
12use serde_json::{json, Map, Value};
13
14use super::films::{FilmRefusal, FilmTier};
15use crate::clock::GameMode;
16use crate::facilities::Kind;
17use crate::services::with_thousands;
18use crate::sim::{LogKind, Simulation};
19use crate::tower::{Extras, Unit};
20
21/// The film one screen shows, its age, and the film it books again once
22/// that one is spent.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct ScreenFilm {
25    pub tier: FilmTier,
26    /// The days the film has shown, unset before its first night.
27    pub days: Option<u8>,
28    /// The Auto-rebook choice, unset for the mode's default.
29    pub policy: Option<&'static str>,
30}
31
32impl ScreenFilm {
33    /// The first screen's film, from a theater's own fields.
34    pub fn first(extras: &Extras) -> ScreenFilm {
35        ScreenFilm {
36            tier: FilmTier::showing(extras),
37            days: extras.film_days,
38            policy: extras.film_policy,
39        }
40    }
41
42    /// The days the film has shown.
43    pub fn days_shown(self) -> i64 {
44        i64::from(self.days.unwrap_or(0))
45    }
46
47    /// Whether two screens show the same film at the same age and book the
48    /// same one again: a film not yet counted has shown 0 days either way.
49    pub fn same_as(self, other: ScreenFilm) -> bool {
50        self.tier == other.tier
51            && self.days_shown() == other.days_shown()
52            && self.policy == other.policy
53    }
54
55    /// The screen as a save writes it, with the keys a theater's first
56    /// screen uses, each left out while unset.
57    pub fn to_json(self) -> Value {
58        let mut m = Map::new();
59        if let Some(policy) = self.policy {
60            m.insert("filmPolicy".into(), json!(policy));
61        }
62        if let Some(days) = self.days {
63            m.insert("filmDays".into(), json!(days));
64        }
65        if self.tier == FilmTier::Classic {
66            m.insert("filmClassic".into(), json!(true));
67        }
68        if self.tier == FilmTier::Blockbuster {
69            m.insert("filmBlockbuster".into(), json!(true));
70        }
71        Value::Object(m)
72    }
73}
74
75impl Extras {
76    /// These extras with a second screen like the first dropped, as a save
77    /// leaves it out.
78    pub(crate) fn without_mirrored_screen(mut self) -> Extras {
79        let first = ScreenFilm::first(&self);
80        if self
81            .second_screen
82            .is_some_and(|second| second.same_as(first))
83        {
84            self.second_screen = None;
85        }
86        self
87    }
88}
89
90/// Both screens of a theater. Where the mode runs one screen, the second is
91/// the first.
92pub(crate) fn screens(mode: GameMode, u: &Unit) -> [ScreenFilm; 2] {
93    let first = ScreenFilm::first(u.extras());
94    let second = if mode.cinema_screens() > 1 {
95        u.extras().second_screen.unwrap_or(first)
96    } else {
97        first
98    };
99    [first, second]
100}
101
102/// The screens a theater runs in its mode.
103pub(crate) fn running_screens(mode: GameMode, u: &Unit) -> impl Iterator<Item = ScreenFilm> {
104    screens(mode, u).into_iter().take(mode.cinema_screens())
105}
106
107/// Writes both screens of a theater. Where the mode runs one screen the
108/// second follows the first, and a second screen like the first
109/// ([`ScreenFilm::same_as`]) is not stored.
110pub(crate) fn put_screens(mode: GameMode, u: &mut Unit, [first, second]: [ScreenFilm; 2]) {
111    let mut extras = u.extras_mut();
112    extras.film_days = first.days;
113    extras.film_classic = first.tier == FilmTier::Classic;
114    extras.film_blockbuster = first.tier == FilmTier::Blockbuster;
115    extras.film_policy = first.policy;
116    let apart = mode.cinema_screens() > 1 && !second.same_as(first);
117    extras.second_screen = apart.then_some(second);
118}
119
120/// Puts each screen's Auto-rebook choice from `policies`, leaving the films.
121/// Reads no mode: a theater whose mode runs one screen stores no second
122/// screen, so its two choices are the same and stay so.
123pub(crate) fn put_screen_policies(u: &mut Unit, policies: [Option<&'static str>; 2]) {
124    let first = ScreenFilm::first(u.extras());
125    let mut screens = [first, u.extras().second_screen.unwrap_or(first)];
126    for (screen, policy) in screens.iter_mut().zip(policies) {
127        screen.policy = policy;
128    }
129    let mut extras = u.extras_mut();
130    extras.film_policy = screens[0].policy;
131    extras.second_screen = (!screens[1].same_as(screens[0])).then_some(screens[1]);
132}
133
134/// Each screen's Auto-rebook choice, as an undo keeps them.
135pub(crate) fn screen_policies(u: &Unit) -> [Option<&'static str>; 2] {
136    let first = ScreenFilm::first(u.extras());
137    let second = u.extras().second_screen.unwrap_or(first);
138    [first.policy, second.policy]
139}
140
141/// How the log names a screen: nothing for the first, so a one-screen
142/// theater's lines read as they always did.
143fn screen_words(screen: usize) -> &'static str {
144    if screen == 0 {
145        ""
146    } else {
147        " on the second screen"
148    }
149}
150
151impl Simulation {
152    /// Shows a `tier` film on cinema `id`'s first screen ([`book_film`]).
153    ///
154    /// [`book_film`]: Simulation::book_film
155    pub fn change_film(&mut self, id: i64, tier: FilmTier) -> Result<f64, FilmRefusal> {
156        self.book_film(id, 0, tier)
157    }
158
159    /// Shows a `tier` film on screen `screen` (from 0) of cinema `id`:
160    /// charges the price (the [`catalog`](crate::catalog::catalog)'s `films`)
161    /// and starts the film on its first day. Returns the price paid, or why
162    /// the film did not change (a tier the mode does not offer is
163    /// `Unavailable`, a screen the theater does not run is `NoScreen`).
164    pub fn book_film(
165        &mut self,
166        id: i64,
167        screen: usize,
168        tier: FilmTier,
169    ) -> Result<f64, FilmRefusal> {
170        let mode = self.tower.mode;
171        let offer = mode.films().offer(tier).ok_or(FilmRefusal::Unavailable)?;
172        let u = self
173            .tower
174            .get_unit(id)
175            .filter(|u| u.kind == Kind::Cinema)
176            .ok_or(FilmRefusal::NotTheater)?;
177        if screen >= mode.cinema_screens() {
178            return Err(FilmRefusal::NoScreen);
179        }
180        if !u.is_operational() {
181            return Err(FilmRefusal::Closed);
182        }
183        let cost = offer.price;
184        if self.money < cost {
185            return Err(FilmRefusal::Funds { cost });
186        }
187        self.money -= cost;
188        self.record_money("entertainment", -cost);
189        let fills_slot = {
190            let u = self.tower.get_unit_mut(id).ok_or(FilmRefusal::NotTheater)?;
191            let mut films = screens(mode, u);
192            films[screen].tier = tier;
193            films[screen].days = Some(0);
194            put_screens(mode, u, films);
195            super::films::fills_blockbuster_slot(mode, u)
196        };
197        let key = id as f64;
198        self.blockbusters.retain(|&b| b != key);
199        if fills_slot {
200            self.blockbusters.push(key);
201        }
202        self.emit(
203            &format!(
204                "๐ŸŽฌ {} opens{} at the movie theater: ${} charged.",
205                offer.opening,
206                screen_words(screen),
207                with_thousands(cost)
208            ),
209            LogKind::Money,
210        );
211        Ok(cost)
212    }
213
214    /// Sets the film cinema `id`'s first screen books again once its film is
215    /// spent ([`set_screen_policy`]).
216    ///
217    /// [`set_screen_policy`]: Simulation::set_screen_policy
218    pub fn set_film_policy(&mut self, id: i64, policy: &str) -> Option<&'static str> {
219        self.set_screen_policy(id, 0, policy)
220    }
221
222    /// Sets the film screen `screen` (from 0) of cinema `id` books again once
223    /// its film is spent (Modern): `auto` or `feature` (a feature),
224    /// `revival`, `blockbuster`, or `off`. Returns the policy set, or `None`
225    /// when `id` is not a cinema, the theater runs no such screen, or
226    /// `policy` is none of the five.
227    pub fn set_screen_policy(
228        &mut self,
229        id: i64,
230        screen: usize,
231        policy: &str,
232    ) -> Option<&'static str> {
233        let policy: &'static str = match policy {
234            "auto" => "auto",
235            "feature" => "feature",
236            "blockbuster" => "blockbuster",
237            "revival" => "revival",
238            "off" => "off",
239            _ => return None,
240        };
241        let mode = self.tower.mode;
242        if screen >= mode.cinema_screens() {
243            return None;
244        }
245        let u = self.tower.get_unit_mut(id)?;
246        if u.kind != Kind::Cinema {
247            return None;
248        }
249        let mut films = screens(mode, u);
250        films[screen].policy = Some(policy);
251        put_screens(mode, u, films);
252        Some(policy)
253    }
254
255    /// Where the mode rebooks spent films (Modern), each screen of an open
256    /// theater whose film is spent books its policy's film again, and pays
257    /// for it. Runs after the day's rollover, so the spent film's last night
258    /// is counted first. A screen that cannot pay keeps its spent film, and
259    /// the log says so on the morning the film is spent.
260    pub fn rebook_spent_films(&mut self) {
261        let mode = self.tower.mode;
262        let films = mode.films();
263        if films.rebooks.is_empty() {
264            return;
265        }
266        let spent = films.run.spent_days;
267        let mut due: Vec<(i64, usize, FilmTier, bool, i64)> = Vec::new();
268        for u in self.tower.units_of_kind(Kind::Cinema) {
269            if !u.is_operational() {
270                continue;
271            }
272            for (screen, film) in running_screens(mode, u).enumerate() {
273                let days = film.days_shown();
274                if days < spent {
275                    continue;
276                }
277                if let Some(tier) = films.rebooked(film.policy) {
278                    due.push((u.id, screen, tier, days == spent, u.floor));
279                }
280            }
281        }
282        for (id, screen, tier, first_spent_morning, floor) in due {
283            if let Err(FilmRefusal::Funds { cost }) = self.book_film(id, screen, tier) {
284                if first_spent_morning {
285                    let label = films.offer(tier).map_or("film", |o| o.label);
286                    let msg = format!(
287                        "๐ŸŽฌ The movie theater on {} can't afford its next {}{} (${}).",
288                        self.floor_label(floor),
289                        label.to_lowercase(),
290                        screen_words(screen),
291                        with_thousands(cost)
292                    );
293                    self.emit(&msg, LogKind::Bad);
294                }
295            }
296        }
297    }
298}
299
300#[cfg(test)]
301#[path = "screens_tests.rs"]
302mod screens_tests;