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
|
use super::traits::{Game, GameError, GamePhase, GameResult, GameState};
use crate::blackjack::{
card_value, fresh_shoe, hand_total, is_blackjack, BlackjackState,
};
use rand::seq::SliceRandom;
use rand::thread_rng;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
pub struct BlackjackGame {
fixed_deck: Option<Vec<String>>,
}
impl BlackjackGame {
pub fn new() -> Self {
Self { fixed_deck: None }
}
pub fn with_deck(deck: Vec<String>) -> Self {
Self {
fixed_deck: Some(deck),
}
}
fn shoe(&self) -> Vec<String> {
if let Some(deck) = &self.fixed_deck {
return deck.clone();
}
let mut shoe = fresh_shoe();
shoe.shuffle(&mut thread_rng());
shoe
}
pub fn deal(&self, bet: u64) -> BlackjackHand {
let mut hand = BlackjackHand::new(self.shoe(), bet);
if is_blackjack(&hand.player) || is_blackjack(&hand.dealer) {
hand.settle();
}
hand
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlackjackHand {
pub shoe: Vec<String>,
pub player: Vec<String>,
pub dealer: Vec<String>,
pub phase: String,
pub base_bet: u64,
pub bet: u64,
pub result: String,
pub winnings: u64,
}
impl BlackjackHand {
fn new(shoe: Vec<String>, bet: u64) -> Self {
let mut hand = Self {
shoe,
player: Vec::new(),
dealer: Vec::new(),
phase: "player".to_string(),
base_bet: bet,
bet,
result: "playing".to_string(),
winnings: 0,
};
let card = hand.draw();
hand.player.push(card);
let card = hand.draw();
hand.dealer.push(card);
let card = hand.draw();
hand.player.push(card);
let card = hand.draw();
hand.dealer.push(card);
hand
}
fn draw(&mut self) -> String {
self.shoe.remove(0)
}
pub fn player_total(&self) -> u8 {
hand_total(&self.player)
}
pub fn dealer_total(&self) -> u8 {
hand_total(&self.dealer)
}
pub fn is_done(&self) -> bool {
self.phase == "done"
}
pub fn hit(&mut self) -> Result<(), String> {
if self.is_done() {
return Err("Hand is over".to_string());
}
let card = self.draw();
self.player.push(card);
let total = self.player_total();
if total > 21 {
self.settle();
} else if total == 21 {
self.dealer_play();
self.settle();
}
Ok(())
}
pub fn stand(&mut self) {
if self.is_done() {
return;
}
self.dealer_play();
self.settle();
}
/// Caller must debit the extra `base_bet` before calling this.
pub fn double(&mut self) -> Result<(), String> {
if self.is_done() {
return Err("Hand is over".to_string());
}
if self.player.len() != 2 {
return Err("Double is only allowed on the first two cards".to_string());
}
self.bet = self.bet.saturating_add(self.base_bet);
let card = self.draw();
self.player.push(card);
self.dealer_play();
self.settle();
Ok(())
}
pub fn cancel(&mut self) {
self.phase = "done".to_string();
self.result = "cancelled".to_string();
self.winnings = 0;
}
fn dealer_play(&mut self) {
while self.dealer_total() < 17 {
let card = self.draw();
self.dealer.push(card);
}
}
fn settle(&mut self) {
if self.is_done() {
return;
}
self.phase = "done".to_string();
let player = self.player_total();
let dealer = self.dealer_total();
let player_blackjack = is_blackjack(&self.player);
let dealer_blackjack = is_blackjack(&self.dealer);
self.result = if player > 21 {
"bust".to_string()
} else if player_blackjack && !dealer_blackjack {
"blackjack".to_string()
} else if dealer_blackjack && !player_blackjack {
"lose".to_string()
} else if dealer > 21 {
"win".to_string()
} else if player == dealer {
"push".to_string()
} else if player > dealer {
"win".to_string()
} else {
"lose".to_string()
};
self.winnings = match self.result.as_str() {
"push" => self.bet,
"blackjack" => self.bet + (self.bet * 3) / 2,
"win" => self.bet * 2,
_ => 0,
};
}
pub fn state(&self, session_id: &str, balance: i64) -> BlackjackState {
let player_total = self.player_total();
let (dealer, dealer_total, actions) = if self.is_done() {
(self.dealer.clone(), self.dealer_total(), Vec::new())
} else {
let visible = self
.dealer
.first()
.map(|card| card_value(card))
.unwrap_or(0);
let mut actions = vec!["hit".to_string(), "stand".to_string()];
if self.player.len() == 2 {
actions.push("double".to_string());
}
(
vec![
self.dealer.first().cloned().unwrap_or_default(),
"?".to_string(),
],
visible,
actions,
)
};
BlackjackState {
session_id: session_id.to_string(),
phase: self.phase.clone(),
player: self.player.clone(),
dealer,
player_total,
dealer_total,
bet: self.bet,
base_bet: self.base_bet,
balance,
actions,
result: self.result.clone(),
winnings: self.winnings,
}
}
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
pub fn from_json(raw: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(raw)
}
}
impl Game for BlackjackGame {
fn game_type(&self) -> &'static str {
"blackjack"
}
fn get_name(&self) -> &'static str {
"Blackjack"
}
fn get_description(&self) -> &'static str {
"Blackjack: hit, stand or double. Dealer stands on all 17s."
}
fn prepare_state(&self, _username: &str, bet_amount: u64) -> GameState {
let mut data = HashMap::new();
data.insert("status".to_string(), "ready".to_string());
GameState {
session_id: String::new(),
game_type: "blackjack".to_string(),
bet_amount,
phase: GamePhase::WaitingToStart,
data,
}
}
fn process_action(
&self,
_state: &GameState,
_action: &str,
_params: &[&str],
) -> Result<GameState, GameError> {
Err(GameError::InvalidAction(
"Blackjack uses BLACKJACK_ACTION".to_string(),
))
}
fn calculate_result(&self, _state: &GameState) -> Result<GameResult, GameError> {
Err(GameError::InternalError(
"Blackjack settles through BLACKJACK_ACTION".to_string(),
))
}
}
|