Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add check to move card to a pile #5

Merged
merged 1 commit into from
Dec 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions deck/src/models/card.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ impl Card {
pub fn flip(&mut self) {
self.is_showed = !self.is_showed;
}

pub fn can_place_on_pile(&self, pile: &Vec<Card>) -> bool {
let pile_last_card = pile.last();
match pile_last_card {
Some(card) => (self.rank + 1 == card.rank) && (self.is_red() != card.is_red()),
None => self.rank == 13,
}
}

pub fn is_red(&self) -> bool {
match self.suit {
Suit::Hearts | Suit::Diamonds => true,
_ => false,
}
}
}

impl fmt::Display for Card {
Expand All @@ -45,6 +60,7 @@ impl fmt::Display for Card {
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -76,4 +92,64 @@ mod tests {
card.flip();
assert_eq!(card.is_showed, true);
}

#[test]
fn check_that_card_red() {
let must_be_red = Card::new(10, Suit::Hearts);
assert!(must_be_red.is_red());
let must_be_red = Card::new(1, Suit::Diamonds);
assert!(must_be_red.is_red());
let must_be_black = Card::new(10, Suit::Clubs);
assert_eq!(false, must_be_black.is_red());
let must_be_black = Card::new(1, Suit::Spades);
assert_eq!(false, must_be_black.is_red());
}

#[test]
fn can_place_on_pile() {
let card_to_check = Card::new(3, Suit::Hearts);
let pile = vec![Card::new(4, Suit::Spades)];

assert!(card_to_check.can_place_on_pile(&pile));
}

#[test]
fn cant_be_placed_on_pile_because_rank() {
let card_to_check = Card::new(13, Suit::Hearts);
let pile = vec![Card::new(11, Suit::Spades)];

let can_place = card_to_check.can_place_on_pile(&pile);

assert_eq!(false, can_place);
}

#[test]
fn cant_be_placed_on_pile_because_color() {
let card_to_check = Card::new(2, Suit::Spades);
let pile = vec![Card::new(3, Suit::Clubs)];

let can_place = card_to_check.can_place_on_pile(&pile);

assert_eq!(false, can_place);
}

#[test]
fn can_be_placed_on_empty_pile() {
let card_to_check = Card::new(13, Suit::Clubs);
let pile: Vec<Card> = vec![];

let can_be_placed = card_to_check.can_place_on_pile(&pile);

assert!(can_be_placed);
}

#[test]
fn cant_be_placed_on_empty_pile() {
let card_to_check = Card::new(12, Suit::Hearts);
let pile: Vec<Card> = vec![];

let can_be_placed = card_to_check.can_place_on_pile(&pile);

assert_eq!(false, can_be_placed);
}
}