atagen

jelq

public

an http based roguelike rpg about jelqing

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