summaryrefslogtreecommitdiffstats
path: root/src/client/core.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/client/core.rs190
1 files changed, 189 insertions, 1 deletions
diff --git a/src/client/core.rs b/src/client/core.rs
index 77761b4..5f8c513 100644
--- a/src/client/core.rs
+++ b/src/client/core.rs
@@ -1,12 +1,14 @@
1use crate::client::games::manager::GameManager; 1use crate::client::games::manager::GameManager;
2use crate::client::games::response::{ 2use crate::client::games::response::{
3 parse_blackjack_response, parse_roulette_response, parse_spin_response, 3 parse_blackjack_response, parse_crash_response, parse_roulette_response, parse_spin_response,
4}; 4};
5use crate::client::ui::{ 5use crate::client::ui::{
6 command_names, completion_lines, display_width, help_lines, input_cursor_column, 6 command_names, completion_lines, display_width, help_lines, input_cursor_column,
7 parse_bet_arg, record_history, 7 parse_bet_arg, record_history,
8}; 8};
9use crate::crash::{multiplier_at, CrashState};
9use crate::roulette::{Bets, NumberBet}; 10use crate::roulette::{Bets, NumberBet};
11use std::time::{Duration, Instant};
10 12
11#[derive(Debug, Clone, Copy, PartialEq, Eq)] 13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Key { 14pub enum Key {
@@ -66,6 +68,9 @@ enum Pending {
66 BlackjackStart, 68 BlackjackStart,
67 BlackjackAction, 69 BlackjackAction,
68 BlackjackForfeit, 70 BlackjackForfeit,
71 CrashStart,
72 CrashCashout,
73 CrashForfeit,
69 Ping, 74 Ping,
70 Echo, 75 Echo,
71 Info, 76 Info,
@@ -90,6 +95,8 @@ pub struct ClientCore {
90 balance: Option<i64>, 95 balance: Option<i64>,
91 host: Option<String>, 96 host: Option<String>,
92 fingerprint: Option<String>, 97 fingerprint: Option<String>,
98 /// Local anchor for the crash multiplier, set when a round starts.
99 crash_started: Option<Instant>,
93} 100}
94 101
95impl ClientCore { 102impl ClientCore {
@@ -105,6 +112,7 @@ impl ClientCore {
105 balance: None, 112 balance: None,
106 host: None, 113 host: None,
107 fingerprint: None, 114 fingerprint: None,
115 crash_started: None,
108 } 116 }
109 } 117 }
110 118
@@ -113,6 +121,7 @@ impl ClientCore {
113 if !connected { 121 if !connected {
114 self.logged_in = None; 122 self.logged_in = None;
115 self.pending = None; 123 self.pending = None;
124 self.crash_started = None;
116 } 125 }
117 } 126 }
118 127
@@ -226,6 +235,49 @@ impl ClientCore {
226 self.board_effects() 235 self.board_effects()
227 } 236 }
228 }, 237 },
238 Some(Pending::CrashStart) => match parse_crash_response(reply) {
239 Ok(state) => self.apply_crash(state),
240 Err(message) => {
241 self.game.set_error(message);
242 self.board_effects()
243 }
244 },
245 Some(Pending::CrashCashout) => match parse_crash_response(reply) {
246 Ok(state) => self.apply_crash(state),
247 Err(message) => {
248 // A pushed bust can settle the round before this reply
249 // arrives. The late request must not overwrite the result.
250 if self.game.crash_status() != "running" {
251 return self.board_effects();
252 }
253 self.game.set_error(message);
254 self.board_effects()
255 }
256 },
257 Some(Pending::CrashForfeit) => match parse_crash_response(reply) {
258 Ok(state) => {
259 self.crash_started = None;
260 self.game.end_game();
261 let message = format!(
262 "Game exited. Round forfeited ({} PLN lost).",
263 state.bet
264 );
265 vec![Effect::ClearRegion, Effect::Print(vec![message])]
266 }
267 Err(_) if self.game.crash_status() != "running" => {
268 // The round ended while the forfeit was in flight.
269 self.crash_started = None;
270 self.game.end_game();
271 vec![
272 Effect::ClearRegion,
273 Effect::Print(vec!["Game exited.".to_string()]),
274 ]
275 }
276 Err(message) => {
277 self.game.set_error(message);
278 self.board_effects()
279 }
280 },
229 Some(Pending::Ping) => { 281 Some(Pending::Ping) => {
230 if reply.trim() == "PONG" { 282 if reply.trim() == "PONG" {
231 print_line("Pong") 283 print_line("Pong")
@@ -270,6 +322,9 @@ impl ClientCore {
270 if game_type == Some("blackjack") { 322 if game_type == Some("blackjack") {
271 return self.handle_blackjack_key(key); 323 return self.handle_blackjack_key(key);
272 } 324 }
325 if game_type == Some("crash") {
326 return self.handle_crash_key(key);
327 }
273 328
274 match key { 329 match key {
275 Key::CtrlC => vec![Effect::Quit], 330 Key::CtrlC => vec![Effect::Quit],
@@ -559,6 +614,138 @@ impl ClientCore {
559 ))] 614 ))]
560 } 615 }
561 616
617 /// Redraw the rising multiplier. Called by the terminal loop on a timer.
618 pub fn tick(&mut self) -> Vec<Effect> {
619 let Some(started) = self.crash_started else {
620 return Vec::new();
621 };
622 self.tick_at(started.elapsed())
623 }
624
625 pub fn tick_at(&mut self, elapsed: Duration) -> Vec<Effect> {
626 if self.crash_started.is_none() {
627 return Vec::new();
628 }
629 if self
630 .game
631 .get_current_state()
632 .map(|state| state.game_type.as_str())
633 != Some("crash")
634 {
635 return Vec::new();
636 }
637 self.game.set_crash_multiplier(multiplier_at(elapsed));
638 self.board_effects()
639 }
640
641 /// True while the server may push a crash event between requests.
642 pub fn expects_push(&self) -> bool {
643 self.crash_started.is_some()
644 }
645
646 pub fn is_async(&self, line: &str) -> bool {
647 line.trim_start().starts_with("CRASH_BUSTED ")
648 }
649
650 /// Handle a server-initiated line. Returns `None` when the line is a normal
651 /// request/response reply and belongs to `handle_reply`.
652 pub fn handle_async_line(&mut self, line: &str) -> Option<Vec<Effect>> {
653 if !self.is_async(line) {
654 return None;
655 }
656 match parse_crash_response(line) {
657 Ok(state) => Some(self.apply_crash(state)),
658 Err(message) => {
659 self.game.set_error(message);
660 Some(self.board_effects())
661 }
662 }
663 }
664
665 fn apply_crash(&mut self, state: CrashState) -> Vec<Effect> {
666 self.balance = Some(state.balance);
667 if state.is_running() {
668 if self.crash_started.is_none() {
669 self.crash_started = Some(Instant::now());
670 }
671 } else {
672 self.crash_started = None;
673 }
674 self.game.apply_crash_state(state);
675 self.board_effects()
676 }
677
678 fn handle_crash_key(&mut self, key: Key) -> Vec<Effect> {
679 let status = self.game.crash_status();
680 let running = status == "running";
681
682 match key {
683 Key::CtrlC => vec![Effect::Quit],
684 Key::Char('q') => {
685 if running {
686 let Some(session) = self.game.crash_session_id() else {
687 return Vec::new();
688 };
689 self.pending = Some(Pending::CrashForfeit);
690 vec![Effect::SendLine(format!("CRASH_FORFEIT {session}"))]
691 } else {
692 self.crash_started = None;
693 self.game.end_game();
694 vec![
695 Effect::ClearRegion,
696 Effect::Print(vec!["Game exited.".to_string()]),
697 ]
698 }
699 }
700 Key::Char(' ') if !running && self.pending.is_none() => self.start_crash(),
701 Key::Char('c') if running && self.pending.is_none() => self.cash_out_crash(),
702 Key::Char('+') | Key::Char('=') if !running => {
703 let _ = self.game.adjust_bet(10);
704 self.board_effects()
705 }
706 Key::Char('-') if !running => {
707 let _ = self.game.adjust_bet(-10);
708 self.board_effects()
709 }
710 _ => Vec::new(),
711 }
712 }
713
714 fn start_crash(&mut self) -> Vec<Effect> {
715 let status = self.game.crash_status();
716 if !matches!(status.as_str(), "ready" | "cashed" | "crashed" | "forfeit") {
717 return Vec::new();
718 }
719 let Some(request) = self.game.spin_request() else {
720 return Vec::new();
721 };
722 if let Some(balance) = self.balance {
723 let bet = self
724 .game
725 .get_current_state()
726 .map(|state| state.bet_amount)
727 .unwrap_or(0);
728 if bet as i64 > balance {
729 self.game.set_error("Insufficient balance");
730 return self.board_effects();
731 }
732 }
733
734 self.game.set_crash_status("starting");
735 self.pending = Some(Pending::CrashStart);
736 let mut effects = self.board_effects();
737 effects.push(Effect::SendLine(request));
738 effects
739 }
740
741 fn cash_out_crash(&mut self) -> Vec<Effect> {
742 let Some(session) = self.game.crash_session_id() else {
743 return Vec::new();
744 };
745 self.pending = Some(Pending::CrashCashout);
746 vec![Effect::SendLine(format!("CRASH_CASHOUT {session}"))]
747 }
748
562 fn submit(&mut self) -> Vec<Effect> { 749 fn submit(&mut self) -> Vec<Effect> {
563 let line = self.input.trim().to_string(); 750 let line = self.input.trim().to_string();
564 self.input.clear(); 751 self.input.clear();
@@ -616,6 +803,7 @@ impl ClientCore {
616 self.connected = false; 803 self.connected = false;
617 self.logged_in = None; 804 self.logged_in = None;
618 self.pending = None; 805 self.pending = None;
806 self.crash_started = None;
619 self.game.end_game(); 807 self.game.end_game();
620 vec![ 808 vec![
621 Effect::ClearRegion, 809 Effect::ClearRegion,