RosettaCodeData/Task/Playing-cards/Rust/playing-cards.rust

64 lines
1.3 KiB
Text
Raw Permalink Normal View History

2015-11-18 06:14:39 +00:00
extern crate rand;
2015-02-20 00:35:01 -05:00
2015-11-18 06:14:39 +00:00
use std::fmt;
use rand::Rng;
use Pip::*;
use Suit::*;
2015-02-20 00:35:01 -05:00
2015-11-18 06:14:39 +00:00
#[derive(Copy, Clone, Debug)]
enum Pip { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }
2015-02-20 00:35:01 -05:00
2015-11-18 06:14:39 +00:00
#[derive(Copy, Clone, Debug)]
enum Suit { Spades, Hearts, Diamonds, Clubs }
2015-02-20 00:35:01 -05:00
struct Card {
pip: Pip,
suit: Suit
}
2015-11-18 06:14:39 +00:00
impl fmt::Display for Card {
2015-02-20 00:35:01 -05:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2015-11-18 06:14:39 +00:00
write!(f, "{:?} of {:?}", self.pip, self.suit)
2015-02-20 00:35:01 -05:00
}
}
struct Deck(Vec<Card>);
impl Deck {
fn new() -> Deck {
let mut cards:Vec<Card> = Vec::with_capacity(52);
2015-11-18 06:14:39 +00:00
for &suit in &[Spades, Hearts, Diamonds, Clubs] {
for &pip in &[Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King] {
cards.push( Card{pip: pip, suit: suit} );
2015-02-20 00:35:01 -05:00
}
}
Deck(cards)
}
fn deal(&mut self) -> Option<Card> {
2015-11-18 06:14:39 +00:00
self.0.pop()
2015-02-20 00:35:01 -05:00
}
fn shuffle(&mut self) {
2015-11-18 06:14:39 +00:00
rand::thread_rng().shuffle(&mut self.0)
2015-02-20 00:35:01 -05:00
}
}
2015-11-18 06:14:39 +00:00
impl fmt::Display for Deck {
2015-02-20 00:35:01 -05:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2015-11-18 06:14:39 +00:00
for card in self.0.iter() {
writeln!(f, "{}", card);
2015-02-20 00:35:01 -05:00
}
2015-11-18 06:14:39 +00:00
write!(f, "")
}
}
2015-02-20 00:35:01 -05:00
2015-11-18 06:14:39 +00:00
fn main() {
let mut deck = Deck::new();
deck.shuffle();
//println!("{}", deck);
for _ in 0..5 {
println!("{}", deck.deal().unwrap());
2015-02-20 00:35:01 -05:00
}
}