atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
fcc6cf6d5edcfdaf719c2b9cd40c6b77532340e6
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/game/run.rsRust392 lines11.5 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: {}\nwarmed up: {}\ngrip: {}\n",
223
            self.standing.suspicion,
224
            self.standing.shame,
225
            if self.body.warmed_up { "yes" } else { "no" },
226
            self.body.grip.name(),
227
        ));
228
        let held: Vec<&str> = self.items.owned().iter().map(|item| item.slug()).collect();
229
        if !held.is_empty() {
230
            s.push_str(&format!("items: {}\n", held.join(", ")));
231
        }
232
        if self.household.mum.is_some() {
233
            s.push_str("Mum is at the door\n");
234
        }
235
        s
236
    }
237
238
    pub(super) fn chance(&mut self, roll: Roll, odds: u32) -> bool {
239
        self.oracle.chance(roll, odds)
240
    }
241
242
    pub fn path(&self, sub: &str) -> String {
243
        format!("/runs/{}{sub}", self.ident.id)
244
    }
245
246
    pub fn current_length(&self) -> f64 {
247
        self.body.length + self.here.temp_length
248
    }
249
250
    pub fn self_reported(&self) -> f64 {
251
        self.current_length() + SELF_REPORT_INFLATION
252
    }
253
254
    pub fn shown_length(&self) -> f64 {
255
        if self.items.kit.ruler {
256
            self.current_length()
257
        } else {
258
            self.self_reported()
259
        }
260
    }
261
262
    pub fn max_stamina(&self) -> i32 {
263
        if self.body.conditions.pulled_muscle {
264
            PULLED_STAMINA
265
        } else {
266
            MAX_STAMINA
267
        }
268
    }
269
270
    pub fn forum_read(&self) -> bool {
271
        self.online.story == Story::ReadForum
272
    }
273
274
    pub fn thread_reachable(&self) -> bool {
275
        self.turn >= BRANCH_TURN
276
            || self.forum_read()
277
            || self.floor.number() >= Floor::Forum.number()
278
    }
279
280
    pub fn footage(&self) -> Option<(SystemTime, u64)> {
281
        let filmed = self.online.filmed_at?;
282
        let age = filmed.elapsed().map_or(0, |d| d.as_secs());
283
        Some((filmed, age))
284
    }
285
286
    pub fn status(&self) -> RunStatus {
287
        if self.ended.is_some() {
288
            RunStatus::Gone
289
        } else if self.clinic.cured {
290
            RunStatus::Normal
291
        } else if self.clinic.prescribed {
292
            RunStatus::Prescribed
293
        } else {
294
            RunStatus::Alive
295
        }
296
    }
297
298
    /// The parts of the run that its response headers do not already carry.
299
    pub fn view(&self) -> Value {
300
        let conditions: Vec<&str> = [
301
            (self.here.teapot, "short and stout"),
302
            (self.body.conditions.peyronie, "curved"),
303
            (self.items.kit.cage, "caged"),
304
            (self.body.conditions.priapism_turns > 0, "priapism"),
305
            (self.body.conditions.pulled_muscle, "pulled muscle"),
306
            (self.online.filmed_at.is_some(), "viral"),
307
        ]
308
        .into_iter()
309
        .filter_map(|(active, name)| active.then_some(name))
310
        .collect();
311
        json!({
312
            "public_id": self.ident.public_id,
313
            "status": self.status().name(),
314
            "turn": self.turn,
315
            "run_shame": self.standing.shame,
316
            "grip": self.body.grip.name(),
317
            "warmed_up": self.body.warmed_up,
318
            "ranked": !self.ident.seeded,
319
            "conditions": conditions,
320
        })
321
    }
322
323
    pub fn end(&mut self, cause: Cause) -> Problem {
324
        self.ended = Some(Ending {
325
            cause,
326
            turn: self.turn,
327
        });
328
        cause.problem().with("turn", self.turn)
329
    }
330
331
    /// The refractory period is the next HOLD. It comes back with full stamina and nothing else.
332
    pub(super) fn recover(&mut self) {
333
        self.body.exhausted = false;
334
        self.body.stamina = self.max_stamina();
335
        self.reset_eq(STARTING_EQ);
336
        self.body.warmed_up = false;
337
    }
338
339
    pub(super) fn check_exhausted(&self) -> Result<(), Problem> {
340
        if !self.body.exhausted {
341
            return Ok(());
342
        }
343
        Err(Problem::new(
344
            StatusCode::TOO_MANY_REQUESTS,
345
            "overtrained",
346
            "Stamina is exhausted. HOLD for the refractory period.",
347
        ))
348
    }
349
350
    pub(super) fn exhaust(&mut self) {
351
        self.body.stamina = 0;
352
        self.body.exhausted = true;
353
    }
354
355
    pub(super) fn realise(&mut self) {
356
        let (due, waiting): (Vec<_>, Vec<_>) = std::mem::take(&mut self.body.pending)
357
            .into_iter()
358
            .partition(|p| p.due <= self.turn);
359
        self.body.pending = waiting;
360
        for p in due {
361
            let foreskin = self.gain(p.length, p.girth, p.foreskin);
362
            let arrived = self.body.arrived.get_or_insert_default();
363
            arrived.length += p.length;
364
            arrived.girth += p.girth;
365
            if let Some(grown) = foreskin {
366
                *arrived.foreskin.get_or_insert(0.0) += grown;
367
            }
368
        }
369
    }
370
371
    pub(super) fn gain(&mut self, length: f64, girth: f64, foreskin: f64) -> Option<f64> {
372
        self.body.length += length;
373
        self.body.girth += girth;
374
        let f = self.body.foreskin.as_mut().filter(|_| foreskin != 0.0)?;
375
        *f += foreskin;
376
        Some(foreskin)
377
    }
378
379
    pub(super) fn rupture(&mut self) -> Problem {
380
        let cause = Cause::Ruptured {
381
            ice_unused: self.items.stores.ice_packs > 0,
382
        };
383
        self.end(cause)
384
    }
385
386
    /// A run whose lock was poisoned by a panic mid-turn cannot be trusted to carry on.
387
    pub fn lose(&mut self) {
388
        if self.ended.is_none() {
389
            self.end(Cause::Lost);
390
        }
391
    }
392
}