Created Hand Type #13

Merged
wesley merged 1 commits from feature/hand into development 2026-01-11 16:25:37 -05:00
3 changed files with 127 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
use std::fmt;
use super::card::Card;
pub struct Hand {
cards: Vec<Card>,
is_dealer: bool,
show_all: bool,
}
impl Hand {
pub fn new(is_dealer: bool) -> Self {
let cards: Vec<Card> = Vec::new();
Self {
cards: cards,
is_dealer: is_dealer,
show_all: !is_dealer,
}
}
pub fn sum(&self) -> u8 {
let mut num_aces = 0;
let mut sum: u8 = 0;
if self.is_dealer && !self.show_all {
if self.cards[1].value + 1 > 10 {
return 10;
} else if self.cards[1].value + 1 == 1 {
return 11;
}
return self.cards[1].value + 1;
}
for card in 0..self.cards.len() {
match self.cards[card].value + 1 {
1 => {
sum += 11;
num_aces += 1;
}
2..=9 => sum += self.cards[card].value + 1,
10..=13 => sum += 10,
_ => sum += 0,
}
}
while num_aces > 0 && sum > 21 {
num_aces -= 1;
sum -= 10;
}
sum
}
pub fn get_new_card(&mut self, new_card: Card) {
self.cards.push(new_card);
}
pub fn set_show_all(&mut self, show_all: bool) {
if self.is_dealer {
self.show_all = show_all;
}
}
}
impl fmt::Display for Hand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut display_string = String::new();
if self.show_all {
for card in 0..self.cards.len() {
display_string.push_str(&self.cards[card].to_string());
display_string.push_str(" ");
}
} else {
display_string.push_str("** ");
display_string.push_str(&self.cards[1].to_string());
display_string.push_str(" ");
}
write!(f, "{}", display_string)
}
}

View File

@@ -1,6 +1,9 @@
use std::error::Error; use std::error::Error;
mod card; mod card;
pub use card::Card;
mod deck; mod deck;
pub use deck::Deck; pub use deck::Deck;
@@ -8,6 +11,8 @@ pub use deck::Deck;
mod gamestate; mod gamestate;
mod hand; mod hand;
pub use hand::Hand;
pub fn run() -> Result<(), Box<dyn Error>> { pub fn run() -> Result<(), Box<dyn Error>> {
println!("Hello, world!"); println!("Hello, world!");

40
tests/hand_tests.rs Normal file
View File

@@ -0,0 +1,40 @@
use blackjack::Card;
use blackjack::Hand;
const ACE_HEARTS: Card = Card { suit: 0, value: 0 };
const ACE_SPADES: Card = Card { suit: 3, value: 0 };
const KING_HEARTS: Card = Card { suit: 0, value: 12 };
const KING_SPADES: Card = Card { suit: 3, value: 12 };
#[test]
fn test_double_ace() {
let mut hand = Hand::new(false);
hand.get_new_card(ACE_HEARTS);
hand.get_new_card(ACE_SPADES);
assert_eq!(12, hand.sum());
}
#[test]
fn double_ace_double_face() {
let mut hand = Hand::new(false);
hand.get_new_card(ACE_HEARTS);
hand.get_new_card(ACE_SPADES);
hand.get_new_card(KING_HEARTS);
hand.get_new_card(KING_SPADES);
assert_eq!(22, hand.sum());
}
#[test]
fn show_all_is_dealer() {
let mut hand = Hand::new(true);
hand.get_new_card(ACE_HEARTS);
hand.get_new_card(KING_SPADES);
assert_eq!(10, hand.sum());
hand.set_show_all(true);
assert_eq!(21, hand.sum());
}