atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
d46f9d0b953a8d854b9d7f39453d483164282ea4
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/game/turn.rsRust546 lines19.3 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.refractory_until.is_some_and(|until| now < until);
245
        if blocked {
246
            return Vec::new();
247
        }
248
        Technique::ALL
249
            .into_iter()
250
            .filter(|&technique| match technique {
251
                Technique::Utility(Utility::Warmup) => true,
252
                Technique::Utility(Utility::Ice) => self.items.ice_packs > 0,
253
                Technique::Utility(Utility::Supplement) => self.items.supplements > 0,
254
                _ => self.access(technique).is_ok() && self.check_storage().is_ok(),
255
            })
256
            .collect()
257
    }
258
259
    fn check_foreskin(&self, min: f64, max: f64) -> Result<(), Problem> {
260
        let Some(f) = self.foreskin else {
261
            if min <= 0.0 {
262
                return Ok(());
263
            }
264
            return Err(Problem::new(
265
                StatusCode::GONE,
266
                "foreskin-gone",
267
                "This technique requires a foreskin. The foreskin is gone.",
268
            )
269
            .header(header::CONTENT_LOCATION, self.path("/foreskin")));
270
        };
271
        if f < min {
272
            return Err(Problem::new(
273
                StatusCode::LENGTH_REQUIRED,
274
                "foreskin-insufficient",
275
                format!(
276
                    "The selected technique requires {min:.1} units of foreskin. {f:.2} units are available. The server has noted the shortfall."
277
                ),
278
            )
279
            .with("required", min));
280
        }
281
        if f > max {
282
            return Err(Problem::new(
283
                StatusCode::PAYLOAD_TOO_LARGE,
284
                "foreskin-excessive",
285
                format!(
286
                    "The selected technique tolerates at most {max:.1} units of foreskin. {f:.2} units are present."
287
                ),
288
            )
289
            .with("maximum", max));
290
        }
291
        Ok(())
292
    }
293
294
    fn check_storage(&self) -> Result<(), Problem> {
295
        if self.items.extender && self.girth > STORAGE_GIRTH {
296
            return Err(Problem::new(
297
                StatusCode::INSUFFICIENT_STORAGE,
298
                "jeans-full",
299
                "The jeans are full. The extender is occupying the remaining storage.",
300
            )
301
            .with("extender", self.path("/inventory/extender")));
302
        }
303
        Ok(())
304
    }
305
306
    pub(super) fn commit(&mut self, intensity: i32, lube: Option<Lube>, now: Instant, cost: i32) {
307
        self.touch();
308
        self.turn += 1;
309
        self.here.turns += 1;
310
        self.realise();
311
        if self.items.extender {
312
            self.length += EXTENDER_GAIN;
313
        }
314
        self.stamina -= cost + i32::from(lube == Some(Lube::Lotion));
315
        if self.stamina <= 0 {
316
            self.exhaust(now);
317
        }
318
        let chill = if self.floor == Floor::ChangingRoom {
319
            CHANGING_ROOM_CHILL
320
        } else {
321
            0
322
        };
323
        let wobble = self.rng.random_range(-EQ_WOBBLE..=EQ_WOBBLE);
324
        self.eq = (self.eq + intensity * 2 - 6 - chill + wobble).clamp(0, 100);
325
326
        let mut suspicion = intensity / 5 + i32::from(lube == Some(Lube::Vaseline));
327
        if matches!(self.floor, Floor::ChangingRoom | Floor::Nans) {
328
            suspicion *= 2;
329
        }
330
        if self.floor == Floor::Nans && lube == Some(Lube::CoconutOil) {
331
            suspicion += 2;
332
        }
333
        let was_below = self.suspicion < SUSPICION_LIMIT;
334
        self.suspicion =
335
            u8::try_from((i32::from(self.suspicion) + suspicion).min(i32::from(SUSPICION_LIMIT)))
336
                .unwrap_or(SUSPICION_LIMIT);
337
        self.maybe_summon_mum(was_below);
338
339
        if let Some(observer) = self.floor.observer()
340
            && self.chance(OBSERVED)
341
        {
342
            self.observed = Some(observer);
343
            self.shame += 1;
344
            if observer == Observer::Cat && self.chance(CAT_TAKES_TOWEL) {
345
                self.here.towel_stolen = true;
346
            }
347
        }
348
        if intensity >= PULLED_MUSCLE_INTENSITY
349
            && !self.conditions.pulled_muscle
350
            && self.chance(PULLED_MUSCLE)
351
        {
352
            self.conditions.pulled_muscle = true;
353
            self.stamina = self.stamina.min(self.max_stamina());
354
        }
355
        if self.items.ring && self.eq > HOT_EQ && self.chance(RING_PRIAPISM) {
356
            self.conditions.priapism_turns = PRIAPISM_TURNS;
357
        }
358
        if self.conditions.priapism_turns > 0 {
359
            self.conditions.priapism_turns -= 1;
360
            self.eq = self.eq.max(PRIAPISM_EQ);
361
        }
362
        if self.turn == BRANCH_TURN && self.story == Story::Unopened {
363
            self.story = Story::Pending;
364
        }
365
    }
366
367
    pub(super) fn maybe_summon_mum(&mut self, was_below: bool) {
368
        if !self.floor.has_mum() || self.mum.is_some() {
369
            return;
370
        }
371
        let summoned = was_below && self.suspicion == SUSPICION_LIMIT;
372
        let visits = u32::from(self.suspicion) + 1;
373
        if summoned || self.rng.random_ratio(visits, super::balance::MUM_VISIT) {
374
            let errand = self.errand(summoned);
375
            let nonce = self.fresh_nonce();
376
            self.mum = Some(MumVisit {
377
                errand,
378
                nonce,
379
                strikes: 0,
380
                knocked: false,
381
            });
382
        }
383
    }
384
385
    fn roll(
386
        &mut self,
387
        training: Training,
388
        intensity: i32,
389
        lube: Option<Lube>,
390
    ) -> Result<Outcome, Problem> {
391
        let profile = training.profile();
392
        let natural: i32 = self.rng.random_range(1..=20);
393
        let band = if EQ_BAND.contains(&self.eq) {
394
            BAND_BONUS
395
        } else {
396
            0
397
        };
398
        let grip = match (self.grip, training) {
399
            (Grip::Underhand, Training::Stretch) => 2,
400
            (Grip::Underhand, Training::Wet) => -1,
401
            _ => 0,
402
        };
403
        let modifier = lube.map_or(0, Lube::modifier) + band + grip;
404
        let dc = profile.dc + intensity / 3;
405
        let total = natural + modifier;
406
        let timing = format!("roll;desc=\"d20{modifier:+} vs {dc}\";dur={natural}");
407
        let timed = |p: Problem| p.header(SERVER_TIMING, &timing);
408
409
        let (length, girth) = self.scaled_gains(&profile, intensity);
410
        let rupture_line = if self.items.ring {
411
            RING_RUPTURE_LINE
412
        } else {
413
            RUPTURE_LINE
414
        };
415
416
        if natural == 1 {
417
            return Err(timed(self.critical_failure(training, &profile)));
418
        }
419
        if natural == 2 && self.eq > DANGER_EQ {
420
            return Err(timed(self.rupture()));
421
        }
422
        if self.eq > rupture_line && total < dc {
423
            return Err(timed(self.rupture()));
424
        }
425
        if natural == 20 {
426
            self.gain(length * 2.0, girth * 2.0, profile.foreskin_growth);
427
            return Ok(Outcome::json(
428
                StatusCode::PERMANENT_REDIRECT,
429
                json!({
430
                    "detail": "Your length has moved permanently.",
431
                    "length": round3(length * 2.0),
432
                    "girth": round3(girth * 2.0),
433
                }),
434
            )
435
            .header(header::LOCATION, self.path("/length"))
436
            .header(SERVER_TIMING, timing));
437
        }
438
        if total < dc - 3 {
439
            return Err(timed(not_extended()));
440
        }
441
        if total < dc {
442
            return Ok(Outcome::empty(StatusCode::NO_CONTENT).header(SERVER_TIMING, timing));
443
        }
444
445
        let outcome = if self.eq < *EQ_BAND.start() {
446
            self.gain(length / 2.0, girth / 2.0, profile.foreskin_growth);
447
            Outcome::json(
448
                StatusCode::PARTIAL_CONTENT,
449
                json!({
450
                    "detail": "Partial gains were applied. EQ was below the band.",
451
                    "length": round3(length / 2.0),
452
                    "girth": round3(girth / 2.0),
453
                }),
454
            )
455
        } else if total >= dc + 5 {
456
            self.gain(length, girth, profile.foreskin_growth);
457
            Outcome::json(
458
                StatusCode::OK,
459
                json!({
460
                    "detail": "Gains were applied.",
461
                    "length": round3(length),
462
                    "girth": round3(girth),
463
                }),
464
            )
465
        } else {
466
            let eta = self.rng.random_range(1..=4);
467
            self.pending.push(Pending {
468
                due: self.turn + eta,
469
                length,
470
                girth,
471
            });
472
            self.gain(0.0, 0.0, profile.foreskin_growth);
473
            Outcome::json(
474
                StatusCode::ACCEPTED,
475
                json!({
476
                    "detail": "Gains have been queued. They may arrive.",
477
                    "eta_turns": eta,
478
                }),
479
            )
480
        };
481
        Ok(outcome.header(SERVER_TIMING, timing))
482
    }
483
484
    fn scaled_gains(&self, profile: &Profile, intensity: i32) -> (f64, f64) {
485
        let scale = f64::from(intensity);
486
        let (mut length, mut girth) = (profile.length * scale, profile.girth * scale);
487
        if self.here.teapot {
488
            length *= 0.5;
489
            girth *= 1.5;
490
        }
491
        if self.items.ring {
492
            girth *= 2.0;
493
        }
494
        (length, girth)
495
    }
496
497
    fn critical_failure(&mut self, training: Training, profile: &Profile) -> Problem {
498
        let uses_foreskin = profile.foreskin.is_some_and(|(min, _)| min > 0.0);
499
        if uses_foreskin && self.foreskin.is_some() {
500
            self.foreskin = None;
501
            self.shame += 25;
502
            return Problem::new(
503
                StatusCode::GONE,
504
                "foreskin-lost",
505
                "The technique has removed the foreskin. It will not be returning.",
506
            )
507
            .header(header::CONTENT_LOCATION, self.path("/foreskin"));
508
        }
509
        if self.eq > DANGER_EQ {
510
            return self.rupture();
511
        }
512
        if training == Training::Stretch && !self.here.teapot {
513
            self.here.teapot = true;
514
            self.items.teapot_spout = true;
515
            self.shame += 5;
516
            return Problem::new(
517
                StatusCode::IM_A_TEAPOT,
518
                "teapot",
519
                "The subject is now short and stout. Length gains are halved for the rest of the floor.",
520
            );
521
        }
522
        if training == Training::Uli && !self.conditions.peyronie {
523
            self.conditions.peyronie = true;
524
            self.shame += 5;
525
            return Problem::new(
526
                StatusCode::MISDIRECTED_REQUEST,
527
                "curvature",
528
                "A curvature has developed. Techniques will land slightly to the left until a professional is consulted.",
529
            );
530
        }
531
        not_extended()
532
    }
533
534
    fn gossip(&mut self, mut outcome: Outcome) -> Outcome {
535
        let reportable = matches!(outcome.status.as_u16(), 200 | 202 | 206);
536
        if !self.here.flatmate_told || !reportable {
537
            return outcome;
538
        }
539
        self.here.flatmate_told = false;
540
        outcome.status = StatusCode::ALREADY_REPORTED;
541
        if let Payload::Json(body) = &mut outcome.payload {
542
            body["detail"] = json!("The flatmate has already told everyone.");
543
        }
544
        outcome
545
    }
546
}