atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
6619c458c23edaf053ae371f8aa0df1e866febb6
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/game/run.rsRust426 lines12.8 KB
1
use std::{
2
    hash::{DefaultHasher, Hash, Hasher},
3
    time::{Instant, SystemTime},
4
};
5
6
use axum::http::StatusCode;
7
use serde_json::{Value, json};
8
9
use super::{
10
    Body, Cause, Clinic, Ending, Floor, FloorState, Household, Item, Items, Notice, Observer,
11
    Online, RunStatus, Standing, Story,
12
    balance::{
13
        BRANCH_TURN, FLOOR_LIMIT, MAX_STAMINA, PRIAPISM_EQ, PULLED_STAMINA, REFRACTORY_STAMINA,
14
        SECOND_WIND, SELF_REPORT_INFLATION, STARTING_BABY_OIL, STARTING_EQ, STARTING_LUBE,
15
    },
16
    measure::round2,
17
    oracle::{Oracle, OracleTemplate, Roll},
18
};
19
use crate::problem::Problem;
20
21
pub struct Identity {
22
    /// The private id in the run's URL. Knowing it is the only authorisation a run has.
23
    pub(crate) id: String,
24
    pub(crate) public_id: String,
25
    pub(crate) seeded: bool,
26
    etag_salt: u64,
27
    pub(crate) version: u64,
28
    pub(crate) last_seen: Instant,
29
}
30
31
pub struct Run {
32
    pub(crate) ident: Identity,
33
    pub(crate) body: Body,
34
    pub(crate) standing: Standing,
35
    pub(crate) household: Household,
36
    pub(crate) online: Online,
37
    pub(crate) items: Items,
38
    pub(crate) clinic: Clinic,
39
    pub(crate) turn: u32,
40
    pub(crate) floor: Floor,
41
    pub(crate) here: FloorState,
42
    pub(crate) observed: Option<Observer>,
43
    pub(crate) notices: Vec<Notice>,
44
    pub(crate) ended: Option<Ending>,
45
    pub(super) oracle: Oracle,
46
}
47
48
impl Run {
49
    #[cfg(test)]
50
    pub fn new(id: String, public_id: String, seed: u64) -> Self {
51
        Self::with_oracle(id, public_id, seed, false, &OracleTemplate::Rng)
52
    }
53
54
    pub fn with_oracle(
55
        id: String,
56
        public_id: String,
57
        seed: u64,
58
        seeded: bool,
59
        template: &OracleTemplate,
60
    ) -> Self {
61
        let mut oracle = Oracle::build(template, seed);
62
        let length = round2(oracle.span(
63
            Run::unborn("length", "How long is it, in inches?"),
64
            4.5,
65
            6.5,
66
        ));
67
        let girth = round2(oracle.span(
68
            Run::unborn("girth", "How thick is it, in inches?"),
69
            4.0,
70
            5.0,
71
        ));
72
        let foreskin = round2(oracle.span(
73
            Run::unborn("foreskin", "How much foreskin is there, in inches?"),
74
            0.4,
75
            2.4,
76
        ));
77
        let mut items = Items::default();
78
        if oracle.chance(
79
            Run::unborn(
80
                "starting-lube",
81
                "Is there a bottle of lube in the drawer already?",
82
            ),
83
            STARTING_LUBE,
84
        ) {
85
            let baby_oil = oracle.chance(
86
                Run::unborn(
87
                    "starting-bottle",
88
                    "Is the bottle baby oil, rather than lotion?",
89
                ),
90
                STARTING_BABY_OIL,
91
            );
92
            items.grant(if baby_oil {
93
                Item::BabyOil
94
            } else {
95
                Item::Lotion
96
            });
97
        }
98
        let etag_salt = oracle.u64();
99
        Self {
100
            ident: Identity {
101
                id,
102
                public_id,
103
                seeded,
104
                etag_salt,
105
                version: 0,
106
                last_seen: Instant::now(),
107
            },
108
            body: Body::new(length, girth, foreskin),
109
            standing: Standing::default(),
110
            household: Household::default(),
111
            online: Online::default(),
112
            items,
113
            clinic: Clinic::default(),
114
            turn: 0,
115
            floor: Floor::Bedroom,
116
            here: FloorState::default(),
117
            observed: None,
118
            notices: Vec::new(),
119
            ended: None,
120
            oracle,
121
        }
122
    }
123
124
    fn unborn(site: &'static str, ask: &'static str) -> Roll {
125
        Roll {
126
            state: "A new run is being created. No game has been played yet.".into(),
127
            site,
128
            ask,
129
        }
130
    }
131
132
    fn etag_at(&self, version: u64) -> String {
133
        let mut hasher = DefaultHasher::new();
134
        (self.ident.etag_salt, version).hash(&mut hasher);
135
        format!("\"{:016x}\"", hasher.finish())
136
    }
137
138
    pub fn etag(&self) -> String {
139
        self.etag_at(self.ident.version)
140
    }
141
142
    /// The ETag the run had when it was created, which the true ending asks for.
143
    pub fn origin_etag(&self) -> String {
144
        self.etag_at(0)
145
    }
146
147
    pub fn touch(&mut self) {
148
        self.ident.version += 1;
149
    }
150
151
    pub(super) fn begin_turn(&mut self) -> Result<(), Problem> {
152
        self.check_clock()?;
153
        self.touch();
154
        self.turn += 1;
155
        self.here.turns += 1;
156
        self.body.torn = 0.0;
157
        self.standing.at_turn_start = self.standing.suspicion;
158
        self.realise(false);
159
        if self.floor.timed() && self.here.turns + 2 == FLOOR_LIMIT {
160
            self.notices.push(Notice::RunningLong(self.floor));
161
        } else if self.floor.timed() && self.here.turns + 1 == FLOOR_LIMIT {
162
            self.notices.push(Notice::LastTurn);
163
        }
164
        Ok(())
165
    }
166
167
    pub(super) fn shed(&mut self, friction: i32) {
168
        self.body.friction = (self.body.friction - friction).max(0);
169
    }
170
171
    /// Priapism holds EQ up no matter what else moves it.
172
    pub(super) fn reset_eq(&mut self, eq: i32) {
173
        let floor = if self.body.conditions.priapism_turns > 0 {
174
            PRIAPISM_EQ
175
        } else {
176
            0
177
        };
178
        self.body.eq = eq.max(floor);
179
    }
180
181
    pub(super) fn end_kitchen_visit(&mut self) {
182
        self.here.kitchen.melon_offered = false;
183
    }
184
185
    /// Going back to the jelq walks away from both the fridge and Pump-Bro.
186
    pub(super) fn step_away(&mut self) {
187
        self.end_kitchen_visit();
188
        self.here.shopping = false;
189
    }
190
191
    pub(super) fn fresh_nonce(&mut self) -> String {
192
        format!("{:016x}", self.oracle.u64())
193
    }
194
195
    /// One game decision. The dice ignore the state prose, so it is only written for the model.
196
    pub(super) fn decision(&self, site: &'static str, ask: &'static str) -> Roll {
197
        Roll {
198
            state: if self.oracle.listens() {
199
                self.oracle_state()
200
            } else {
201
                String::new()
202
            },
203
            site,
204
            ask,
205
        }
206
    }
207
208
    fn oracle_state(&self) -> String {
209
        let mut s = format!(
210
            "Floor {}, {}. Turn {}.\n\neq: {}\nstamina: {}\nfriction: {}\n",
211
            self.floor.number(),
212
            self.floor.place(),
213
            self.turn,
214
            self.body.eq,
215
            self.body.stamina,
216
            self.body.friction
217
        );
218
        let conditions = &self.body.conditions;
219
        for (active, line) in [
220
            (conditions.friction_burn, "friction burn: yes, untreated\n"),
221
            (conditions.priapism_turns > 0, "priapism: yes\n"),
222
            (conditions.peyronie, "peyronie's disease: yes\n"),
223
            (conditions.pulled_muscle, "pulled muscle: yes\n"),
224
        ] {
225
            if active {
226
                s.push_str(line);
227
            }
228
        }
229
        s.push_str(&format!(
230
            "suspicion: {}\nshame: {}\ngrip: {}\n",
231
            self.standing.suspicion,
232
            self.standing.shame,
233
            self.body.grip.name(),
234
        ));
235
        let held: Vec<&str> = self.items.owned().iter().map(|item| item.slug()).collect();
236
        if !held.is_empty() {
237
            s.push_str(&format!("items: {}\n", held.join(", ")));
238
        }
239
        if self.household.mum.is_some() {
240
            s.push_str("Mum is at the door\n");
241
        }
242
        s
243
    }
244
245
    pub(super) fn chance(&mut self, roll: Roll, odds: u32) -> bool {
246
        self.oracle.chance(roll, odds)
247
    }
248
249
    pub fn path(&self, sub: &str) -> String {
250
        format!("/runs/{}{sub}", self.ident.id)
251
    }
252
253
    pub fn current_length(&self) -> f64 {
254
        self.body.length + self.here.temp_length
255
    }
256
257
    pub fn self_reported(&self) -> f64 {
258
        self.current_length() + SELF_REPORT_INFLATION
259
    }
260
261
    pub fn shown_length(&self) -> f64 {
262
        if self.items.kit.ruler {
263
            self.current_length()
264
        } else {
265
            self.self_reported()
266
        }
267
    }
268
269
    pub fn max_stamina(&self) -> i32 {
270
        if self.body.conditions.pulled_muscle {
271
            PULLED_STAMINA
272
        } else {
273
            MAX_STAMINA
274
        }
275
    }
276
277
    pub fn forum_read(&self) -> bool {
278
        self.online.story == Story::ReadForum
279
    }
280
281
    pub fn thread_reachable(&self) -> bool {
282
        self.turn >= BRANCH_TURN
283
            || self.forum_read()
284
            || self.floor.number() >= Floor::Forum.number()
285
    }
286
287
    pub fn footage(&self) -> Option<(SystemTime, u64)> {
288
        let filmed = self.online.filmed_at?;
289
        let age = filmed.elapsed().map_or(0, |d| d.as_secs());
290
        Some((filmed, age))
291
    }
292
293
    pub fn status(&self) -> RunStatus {
294
        if self.ended.is_some() {
295
            RunStatus::Gone
296
        } else if self.clinic.cured {
297
            RunStatus::Normal
298
        } else if self.clinic.prescribed {
299
            RunStatus::Prescribed
300
        } else {
301
            RunStatus::Alive
302
        }
303
    }
304
305
    /// The parts of the run that its response headers do not already carry.
306
    pub fn view(&self) -> Value {
307
        let conditions: Vec<&str> = [
308
            (self.here.teapot, "short and stout"),
309
            (self.body.conditions.peyronie, "curved"),
310
            (self.items.kit.cage, "caged"),
311
            (self.body.conditions.priapism_turns > 0, "priapism"),
312
            (self.body.conditions.pulled_muscle, "pulled muscle"),
313
            (self.online.filmed_at.is_some(), "viral"),
314
        ]
315
        .into_iter()
316
        .filter_map(|(active, name)| active.then_some(name))
317
        .collect();
318
        json!({
319
            "public_id": self.ident.public_id,
320
            "status": self.status().name(),
321
            "turn": self.turn,
322
            "run_shame": self.standing.shame,
323
            "grip": self.body.grip.name(),
324
            "ranked": !self.ident.seeded,
325
            "conditions": conditions,
326
        })
327
    }
328
329
    pub fn end(&mut self, cause: Cause) -> Problem {
330
        self.ended = Some(Ending {
331
            cause,
332
            turn: self.turn,
333
        });
334
        cause.problem().with("turn", self.turn)
335
    }
336
337
    /// The refractory period is the next HOLD. Returns whether it rolled the second wind that refills stamina outright.
338
    pub(super) fn recover(&mut self) -> bool {
339
        self.body.exhausted = false;
340
        let second_wind = self.chance(
341
            self.decision(
342
                "second-wind",
343
                "Does the refractory period end in a second wind?",
344
            ),
345
            SECOND_WIND,
346
        );
347
        self.body.stamina = if second_wind {
348
            self.max_stamina()
349
        } else {
350
            let (lo, hi) = REFRACTORY_STAMINA;
351
            let back = self.oracle.span_int(
352
                self.decision(
353
                    "refractory",
354
                    "How much stamina comes back after the refractory period?",
355
                ),
356
                lo,
357
                hi,
358
            );
359
            back.min(self.max_stamina())
360
        };
361
        self.reset_eq(STARTING_EQ);
362
        second_wind
363
    }
364
365
    pub(super) fn check_exhausted(&self) -> Result<(), Problem> {
366
        if !self.body.exhausted {
367
            return Ok(());
368
        }
369
        Err(Problem::new(
370
            StatusCode::TOO_MANY_REQUESTS,
371
            "overtrained",
372
            "Stamina is exhausted. HOLD for the refractory period.",
373
        ))
374
    }
375
376
    pub(super) fn exhaust(&mut self) {
377
        self.body.stamina = 0;
378
        self.body.exhausted = true;
379
    }
380
381
    /// Leaving a floor lets time pass, so everything still queued arrives at once.
382
    pub(super) fn realise(&mut self, everything: bool) {
383
        let (due, waiting): (Vec<_>, Vec<_>) = std::mem::take(&mut self.body.pending)
384
            .into_iter()
385
            .partition(|p| everything || p.due <= self.turn);
386
        self.body.pending = waiting;
387
        for p in due {
388
            let foreskin = self.gain(p.length, p.girth, p.foreskin);
389
            let arrived = self.body.arrived.get_or_insert_default();
390
            arrived.length += p.length;
391
            arrived.girth += p.girth;
392
            if let Some(grown) = foreskin {
393
                *arrived.foreskin.get_or_insert(0.0) += grown;
394
            }
395
        }
396
    }
397
398
    /// The foreskin change it returns nets out whatever friction tore off this turn.
399
    pub(super) fn gain(&mut self, length: f64, girth: f64, foreskin: f64) -> Option<f64> {
400
        self.body.length += length;
401
        self.body.girth += girth;
402
        let torn = std::mem::take(&mut self.body.torn);
403
        let grown = match &mut self.body.foreskin {
404
            Some(f) => {
405
                *f += foreskin;
406
                foreskin
407
            }
408
            None => 0.0,
409
        };
410
        (grown != 0.0 || torn != 0.0).then_some(grown - torn)
411
    }
412
413
    pub(super) fn rupture(&mut self) -> Problem {
414
        let cause = Cause::Ruptured {
415
            ice_unused: self.items.stores.ice_packs > 0,
416
        };
417
        self.end(cause)
418
    }
419
420
    /// A run whose lock was poisoned by a panic mid-turn cannot be trusted to carry on.
421
    pub fn lose(&mut self) {
422
        if self.ended.is_none() {
423
            self.end(Cause::Lost);
424
        }
425
    }
426
}