initial commit - basic TUI blackjack game

This commit is contained in:
Nick Pegg 2025-07-04 14:15:56 -07:00
commit 0a72da768e
9 changed files with 738 additions and 0 deletions

93
src/main.rs Normal file
View file

@ -0,0 +1,93 @@
use blackjack::card::Card;
use blackjack::game::{Game, PlayResult, PlayerChoice};
use blackjack::hand::Hand;
use std::io;
use std::io::prelude::*;
fn main() {
interactive_play();
}
fn interactive_play() {
let mut bank: u64 = 1_000;
let mut game = Game::new().with_decks(6);
let mut last_bet: Option<u32> = None;
loop {
println!("\nMoney in the bank: {bank}");
// Bet checking loop
let mut bet: u32;
loop {
if last_bet.is_some() {
print!("Your bet [{}]? ", last_bet.unwrap());
io::stdout().flush().unwrap();
let input = read_input();
if input == "" {
bet = last_bet.unwrap();
} else {
bet = input.parse().unwrap();
}
} else {
print!("Your bet? ");
io::stdout().flush().unwrap();
bet = read_input().parse().unwrap();
}
if bet as u64 <= bank {
break;
} else {
println!("You don't have enough money!\n");
}
}
bank -= bet as u64;
last_bet = Some(bet);
println!();
let result = game.play(bet, interactive_decision);
let dealer_hand = Hand::from(result.dealer_cards);
let player_hand = Hand::from(result.player_cards);
println!("Dealer's hand: {} = {}", dealer_hand, dealer_hand.value());
println!("Your hand: {} = {}", player_hand, player_hand.value());
match result.result {
PlayResult::Win => println!("You won!"),
PlayResult::Blackjack => println!("Blackjack!"),
PlayResult::Lose => println!("You lost"),
PlayResult::Push => println!("Push"),
PlayResult::DealerBlackjack => println!("Dealer got blackjack"),
PlayResult::Bust => println!("You busted"),
}
bank += result.player_winnings;
}
}
fn interactive_decision(hand: &Hand, dealer_showing: &Card) -> PlayerChoice {
println!("\nDealer showing: {dealer_showing}");
println!("Your hand: {hand}\n");
if hand.value() == 21 {
println!("You have 21, standing.");
return PlayerChoice::Stand;
}
let choice: PlayerChoice;
loop {
print!("(h)it or (s)tand? ");
io::stdout().flush().unwrap();
choice = match read_input().to_lowercase().as_ref() {
"h" => PlayerChoice::Hit,
"s" => PlayerChoice::Stand,
_ => continue,
};
break;
}
choice
}
fn read_input() -> String {
let mut buf = String::new();
io::stdin().read_line(&mut buf).unwrap();
buf.trim().to_owned()
}