atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
4347977b819220280d64f9e914967717329b830a
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/game/mod.rsRust323 lines8.8 KB
1
pub mod balance;
2
mod body;
3
mod clinic;
4
mod floors;
5
mod forum;
6
mod hazards;
7
mod household;
8
mod items;
9
mod outcome;
10
mod shop;
11
mod state;
12
mod techniques;
13
mod turn;
14
mod utility;
15
16
pub use body::PatchOp;
17
pub use forum::{ELDER_LAST_MODIFIED, FORUM_THREAD, forum_thread};
18
pub use items::{Item, Items, SHOP};
19
pub use outcome::{Outcome, Payload};
20
pub use state::{
21
    Cause, Clinic, Conditions, Elder, Ending, Floor, FloorState, Grip, MumVisit, Observer, Story,
22
};
23
pub use techniques::{LUBRICANTS, Lube, Technique};
24
25
use std::{
26
    hash::{DefaultHasher, Hash, Hasher},
27
    time::{Duration, Instant, SystemTime},
28
};
29
30
use axum::http::{StatusCode, header};
31
use rand::{Rng, SeedableRng, rngs::StdRng};
32
use serde_json::{Value, json};
33
34
use crate::problem::Problem;
35
use balance::{
36
    HONEST_TOLERANCE, MAX_STAMINA, PULLED_STAMINA, SELF_REPORT_INFLATION, STARTING_CASH,
37
    STARTING_EQ,
38
};
39
use state::Pending;
40
41
pub struct Run {
42
    /// The private id in the run's URL. Knowing it is the only authorisation a run has.
43
    pub id: String,
44
    pub public_id: String,
45
    etag_salt: u64,
46
    pub version: u64,
47
    pub turn: u32,
48
    pub floor: Floor,
49
    pub here: FloorState,
50
    pub length: f64,
51
    pub girth: f64,
52
    pub foreskin: Option<f64>,
53
    pub eq: i32,
54
    pub stamina: i32,
55
    pub suspicion: u8,
56
    pub shame: u32,
57
    pub shame_reported: u32,
58
    pub shame_total: u32,
59
    pub cash: u32,
60
    pub grip: Grip,
61
    pub items: Items,
62
    pub conditions: Conditions,
63
    pub warmed_up: bool,
64
    pub put_applied: bool,
65
    pub story: Story,
66
    pub meditation_taught: bool,
67
    pub mum: Option<MumVisit>,
68
    pub heard: Vec<String>,
69
    pub elder: Elder,
70
    pub clinic: Clinic,
71
    pub seeded: bool,
72
    pub filmed_at: Option<SystemTime>,
73
    pub observed: Option<Observer>,
74
    pub refractory: Duration,
75
    pub refractory_until: Option<Instant>,
76
    pub pending: Vec<Pending>,
77
    pub notices: Vec<&'static str>,
78
    pub ended: Option<Ending>,
79
    pub last_seen: Instant,
80
    rng: StdRng,
81
}
82
83
pub fn round2(x: f64) -> f64 {
84
    (x * 100.0).round() / 100.0
85
}
86
87
fn round3(x: f64) -> f64 {
88
    (x * 1000.0).round() / 1000.0
89
}
90
91
fn honest(claimed: f64, actual: f64) -> bool {
92
    (claimed - actual).abs() < HONEST_TOLERANCE
93
}
94
95
fn not_extended() -> Problem {
96
    Problem::new(
97
        StatusCode::NOT_EXTENDED,
98
        "not-extended",
99
        "The requested extension was not applied. The server has recorded the attempt.",
100
    )
101
}
102
103
pub fn parse_credentials<'a>(authorization: &'a str, scheme: &str) -> Option<&'a str> {
104
    let (given, rest) = authorization.trim().split_once(' ')?;
105
    given
106
        .eq_ignore_ascii_case(scheme)
107
        .then(|| rest.trim().trim_matches('"'))
108
}
109
110
pub fn etag_matches(condition: &str, etag: &str) -> bool {
111
    condition
112
        .split(',')
113
        .map(str::trim)
114
        .any(|tag| tag == "*" || tag.trim_start_matches("W/") == etag)
115
}
116
117
pub fn shaft(mm: usize) -> String {
118
    format!("8{}D", "=".repeat(mm.saturating_sub(2)))
119
}
120
121
impl Run {
122
    pub fn new(id: String, public_id: String, seed: u64) -> Self {
123
        let mut rng = StdRng::seed_from_u64(seed);
124
        let length = round2(rng.random_range(4.5..6.5));
125
        let girth = round2(rng.random_range(4.0..5.0));
126
        let foreskin = round2(rng.random_range(0.4..2.4));
127
        let etag_salt = rng.random();
128
        Self {
129
            id,
130
            public_id,
131
            etag_salt,
132
            version: 0,
133
            turn: 0,
134
            floor: Floor::Bedroom,
135
            here: FloorState::default(),
136
            length,
137
            girth,
138
            foreskin: Some(foreskin),
139
            eq: STARTING_EQ,
140
            stamina: MAX_STAMINA,
141
            suspicion: 0,
142
            shame: 0,
143
            shame_reported: 0,
144
            shame_total: 0,
145
            cash: STARTING_CASH,
146
            grip: Grip::Overhand,
147
            items: Items::default(),
148
            conditions: Conditions::default(),
149
            warmed_up: false,
150
            put_applied: false,
151
            story: Story::Unopened,
152
            meditation_taught: false,
153
            mum: None,
154
            heard: Vec::new(),
155
            notices: Vec::new(),
156
            elder: Elder::Unverified { strikes: 0 },
157
            clinic: Clinic::default(),
158
            seeded: false,
159
            filmed_at: None,
160
            observed: None,
161
            refractory: Duration::from_secs(30),
162
            refractory_until: None,
163
            pending: Vec::new(),
164
            ended: None,
165
            last_seen: Instant::now(),
166
            rng,
167
        }
168
    }
169
170
    fn etag_at(&self, version: u64) -> String {
171
        let mut hasher = DefaultHasher::new();
172
        (self.etag_salt, version).hash(&mut hasher);
173
        format!("\"{:016x}\"", hasher.finish())
174
    }
175
176
    pub fn etag(&self) -> String {
177
        self.etag_at(self.version)
178
    }
179
180
    /// The ETag the run had when it was created, which the true ending asks for.
181
    pub fn origin_etag(&self) -> String {
182
        self.etag_at(0)
183
    }
184
185
    pub fn touch(&mut self) {
186
        self.version += 1;
187
    }
188
189
    fn fresh_nonce(&mut self) -> String {
190
        format!("{:016x}", self.rng.random::<u64>())
191
    }
192
193
    fn chance(&mut self, odds: u32) -> bool {
194
        self.rng.random_ratio(1, odds)
195
    }
196
197
    pub fn path(&self, sub: &str) -> String {
198
        format!("/runs/{}{sub}", self.id)
199
    }
200
201
    pub fn current_length(&self) -> f64 {
202
        self.length + self.here.temp_length
203
    }
204
205
    pub fn self_reported(&self) -> f64 {
206
        self.current_length() + SELF_REPORT_INFLATION
207
    }
208
209
    pub fn max_stamina(&self) -> i32 {
210
        if self.conditions.pulled_muscle {
211
            PULLED_STAMINA
212
        } else {
213
            MAX_STAMINA
214
        }
215
    }
216
217
    pub fn forum_read(&self) -> bool {
218
        self.story == Story::ReadForum
219
    }
220
221
    pub fn footage(&self) -> Option<(SystemTime, u64)> {
222
        let filmed = self.filmed_at?;
223
        let age = filmed.elapsed().map_or(0, |d| d.as_secs());
224
        Some((filmed, age))
225
    }
226
227
    pub fn status(&self) -> &'static str {
228
        match (&self.ended, self.clinic.cured) {
229
            (Some(_), _) => "gone",
230
            (None, true) => "normal",
231
            (None, false) => "alive",
232
        }
233
    }
234
235
    /// The parts of the run that its response headers do not already carry.
236
    pub fn view(&self) -> Value {
237
        let conditions: Vec<&str> = [
238
            (self.here.teapot, "short and stout"),
239
            (self.conditions.peyronie, "curved"),
240
            (self.items.cage, "caged"),
241
            (self.conditions.priapism_turns > 0, "priapism"),
242
            (self.conditions.pulled_muscle, "pulled muscle"),
243
            (self.filmed_at.is_some(), "viral"),
244
        ]
245
        .into_iter()
246
        .filter_map(|(active, name)| active.then_some(name))
247
        .collect();
248
        json!({
249
            "public_id": self.public_id,
250
            "status": self.status(),
251
            "turn": self.turn,
252
            "run_shame": self.shame,
253
            "grip": self.grip.name(),
254
            "warmed_up": self.warmed_up,
255
            "ranked": !self.seeded,
256
            "conditions": conditions,
257
        })
258
    }
259
260
    pub fn end(&mut self, cause: Cause) -> Problem {
261
        self.ended = Some(Ending {
262
            cause,
263
            turn: self.turn,
264
        });
265
        cause.problem().with("turn", self.turn)
266
    }
267
268
    /// Ends the refractory period once it has run out, whatever the request.
269
    pub fn recover(&mut self, now: Instant) {
270
        if self.refractory_until.is_some_and(|until| now >= until) {
271
            self.refractory_until = None;
272
            self.stamina = self.max_stamina();
273
            self.eq = STARTING_EQ;
274
            self.warmed_up = false;
275
            self.touch();
276
        }
277
    }
278
279
    fn check_refractory(&mut self, now: Instant) -> Result<(), Problem> {
280
        self.recover(now);
281
        let Some(until) = self.refractory_until else {
282
            return Ok(());
283
        };
284
        let seconds = until.saturating_duration_since(now).as_secs() + 1;
285
        Err(Problem::new(
286
            StatusCode::TOO_MANY_REQUESTS,
287
            "overtrained",
288
            "Stamina is exhausted. The refractory period is in effect.",
289
        )
290
        .header(header::RETRY_AFTER, seconds.to_string()))
291
    }
292
293
    fn exhaust(&mut self, now: Instant) {
294
        self.stamina = 0;
295
        self.refractory_until = Some(now + self.refractory);
296
    }
297
298
    fn realise(&mut self) {
299
        let (due, waiting): (Vec<_>, Vec<_>) = std::mem::take(&mut self.pending)
300
            .into_iter()
301
            .partition(|p| p.due <= self.turn);
302
        self.pending = waiting;
303
        for p in due {
304
            self.length += p.length;
305
            self.girth += p.girth;
306
        }
307
    }
308
309
    fn gain(&mut self, length: f64, girth: f64, foreskin: f64) {
310
        self.length += length;
311
        self.girth += girth;
312
        if let Some(f) = &mut self.foreskin {
313
            *f += foreskin;
314
        }
315
    }
316
317
    fn rupture(&mut self) -> Problem {
318
        let cause = Cause::Ruptured {
319
            ice_unused: self.items.ice_packs > 0,
320
        };
321
        self.end(cause)
322
    }
323
}