atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
7288fc269bb68466e68614d7f97cb55fc4ae1358
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/game/turn.rsRust548 lines19.4 KB
1
use std::{fmt::Write as _, ops::ControlFlow, time::Instant};
2
3
use axum::http::{StatusCode, header};
4
use rand::Rng;
5
use serde_json::json;
6
7
use super::{
8
    Floor, Grip, LUBRICANTS, Lube, Outcome, Payload, Run, Story, Technique,
9
    balance::{
10
        BAND_BONUS, BRANCH_TURN, CAT_TAKES_TOWEL, CHANGING_ROOM_CHILL, DANGER_EQ, EQ_BAND,
11
        EQ_WOBBLE, EXTENDER_GAIN, HOT_EQ, OBSERVED, PRIAPISM_EQ, PRIAPISM_TURNS, PULLED_MUSCLE,
12
        PULLED_MUSCLE_INTENSITY, RING_PRIAPISM, RING_RUPTURE_LINE, RUPTURE_LINE, STORAGE_GIRTH,
13
        SUSPICION_LIMIT,
14
    },
15
    not_extended, round3,
16
    state::{MumVisit, Observer, Pending},
17
    techniques::{LubeRule, Profile, Training, Utility},
18
};
19
use crate::{headers::SERVER_TIMING, problem::Problem};
20
21
impl Run {
22
    pub fn jelq(
23
        &mut self,
24
        techniques: &[Technique],
25
        intensity: i32,
26
        lube: Option<Lube>,
27
        now: Instant,
28
    ) -> Result<Outcome, Problem> {
29
        self.check_refractory(now)?;
30
        if self.story == Story::Pending {
31
            return Ok(self.branch_offer());
32
        }
33
        if self.floor == Floor::Forum {
34
            return Ok(Outcome::json(
35
                StatusCode::SEE_OTHER,
36
                json!({ "detail": "Refer to the forum." }),
37
            )
38
            .header(header::LOCATION, super::FORUM_THREAD));
39
        }
40
        if self.items.cage {
41
            return Err(Problem::new(
42
                StatusCode::LOCKED,
43
                "caged",
44
                "The cage is locked. The key is not in the box.",
45
            ));
46
        }
47
        match *techniques {
48
            [Technique::Utility(utility)] => self.utility(utility, lube, now),
49
            [Technique::Training(training)] => self.single(training, intensity, lube, now),
50
            [Technique::Training(a), Technique::Training(b)] => {
51
                self.combo(a, b, intensity, lube, now)
52
            }
53
            [_, _] => Err(Problem::new(
54
                StatusCode::BAD_REQUEST,
55
                "combo-invalid",
56
                "Only training techniques can be combined.",
57
            )),
58
            _ => Err(Problem::new(
59
                StatusCode::BAD_REQUEST,
60
                "too-many-techniques",
61
                "Two techniques at most. The server has limits even if you do not.",
62
            )),
63
        }
64
    }
65
66
    fn utility(
67
        &mut self,
68
        utility: Utility,
69
        lube: Option<Lube>,
70
        now: Instant,
71
    ) -> Result<Outcome, Problem> {
72
        match utility {
73
            Utility::Warmup => return self.warm_up(),
74
            Utility::Ice => return self.ice(),
75
            Utility::Supplement => return self.supplement(),
76
            Utility::Edge | Utility::Pump => {}
77
        }
78
        if utility == Utility::Pump {
79
            self.here.edges = 0;
80
        }
81
        self.ready(Technique::Utility(utility), lube)?;
82
        self.check_storage()?;
83
        self.floor_enemy()?;
84
        match utility {
85
            Utility::Edge => self.edge(now),
86
            _ => self.pump(now),
87
        }
88
    }
89
90
    fn single(
91
        &mut self,
92
        training: Training,
93
        intensity: i32,
94
        lube: Option<Lube>,
95
        now: Instant,
96
    ) -> Result<Outcome, Problem> {
97
        self.here.edges = 0;
98
        self.ready(Technique::Training(training), lube)?;
99
        self.check_storage()?;
100
        self.floor_enemy()?;
101
        self.commit(intensity, lube, now, 1);
102
        if let ControlFlow::Break(interrupted) = self.mishaps(training, intensity)? {
103
            return Ok(interrupted);
104
        }
105
        if let ControlFlow::Break(interrupted) = self.hazards(intensity)? {
106
            return Ok(interrupted);
107
        }
108
        let outcome = self.roll(training, intensity, lube)?;
109
        Ok(self.gossip(outcome))
110
    }
111
112
    fn combo(
113
        &mut self,
114
        a: Training,
115
        b: Training,
116
        intensity: i32,
117
        lube: Option<Lube>,
118
        now: Instant,
119
    ) -> Result<Outcome, Problem> {
120
        if a == b {
121
            return Err(Problem::new(
122
                StatusCode::BAD_REQUEST,
123
                "combo-invalid",
124
                "A technique cannot be combined with itself. The server has checked.",
125
            ));
126
        }
127
        self.here.edges = 0;
128
        self.ready(Technique::Training(a), lube)?;
129
        self.ready(Technique::Training(b), lube)?;
130
        self.check_storage()?;
131
        self.floor_enemy()?;
132
        self.commit(intensity, lube, now, 2);
133
        for training in [a, b] {
134
            if let ControlFlow::Break(interrupted) = self.mishaps(training, intensity)? {
135
                return Ok(interrupted);
136
            }
137
        }
138
        if let ControlFlow::Break(interrupted) = self.hazards(intensity)? {
139
            return Ok(interrupted);
140
        }
141
142
        let mut statuses = Vec::new();
143
        for training in [a, b] {
144
            let result = self.roll(training, intensity, lube);
145
            if self.ended.is_some() {
146
                return result;
147
            }
148
            let status = match result {
149
                Ok(outcome) => self.gossip(outcome).status,
150
                Err(problem) => problem.status(),
151
            };
152
            statuses.push((training, status));
153
        }
154
155
        let mut xml = String::from(
156
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<D:multistatus xmlns:D=\"DAV:\">\n",
157
        );
158
        for (training, status) in statuses {
159
            let _ = write!(
160
                xml,
161
                "  <D:response>\n    <D:href>{}?technique={}</D:href>\n    <D:status>HTTP/1.1 {} {}</D:status>\n  </D:response>\n",
162
                self.path(""),
163
                training.name(),
164
                status.as_u16(),
165
                crate::problem::reason(status),
166
            );
167
        }
168
        xml.push_str(
169
            "  <D:responsedescription>Each technique has been reported separately.</D:responsedescription>\n</D:multistatus>\n",
170
        );
171
        Ok(Outcome::raw(
172
            StatusCode::MULTI_STATUS,
173
            "application/xml; charset=utf-8",
174
            xml,
175
        ))
176
    }
177
178
    fn ready(&self, technique: Technique, lube: Option<Lube>) -> Result<(), Problem> {
179
        self.access(technique)?;
180
        match technique {
181
            Technique::Training(training) => Self::check_lube(training, lube),
182
            Technique::Utility(_) => Ok(()),
183
        }
184
    }
185
186
    /// Whether the run could attempt the technique now, ignoring the lubricant.
187
    fn access(&self, technique: Technique) -> Result<(), Problem> {
188
        if technique == Technique::Training(Training::Uli) && !self.forum_read() {
189
            return Err(Problem::new(
190
                StatusCode::FORBIDDEN,
191
                "technique-locked",
192
                "This technique is discussed on the forum. You have not been to the forum.",
193
            ));
194
        }
195
        if !self.warmed_up {
196
            return Err(Problem::new(
197
                StatusCode::PRECONDITION_FAILED,
198
                "cold-start",
199
                "Warm-up was skipped. The server has noted this.",
200
            )
201
            .with("technique", Utility::Warmup.name()));
202
        }
203
        match technique {
204
            Technique::Utility(Utility::Pump) if !self.items.pump_pro => Err(Problem::new(
205
                StatusCode::FAILED_DEPENDENCY,
206
                "no-pump",
207
                "The pump technique depends on a pump.",
208
            )),
209
            Technique::Utility(_) => Ok(()),
210
            Technique::Training(training) => match training.profile().foreskin {
211
                Some((min, max)) => self.check_foreskin(min, max),
212
                None => Ok(()),
213
            },
214
        }
215
    }
216
217
    fn check_lube(training: Training, lube: Option<Lube>) -> Result<(), Problem> {
218
        match (training.profile().lube, lube) {
219
            (LubeRule::Required, None) => Err(Problem::new(
220
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
221
                "lubricant-required",
222
                format!(
223
                    "The {} technique requires a lubricant. None was declared.",
224
                    training.name()
225
                ),
226
            )
227
            .with("lubricants", json!(LUBRICANTS))),
228
            (LubeRule::Forbidden, Some(_)) => Err(Problem::new(
229
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
230
                "lubricant-declared",
231
                format!(
232
                    "The {} technique was requested. A lubricant was declared.",
233
                    training.name()
234
                ),
235
            )),
236
            _ => Ok(()),
237
        }
238
    }
239
240
    /// The techniques a JELQ could use right now without being refused before the roll.
241
    pub fn techniques_now(&self, now: Instant) -> Vec<Technique> {
242
        let blocked = !self.floor.timed()
243
            || self.items.cage
244
            || self.story == Story::Pending
245
            || self.refractory_until.is_some_and(|until| now < until);
246
        if blocked {
247
            return Vec::new();
248
        }
249
        let rested = self.refractory_until.is_some();
250
        Technique::ALL
251
            .into_iter()
252
            .filter(|&technique| match technique {
253
                Technique::Utility(Utility::Warmup) => true,
254
                Technique::Utility(Utility::Ice) => self.items.ice_packs > 0,
255
                Technique::Utility(Utility::Supplement) => self.items.supplements > 0,
256
                _ if rested => false,
257
                _ => self.access(technique).is_ok() && self.check_storage().is_ok(),
258
            })
259
            .collect()
260
    }
261
262
    fn check_foreskin(&self, min: f64, max: f64) -> Result<(), Problem> {
263
        let Some(f) = self.foreskin else {
264
            if min <= 0.0 {
265
                return Ok(());
266
            }
267
            return Err(Problem::new(
268
                StatusCode::GONE,
269
                "foreskin-gone",
270
                "This technique requires a foreskin. The foreskin is gone.",
271
            )
272
            .header(header::CONTENT_LOCATION, self.path("/foreskin")));
273
        };
274
        if f < min {
275
            return Err(Problem::new(
276
                StatusCode::LENGTH_REQUIRED,
277
                "foreskin-insufficient",
278
                format!(
279
                    "The selected technique requires {min:.1} units of foreskin. {f:.2} units are available. The server has noted the shortfall."
280
                ),
281
            )
282
            .with("required", min));
283
        }
284
        if f > max {
285
            return Err(Problem::new(
286
                StatusCode::PAYLOAD_TOO_LARGE,
287
                "foreskin-excessive",
288
                format!(
289
                    "The selected technique tolerates at most {max:.1} units of foreskin. {f:.2} units are present."
290
                ),
291
            )
292
            .with("maximum", max));
293
        }
294
        Ok(())
295
    }
296
297
    fn check_storage(&self) -> Result<(), Problem> {
298
        if self.items.extender && self.girth > STORAGE_GIRTH {
299
            return Err(Problem::new(
300
                StatusCode::INSUFFICIENT_STORAGE,
301
                "jeans-full",
302
                "The jeans are full. The extender is occupying the remaining storage.",
303
            )
304
            .with("extender", self.path("/inventory/extender")));
305
        }
306
        Ok(())
307
    }
308
309
    pub(super) fn commit(&mut self, intensity: i32, lube: Option<Lube>, now: Instant, cost: i32) {
310
        self.touch();
311
        self.turn += 1;
312
        self.here.turns += 1;
313
        self.realise();
314
        if self.items.extender {
315
            self.length += EXTENDER_GAIN;
316
        }
317
        self.stamina -= cost + i32::from(lube == Some(Lube::Lotion));
318
        if self.stamina <= 0 {
319
            self.exhaust(now);
320
        }
321
        let chill = if self.floor == Floor::ChangingRoom {
322
            CHANGING_ROOM_CHILL
323
        } else {
324
            0
325
        };
326
        let wobble = self.rng.random_range(-EQ_WOBBLE..=EQ_WOBBLE);
327
        self.eq = (self.eq + intensity * 2 - 6 - chill + wobble).clamp(0, 100);
328
329
        let mut suspicion = intensity / 5 + i32::from(lube == Some(Lube::Vaseline));
330
        if matches!(self.floor, Floor::ChangingRoom | Floor::Nans) {
331
            suspicion *= 2;
332
        }
333
        if self.floor == Floor::Nans && lube == Some(Lube::CoconutOil) {
334
            suspicion += 2;
335
        }
336
        let was_below = self.suspicion < SUSPICION_LIMIT;
337
        self.suspicion =
338
            u8::try_from((i32::from(self.suspicion) + suspicion).min(i32::from(SUSPICION_LIMIT)))
339
                .unwrap_or(SUSPICION_LIMIT);
340
        self.maybe_summon_mum(was_below);
341
342
        if let Some(observer) = self.floor.observer()
343
            && self.chance(OBSERVED)
344
        {
345
            self.observed = Some(observer);
346
            self.shame += 1;
347
            if observer == Observer::Cat && self.chance(CAT_TAKES_TOWEL) {
348
                self.here.towel_stolen = true;
349
            }
350
        }
351
        if intensity >= PULLED_MUSCLE_INTENSITY
352
            && !self.conditions.pulled_muscle
353
            && self.chance(PULLED_MUSCLE)
354
        {
355
            self.conditions.pulled_muscle = true;
356
            self.stamina = self.stamina.min(self.max_stamina());
357
        }
358
        if self.items.ring && self.eq > HOT_EQ && self.chance(RING_PRIAPISM) {
359
            self.conditions.priapism_turns = PRIAPISM_TURNS;
360
        }
361
        if self.conditions.priapism_turns > 0 {
362
            self.conditions.priapism_turns -= 1;
363
            self.eq = self.eq.max(PRIAPISM_EQ);
364
        }
365
        if self.turn == BRANCH_TURN && self.story == Story::Unopened {
366
            self.story = Story::Pending;
367
        }
368
    }
369
370
    fn maybe_summon_mum(&mut self, was_below: bool) {
371
        if !self.floor.has_mum() || self.mum.is_some() {
372
            return;
373
        }
374
        let summoned = was_below && self.suspicion == SUSPICION_LIMIT;
375
        let visits = u32::from(self.suspicion) + 1;
376
        if summoned || self.rng.random_ratio(visits, super::balance::MUM_VISIT) {
377
            let errand = self.errand(summoned);
378
            let nonce = self.fresh_nonce();
379
            self.mum = Some(MumVisit {
380
                errand,
381
                nonce,
382
                strikes: 0,
383
            });
384
        }
385
    }
386
387
    fn roll(
388
        &mut self,
389
        training: Training,
390
        intensity: i32,
391
        lube: Option<Lube>,
392
    ) -> Result<Outcome, Problem> {
393
        let profile = training.profile();
394
        let natural: i32 = self.rng.random_range(1..=20);
395
        let band = if EQ_BAND.contains(&self.eq) {
396
            BAND_BONUS
397
        } else {
398
            0
399
        };
400
        let grip = match (self.grip, training) {
401
            (Grip::Underhand, Training::Stretch) => 2,
402
            (Grip::Underhand, Training::Wet) => -1,
403
            _ => 0,
404
        };
405
        let modifier = lube.map_or(0, Lube::modifier) + band + grip;
406
        let dc = profile.dc + intensity / 3;
407
        let total = natural + modifier;
408
        let timing = format!("roll;desc=\"d20{modifier:+} vs {dc}\";dur={natural}");
409
        let timed = |p: Problem| p.header(SERVER_TIMING, &timing);
410
411
        let (length, girth) = self.scaled_gains(&profile, intensity);
412
        let rupture_line = if self.items.ring {
413
            RING_RUPTURE_LINE
414
        } else {
415
            RUPTURE_LINE
416
        };
417
418
        if natural == 1 {
419
            return Err(timed(self.critical_failure(training, &profile)));
420
        }
421
        if natural == 2 && self.eq > DANGER_EQ {
422
            return Err(timed(self.rupture()));
423
        }
424
        if self.eq > rupture_line && total < dc {
425
            return Err(timed(self.rupture()));
426
        }
427
        if natural == 20 {
428
            self.gain(length * 2.0, girth * 2.0, profile.foreskin_growth);
429
            return Ok(Outcome::json(
430
                StatusCode::PERMANENT_REDIRECT,
431
                json!({
432
                    "detail": "Your length has moved permanently.",
433
                    "length": round3(length * 2.0),
434
                    "girth": round3(girth * 2.0),
435
                }),
436
            )
437
            .header(header::LOCATION, self.path("/length"))
438
            .header(SERVER_TIMING, timing));
439
        }
440
        if total < dc - 3 {
441
            return Err(timed(not_extended()));
442
        }
443
        if total < dc {
444
            return Ok(Outcome::empty(StatusCode::NO_CONTENT).header(SERVER_TIMING, timing));
445
        }
446
447
        let outcome = if self.eq < *EQ_BAND.start() {
448
            self.gain(length / 2.0, girth / 2.0, profile.foreskin_growth);
449
            Outcome::json(
450
                StatusCode::PARTIAL_CONTENT,
451
                json!({
452
                    "detail": "Partial gains were applied. EQ was below the band.",
453
                    "length": round3(length / 2.0),
454
                    "girth": round3(girth / 2.0),
455
                }),
456
            )
457
        } else if total >= dc + 5 {
458
            self.gain(length, girth, profile.foreskin_growth);
459
            Outcome::json(
460
                StatusCode::OK,
461
                json!({
462
                    "detail": "Gains were applied.",
463
                    "length": round3(length),
464
                    "girth": round3(girth),
465
                }),
466
            )
467
        } else {
468
            let eta = self.rng.random_range(1..=4);
469
            self.pending.push(Pending {
470
                due: self.turn + eta,
471
                length,
472
                girth,
473
            });
474
            self.gain(0.0, 0.0, profile.foreskin_growth);
475
            Outcome::json(
476
                StatusCode::ACCEPTED,
477
                json!({
478
                    "detail": "Gains have been queued. They may arrive.",
479
                    "eta_turns": eta,
480
                }),
481
            )
482
        };
483
        Ok(outcome.header(SERVER_TIMING, timing))
484
    }
485
486
    fn scaled_gains(&self, profile: &Profile, intensity: i32) -> (f64, f64) {
487
        let scale = f64::from(intensity);
488
        let (mut length, mut girth) = (profile.length * scale, profile.girth * scale);
489
        if self.here.teapot {
490
            length *= 0.5;
491
            girth *= 1.5;
492
        }
493
        if self.items.ring {
494
            girth *= 2.0;
495
        }
496
        (length, girth)
497
    }
498
499
    fn critical_failure(&mut self, training: Training, profile: &Profile) -> Problem {
500
        let uses_foreskin = profile.foreskin.is_some_and(|(min, _)| min > 0.0);
501
        if uses_foreskin && self.foreskin.is_some() {
502
            self.foreskin = None;
503
            self.shame += 25;
504
            return Problem::new(
505
                StatusCode::GONE,
506
                "foreskin-lost",
507
                "The technique has removed the foreskin. It will not be returning.",
508
            )
509
            .header(header::CONTENT_LOCATION, self.path("/foreskin"));
510
        }
511
        if self.eq > DANGER_EQ {
512
            return self.rupture();
513
        }
514
        if training == Training::Stretch && !self.here.teapot {
515
            self.here.teapot = true;
516
            self.items.teapot_spout = true;
517
            self.shame += 5;
518
            return Problem::new(
519
                StatusCode::IM_A_TEAPOT,
520
                "teapot",
521
                "The subject is now short and stout. Length gains are halved for the rest of the floor.",
522
            );
523
        }
524
        if training == Training::Uli && !self.conditions.peyronie {
525
            self.conditions.peyronie = true;
526
            self.shame += 5;
527
            return Problem::new(
528
                StatusCode::MISDIRECTED_REQUEST,
529
                "curvature",
530
                "A curvature has developed. Techniques will land slightly to the left until a professional is consulted.",
531
            );
532
        }
533
        not_extended()
534
    }
535
536
    fn gossip(&mut self, mut outcome: Outcome) -> Outcome {
537
        let reportable = matches!(outcome.status.as_u16(), 200 | 202 | 206);
538
        if !self.here.flatmate_told || !reportable {
539
            return outcome;
540
        }
541
        self.here.flatmate_told = false;
542
        outcome.status = StatusCode::ALREADY_REPORTED;
543
        if let Payload::Json(body) = &mut outcome.payload {
544
            body["detail"] = json!("The flatmate has already told everyone.");
545
        }
546
        outcome
547
    }
548
}