Use console for screen clearning and immediate single-char input

This commit is contained in:
Nick Pegg 2025-07-05 19:55:51 -07:00
parent 7229b32f03
commit 821d2114d5
3 changed files with 121 additions and 13 deletions

View file

@ -1,6 +1,7 @@
use blackjack::card::Card;
use blackjack::game::{Game, PlayResult, PlayerChoice};
use blackjack::hand::Hand;
use console::Term;
use std::env;
use std::fs;
use std::io;
@ -18,6 +19,7 @@ fn interactive_play() {
// TODO: Persist bank between plays
// TODO: Make a way to reset bank
//
let term = Term::stdout();
let mut bank: u32 = match load_bank() {
Some(b) => b,
None => 1_000,
@ -35,7 +37,7 @@ fn interactive_play() {
if last_bet.is_some() {
print!("Your bet [{}]? ", last_bet.unwrap());
io::stdout().flush().unwrap();
let input = read_input();
let input = term.read_line().unwrap();
if input == "" {
bet = last_bet.unwrap();
} else {
@ -47,7 +49,7 @@ fn interactive_play() {
} else {
print!("Your bet? ");
io::stdout().flush().unwrap();
match read_input().parse() {
match term.read_line().unwrap().parse() {
Ok(b) => bet = b,
Err(_) => continue,
}
@ -65,6 +67,8 @@ fn interactive_play() {
let result = game.play(&mut bank, bet, interactive_decision);
let dealer_hand = Hand::from(result.dealer_cards);
let player_hand = Hand::from(result.player_cards);
term.clear_screen().unwrap();
println!("Dealer's hand: {} = {}", dealer_hand, dealer_hand.value());
println!("Your hand: {} = {}", player_hand, player_hand.value());
@ -90,7 +94,10 @@ fn interactive_play() {
}
fn interactive_decision(hand: &Hand, dealer_showing: &Card) -> PlayerChoice {
println!("\nDealer showing: {dealer_showing}");
let term = Term::stdout();
term.clear_screen().unwrap();
println!("Dealer showing: {dealer_showing}");
println!("Your hand: {hand}\n");
if hand.value() == 21 {
@ -108,12 +115,13 @@ fn interactive_decision(hand: &Hand, dealer_showing: &Card) -> PlayerChoice {
msg += "? ";
io::stdout().write_all(msg.as_bytes()).unwrap();
io::stdout().flush().unwrap();
choice = match read_input().to_lowercase().as_ref() {
"h" => PlayerChoice::Hit,
"s" => PlayerChoice::Stand,
"d" if can_dd => PlayerChoice::DoubleDown,
choice = match term.read_char().unwrap() {
'h' => PlayerChoice::Hit,
's' => PlayerChoice::Stand,
'd' if can_dd => PlayerChoice::DoubleDown,
_ => continue,
};
println!("\n");
break;
}
choice
@ -202,12 +210,6 @@ fn old_man() {
println!("Profit/Loss: ${pl}");
}
fn read_input() -> String {
let mut buf = String::new();
io::stdin().read_line(&mut buf).unwrap();
buf.trim().to_owned()
}
fn data_dir() -> PathBuf {
env::home_dir().unwrap().join(".local/share/blackjack")
}