atagen

jelq

public

an http based roguelike rpg about jelqing

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