atagen

jelq

public

an http based roguelike rpg about jelqing

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