atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
bf5f8cb6f60f6e974991335cdfec63b7874a37bf
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/game/run.rsRust389 lines11.4 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, MAX_STAMINA, PRIAPISM_EQ, PULLED_STAMINA, SELF_REPORT_INFLATION,
14
        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) {
152
        self.touch();
153
        self.turn += 1;
154
        self.here.turns += 1;
155
        self.standing.at_turn_start = self.standing.suspicion;
156
        self.realise();
157
    }
158
159
    pub(super) fn shed(&mut self, friction: i32) {
160
        self.body.friction = (self.body.friction - friction).max(0);
161
    }
162
163
    /// Priapism holds EQ up no matter what else moves it.
164
    pub(super) fn reset_eq(&mut self, eq: i32) {
165
        let floor = if self.body.conditions.priapism_turns > 0 {
166
            PRIAPISM_EQ
167
        } else {
168
            0
169
        };
170
        self.body.eq = eq.max(floor);
171
    }
172
173
    pub(super) fn end_kitchen_visit(&mut self) {
174
        self.here.kitchen.melon_offered = false;
175
    }
176
177
    /// Going back to the jelq walks away from both the fridge and Pump-Bro.
178
    pub(super) fn step_away(&mut self) {
179
        self.end_kitchen_visit();
180
        self.here.shopping = false;
181
    }
182
183
    pub(super) fn fresh_nonce(&mut self) -> String {
184
        format!("{:016x}", self.oracle.u64())
185
    }
186
187
    /// One game decision. The dice ignore the state prose, so it is only written for the model.
188
    pub(super) fn decision(&self, site: &'static str, ask: &'static str) -> Roll {
189
        Roll {
190
            state: if self.oracle.listens() {
191
                self.oracle_state()
192
            } else {
193
                String::new()
194
            },
195
            site,
196
            ask,
197
        }
198
    }
199
200
    fn oracle_state(&self) -> String {
201
        let mut s = format!(
202
            "Floor {}, {}. Turn {}.\n\neq: {}\nstamina: {}\nfriction: {}\n",
203
            self.floor.number(),
204
            self.floor.place(),
205
            self.turn,
206
            self.body.eq,
207
            self.body.stamina,
208
            self.body.friction
209
        );
210
        let conditions = &self.body.conditions;
211
        for (active, line) in [
212
            (conditions.friction_burn, "friction burn: yes, untreated\n"),
213
            (conditions.priapism_turns > 0, "priapism: yes\n"),
214
            (conditions.peyronie, "peyronie's disease: yes\n"),
215
            (conditions.pulled_muscle, "pulled muscle: yes\n"),
216
        ] {
217
            if active {
218
                s.push_str(line);
219
            }
220
        }
221
        s.push_str(&format!(
222
            "suspicion: {}\nshame: {}\ngrip: {}\n",
223
            self.standing.suspicion,
224
            self.standing.shame,
225
            self.body.grip.name(),
226
        ));
227
        let held: Vec<&str> = self.items.owned().iter().map(|item| item.slug()).collect();
228
        if !held.is_empty() {
229
            s.push_str(&format!("items: {}\n", held.join(", ")));
230
        }
231
        if self.household.mum.is_some() {
232
            s.push_str("Mum is at the door\n");
233
        }
234
        s
235
    }
236
237
    pub(super) fn chance(&mut self, roll: Roll, odds: u32) -> bool {
238
        self.oracle.chance(roll, odds)
239
    }
240
241
    pub fn path(&self, sub: &str) -> String {
242
        format!("/runs/{}{sub}", self.ident.id)
243
    }
244
245
    pub fn current_length(&self) -> f64 {
246
        self.body.length + self.here.temp_length
247
    }
248
249
    pub fn self_reported(&self) -> f64 {
250
        self.current_length() + SELF_REPORT_INFLATION
251
    }
252
253
    pub fn shown_length(&self) -> f64 {
254
        if self.items.kit.ruler {
255
            self.current_length()
256
        } else {
257
            self.self_reported()
258
        }
259
    }
260
261
    pub fn max_stamina(&self) -> i32 {
262
        if self.body.conditions.pulled_muscle {
263
            PULLED_STAMINA
264
        } else {
265
            MAX_STAMINA
266
        }
267
    }
268
269
    pub fn forum_read(&self) -> bool {
270
        self.online.story == Story::ReadForum
271
    }
272
273
    pub fn thread_reachable(&self) -> bool {
274
        self.turn >= BRANCH_TURN
275
            || self.forum_read()
276
            || self.floor.number() >= Floor::Forum.number()
277
    }
278
279
    pub fn footage(&self) -> Option<(SystemTime, u64)> {
280
        let filmed = self.online.filmed_at?;
281
        let age = filmed.elapsed().map_or(0, |d| d.as_secs());
282
        Some((filmed, age))
283
    }
284
285
    pub fn status(&self) -> RunStatus {
286
        if self.ended.is_some() {
287
            RunStatus::Gone
288
        } else if self.clinic.cured {
289
            RunStatus::Normal
290
        } else if self.clinic.prescribed {
291
            RunStatus::Prescribed
292
        } else {
293
            RunStatus::Alive
294
        }
295
    }
296
297
    /// The parts of the run that its response headers do not already carry.
298
    pub fn view(&self) -> Value {
299
        let conditions: Vec<&str> = [
300
            (self.here.teapot, "short and stout"),
301
            (self.body.conditions.peyronie, "curved"),
302
            (self.items.kit.cage, "caged"),
303
            (self.body.conditions.priapism_turns > 0, "priapism"),
304
            (self.body.conditions.pulled_muscle, "pulled muscle"),
305
            (self.online.filmed_at.is_some(), "viral"),
306
        ]
307
        .into_iter()
308
        .filter_map(|(active, name)| active.then_some(name))
309
        .collect();
310
        json!({
311
            "public_id": self.ident.public_id,
312
            "status": self.status().name(),
313
            "turn": self.turn,
314
            "run_shame": self.standing.shame,
315
            "grip": self.body.grip.name(),
316
            "ranked": !self.ident.seeded,
317
            "conditions": conditions,
318
        })
319
    }
320
321
    pub fn end(&mut self, cause: Cause) -> Problem {
322
        self.ended = Some(Ending {
323
            cause,
324
            turn: self.turn,
325
        });
326
        cause.problem().with("turn", self.turn)
327
    }
328
329
    /// The refractory period is the next HOLD. It comes back with full stamina and nothing else.
330
    pub(super) fn recover(&mut self) {
331
        self.body.exhausted = false;
332
        self.body.stamina = self.max_stamina();
333
        self.reset_eq(STARTING_EQ);
334
    }
335
336
    pub(super) fn check_exhausted(&self) -> Result<(), Problem> {
337
        if !self.body.exhausted {
338
            return Ok(());
339
        }
340
        Err(Problem::new(
341
            StatusCode::TOO_MANY_REQUESTS,
342
            "overtrained",
343
            "Stamina is exhausted. HOLD for the refractory period.",
344
        ))
345
    }
346
347
    pub(super) fn exhaust(&mut self) {
348
        self.body.stamina = 0;
349
        self.body.exhausted = true;
350
    }
351
352
    pub(super) fn realise(&mut self) {
353
        let (due, waiting): (Vec<_>, Vec<_>) = std::mem::take(&mut self.body.pending)
354
            .into_iter()
355
            .partition(|p| p.due <= self.turn);
356
        self.body.pending = waiting;
357
        for p in due {
358
            let foreskin = self.gain(p.length, p.girth, p.foreskin);
359
            let arrived = self.body.arrived.get_or_insert_default();
360
            arrived.length += p.length;
361
            arrived.girth += p.girth;
362
            if let Some(grown) = foreskin {
363
                *arrived.foreskin.get_or_insert(0.0) += grown;
364
            }
365
        }
366
    }
367
368
    pub(super) fn gain(&mut self, length: f64, girth: f64, foreskin: f64) -> Option<f64> {
369
        self.body.length += length;
370
        self.body.girth += girth;
371
        let f = self.body.foreskin.as_mut().filter(|_| foreskin != 0.0)?;
372
        *f += foreskin;
373
        Some(foreskin)
374
    }
375
376
    pub(super) fn rupture(&mut self) -> Problem {
377
        let cause = Cause::Ruptured {
378
            ice_unused: self.items.stores.ice_packs > 0,
379
        };
380
        self.end(cause)
381
    }
382
383
    /// A run whose lock was poisoned by a panic mid-turn cannot be trusted to carry on.
384
    pub fn lose(&mut self) {
385
        if self.ended.is_none() {
386
            self.end(Cause::Lost);
387
        }
388
    }
389
}