rspin 0.1.0

A terminal-based slot machine simulator with animated reels
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use crossterm::{
    cursor,
    event::{self, Event},
    execute,
    style::Stylize,
    terminal::{Clear, ClearType, disable_raw_mode, enable_raw_mode},
};
use std::collections::HashSet;
use std::io::{self, Write};
use std::thread;
use std::time::Duration;

use crate::{
    animation_state::{
        AnimationState, AnimationType, FRAMES_PER_PAYLINE, LEVER_PULL_FRAME_TIME,
        total_animation_frames,
    },
    machine::{Machine, calc_reel_starting_points, get_visible_symbols_for_reel},
    paylines::Paylines,
};

// TODO: make this configurable (with a "fast mode")
// TODO: add some debug prints/flag
// TODO: add a session tracker, need to think through this
const FRAME_MS: u64 = 80;
const LEFT_PADDING: usize = 5;
const REEL_WIDTH: usize = 3;

pub struct TerminalUI {
    stdout: io::Stdout,
}

impl TerminalUI {
    pub fn new() -> Self {
        Self {
            stdout: io::stdout(),
        }
    }

    pub fn start(&mut self, total_lines: u16) -> io::Result<()> {
        enable_raw_mode()?;
        execute!(self.stdout, cursor::Hide)?;

        // Set the stage
        // We print the lines once to push the prompt up and establish our space.
        for _ in 0..total_lines {
            writeln!(self.stdout)?;
        }

        Ok(())
    }

    #[allow(clippy::unused_self)]
    pub fn wait_for_keypress(&mut self) -> io::Result<()> {
        loop {
            if let Event::Key(_) = event::read()? {
                break;
            }
        }

        Ok(())
    }

    pub fn finish(&mut self, total_lines: u16) -> io::Result<()> {
        execute!(self.stdout, cursor::Show)?;
        disable_raw_mode()?;

        // Cleanup
        // Move back up one last time and wipe the stage clean.
        execute!(
            self.stdout,
            cursor::MoveUp(total_lines + 1),
            Clear(ClearType::FromCursorDown)
        )?;

        Ok(())
    }

    pub fn run_spin_animation(&mut self, machines: &[Machine], total_lines: u16) -> io::Result<()> {
        let max_paylines = machines.iter().map(|m| m.paylines.len()).max().unwrap_or(0);
        let total_machines = machines.len();

        let mut machine_animations: Vec<(Machine, AnimationState)> = machines
            .iter()
            .enumerate()
            .map(|(i, machine)| {
                (
                    machine.clone(),
                    AnimationState::new(i, total_machines, max_paylines),
                )
            })
            .collect();

        let total_frames = total_animation_frames(total_machines, max_paylines);
        for frame in 0..total_frames {
            // Move to the top of the stage
            execute!(self.stdout, cursor::MoveUp(total_lines))?;
            writeln!(self.stdout)?;

            for (machine, animation_state) in &mut machine_animations {
                self.render_machine_inline(machine, animation_state, frame)?;
            }

            // Total winnings line
            let all_stopped = machine_animations
                .iter()
                .all(|(_, state)| matches!(state.animation_type, AnimationType::Stopped));

            execute!(
                self.stdout,
                cursor::MoveToColumn(0),
                Clear(ClearType::UntilNewLine)
            )?;
            if all_stopped {
                let total_winnings: i32 = machine_animations
                    .iter()
                    .map(|(m, _)| m.paylines.iter().map(|p| p.get_payout(m.bet)).sum::<i32>())
                    .sum();
                writeln!(
                    self.stdout,
                    "{}You won {} credits!",
                    " ".repeat(LEFT_PADDING),
                    total_winnings
                )?;
            } else {
                writeln!(self.stdout)?;
            }

            // Press any key line
            execute!(
                self.stdout,
                cursor::MoveToColumn(0),
                Clear(ClearType::UntilNewLine)
            )?;
            if all_stopped {
                writeln!(
                    self.stdout,
                    "{}{}",
                    " ".repeat(LEFT_PADDING),
                    "Press any key to continue...".dark_grey()
                )?;
            } else {
                writeln!(self.stdout)?;
            }

            self.stdout.flush()?;
            thread::sleep(Duration::from_millis(FRAME_MS));
        }

        Ok(())
    }

    #[allow(clippy::too_many_lines)]
    fn render_machine_inline(
        &mut self,
        machine: &mut Machine,
        animation_state: &mut AnimationState,
        frame: usize,
    ) -> io::Result<()> {
        // Go to top
        execute!(
            self.stdout,
            cursor::MoveToColumn(0),
            Clear(ClearType::UntilNewLine)
        )?;

        // Header
        writeln!(
            self.stdout,
            "{} {}",
            " ".repeat(11),
            (*machine.name).yellow()
        )?;

        // Make top of machine
        // │ ┌ ┐ └ ┘ ┬ ┴ ─
        execute!(
            self.stdout,
            cursor::MoveToColumn(0),
            Clear(ClearType::UntilNewLine)
        )?;
        writeln!(
            self.stdout,
            "{}{}{}{}{}{}",
            " ".repeat(LEFT_PADDING),
            "".repeat(REEL_WIDTH),
            "".repeat(REEL_WIDTH),
            "".repeat(REEL_WIDTH),
            "".repeat(REEL_WIDTH),
            "".repeat(REEL_WIDTH),
        )?;

        let reel_mid_overrides = calc_reel_starting_points(machine);

        let info_line: String = match animation_state.animation_type {
            AnimationType::Wait => {
                let visible_symbols =
                    get_visible_symbols_for_reel(&machine.reels, Some(&reel_mid_overrides));
                for (row_idx, row) in visible_symbols.iter().enumerate() {
                    execute!(
                        self.stdout,
                        cursor::MoveToColumn(0),
                        Clear(ClearType::UntilNewLine)
                    )?;

                    let lever = if row_idx == 0 { " O" } else { "  " };
                    writeln!(
                        self.stdout,
                        "{}{}{}{}{}{}{}",
                        " ".repeat(LEFT_PADDING),
                        row[0],
                        row[1],
                        row[2],
                        row[3],
                        row[4],
                        lever
                    )?;
                }
                String::new()
            }
            AnimationType::LeverPull => {
                let lever_frame =
                    (LEVER_PULL_FRAME_TIME - 1).saturating_sub(animation_state.frames_remaining);

                let lever_suffix = |row_idx: usize| -> &'static str {
                    match (lever_frame, row_idx) {
                        (0 | 4, 0) | (1 | 3, 1) | (2, 2) => " O",
                        (1 | 3, 0) | (2, 0 | 1) => " |",
                        _ => "  ",
                    }
                };

                let visible_symbols =
                    get_visible_symbols_for_reel(&machine.reels, Some(&reel_mid_overrides));
                for (row_idx, row) in visible_symbols.iter().enumerate() {
                    execute!(
                        self.stdout,
                        cursor::MoveToColumn(0),
                        Clear(ClearType::UntilNewLine)
                    )?;
                    writeln!(
                        self.stdout,
                        "{}{}{}{}{}{}{}",
                        " ".repeat(LEFT_PADDING),
                        row[0],
                        row[1],
                        row[2],
                        row[3],
                        row[4],
                        lever_suffix(row_idx)
                    )?;
                }
                String::new()
            }
            AnimationType::Spinning => {
                let spinning_mid_override = frame % 20;
                let visible_symbols = get_visible_symbols_for_reel(
                    &machine.reels,
                    Some(&[
                        spinning_mid_override,
                        spinning_mid_override,
                        spinning_mid_override,
                        spinning_mid_override,
                        spinning_mid_override,
                    ]),
                );
                for (row_idx, row) in visible_symbols.iter().enumerate() {
                    execute!(
                        self.stdout,
                        cursor::MoveToColumn(0),
                        Clear(ClearType::UntilNewLine)
                    )?;

                    let lever = if row_idx == 0 { " O" } else { "  " };
                    writeln!(
                        self.stdout,
                        "{}{}{}{}{}{}{}",
                        " ".repeat(LEFT_PADDING),
                        row[0],
                        row[1],
                        row[2],
                        row[3],
                        row[4],
                        lever,
                    )?;
                }
                String::new()
            }
            AnimationType::ShowWinnings => {
                let visible_symbols = get_visible_symbols_for_reel(&machine.reels, None);

                if machine.paylines.is_empty() {
                    for (row_idx, row) in visible_symbols.iter().enumerate() {
                        execute!(
                            self.stdout,
                            cursor::MoveToColumn(0),
                            Clear(ClearType::UntilNewLine)
                        )?;

                        let lever = if row_idx == 0 { " O" } else { "  " };
                        writeln!(
                            self.stdout,
                            "{}{}{}{}{}{}{}",
                            " ".repeat(LEFT_PADDING),
                            format!("{}", row[0]).dark_grey(),
                            format!("{}", row[1]).dark_grey(),
                            format!("{}", row[2]).dark_grey(),
                            format!("{}", row[3]).dark_grey(),
                            format!("{}", row[4]).dark_grey(),
                            lever,
                        )?;
                    }
                    format!("{}{}", " ".repeat(LEFT_PADDING), "0 lines paid 0 credits")
                } else {
                    let elapsed = animation_state
                        .show_winnings_duration
                        .saturating_sub(animation_state.frames_remaining);
                    let current_idx = (elapsed / FRAMES_PER_PAYLINE) % machine.paylines.len();
                    let current_payline = &machine.paylines[current_idx];

                    let winning_positions: HashSet<(usize, usize)> =
                        current_payline.positions().iter().copied().collect();

                    for (row_idx, row) in visible_symbols.iter().enumerate() {
                        execute!(
                            self.stdout,
                            cursor::MoveToColumn(0),
                            Clear(ClearType::UntilNewLine)
                        )?;

                        let lever = if row_idx == 0 { " O" } else { "  " };

                        let styled: Vec<String> = row
                            .iter()
                            .enumerate()
                            .map(|(col_idx, sym)| {
                                let text = format!("{sym}");
                                if winning_positions.contains(&(row_idx, col_idx)) {
                                    style_winning_symbol(current_payline, text).to_string()
                                } else {
                                    format!("{}", text.dark_grey())
                                }
                            })
                            .collect();

                        writeln!(
                            self.stdout,
                            "{}{}{}{}{}{}{}",
                            " ".repeat(LEFT_PADDING),
                            styled[0],
                            styled[1],
                            styled[2],
                            styled[3],
                            styled[4],
                            lever,
                        )?;
                    }

                    let payout = current_payline.get_payout(machine.bet);
                    format!(
                        "{}{} ({}) - {} credits",
                        " ".repeat(LEFT_PADDING),
                        current_payline.display_name(),
                        current_payline.symbol(),
                        payout
                    )
                }
            }
            AnimationType::Stopped => {
                let visible_symbols = get_visible_symbols_for_reel(&machine.reels, None);
                for (row_idx, row) in visible_symbols.iter().enumerate() {
                    execute!(
                        self.stdout,
                        cursor::MoveToColumn(0),
                        Clear(ClearType::UntilNewLine)
                    )?;

                    let lever = if row_idx == 0 { " O" } else { "  " };
                    writeln!(
                        self.stdout,
                        "{}{}{}{}{}{}{}",
                        " ".repeat(LEFT_PADDING),
                        format!("{}", row[0]).dark_grey(),
                        format!("{}", row[1]).dark_grey(),
                        format!("{}", row[2]).dark_grey(),
                        format!("{}", row[3]).dark_grey(),
                        format!("{}", row[4]).dark_grey(),
                        lever,
                    )?;
                }

                let total_payout: i32 = machine
                    .paylines
                    .iter()
                    .map(|p| p.get_payout(machine.bet))
                    .sum();
                let line_count = machine.paylines.len();
                format!(
                    "{}{} lines paid {} credits",
                    " ".repeat(LEFT_PADDING),
                    line_count,
                    total_payout
                )
            }
        };

        // Make bottom of machine
        // │ ┌ ┐ └ ┘ ┬ ┴ ─
        execute!(
            self.stdout,
            cursor::MoveToColumn(0),
            Clear(ClearType::UntilNewLine)
        )?;
        writeln!(
            self.stdout,
            "{}{}{}{}{}{}",
            " ".repeat(LEFT_PADDING),
            "".repeat(REEL_WIDTH),
            "".repeat(REEL_WIDTH),
            "".repeat(REEL_WIDTH),
            "".repeat(REEL_WIDTH),
            "".repeat(REEL_WIDTH),
        )?;

        // Info line
        execute!(
            self.stdout,
            cursor::MoveToColumn(0),
            Clear(ClearType::UntilNewLine)
        )?;
        writeln!(self.stdout, "{info_line}")?;

        // Spacer
        execute!(
            self.stdout,
            cursor::MoveToColumn(0),
            Clear(ClearType::UntilNewLine)
        )?;
        writeln!(self.stdout)?;

        animation_state.tick();
        Ok(())
    }
}

fn style_winning_symbol(payline: &Paylines, text: String) -> String {
    let styled = match payline {
        Paylines::HorSM(..) => text.yellow().bold(),
        Paylines::AboveSM(..) => text.cyan().bold(),
        Paylines::BelowSM(..) => text.blue().bold(),
        Paylines::ZigSM(..) => text.magenta().bold(),
        Paylines::ZagSM(..) => text.dark_magenta().bold(),
        Paylines::HorXL(..) => text.green().bold(),
        Paylines::Zig(..) => text.dark_yellow().bold(),
        Paylines::Zag(..) => text.red().bold(),
        Paylines::Above(..) => text.dark_cyan().bold(),
        Paylines::Below(..) => text.dark_blue().bold(),
        Paylines::Eye(..) => text.white().bold(),
    };
    format!("{styled}")
}