atagen

jelq

public

an http based roguelike rpg about jelqing

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