4
|
1 |
use core::fmt; |
|
2 |
|
5
|
3 |
/// This is the implementation of a Card. |
|
4 |
/// Smart card! ;-) Can do a few things by herself. |
|
5 |
|
4
|
6 |
#[derive(Debug)] |
5
|
7 |
/// A playing Card. Knows its face `value` |
|
8 |
/// and the punishment `points` (in the game |
|
9 |
/// these are symbolised by little bull heads). |
4
|
10 |
pub struct Card { |
|
11 |
pub value: i8, |
|
12 |
pub points: i8, |
|
13 |
} |
|
14 |
|
|
15 |
impl Card { |
5
|
16 |
/// Generate a new card with the face `value` parameter. |
|
17 |
/// Calculates the `points` for the value. |
4
|
18 |
pub fn new(value: i8)->Self { |
|
19 |
|
|
20 |
let mut points = 0; |
|
21 |
if value % 10 == 5 { |
|
22 |
// ends with 5 = 2 point |
|
23 |
points = 2; |
|
24 |
// println!("*5 add 1, val={}, pt={}", value, points); |
|
25 |
} |
|
26 |
|
|
27 |
if value % 10 == 0 { |
|
28 |
// ends with 0 = 3 point |
|
29 |
points = 3; |
|
30 |
// println!("*0 add 2, val={}, pt={}", value, points); |
|
31 |
} |
|
32 |
|
|
33 |
if value % 10 == value / 10 { |
5
|
34 |
// same numbers = 5 points (11,22,33... but 55=7) |
4
|
35 |
points += 5; |
|
36 |
// println!("NN add 5, val={}, pt={}", value, points); |
|
37 |
} |
|
38 |
|
|
39 |
if points == 0 { |
5
|
40 |
// rest of the cards are 1 point |
4
|
41 |
points = 1; |
|
42 |
} |
|
43 |
|
5
|
44 |
// Return a Card |
4
|
45 |
Card { |
|
46 |
value, |
|
47 |
points, |
|
48 |
} |
|
49 |
} |
|
50 |
} |
|
51 |
|
|
52 |
impl fmt::Display for Card { |
5
|
53 |
/// Print formatter for a card, so it can be written in `println!()` |
4
|
54 |
fn fmt( &self, f: &mut fmt::Formatter ) -> fmt::Result { |
|
55 |
write!(f, "(Card {}, points {})", self.value, self.points) |
|
56 |
} |
|
57 |
} |
|
58 |
|
|
59 |
impl PartialEq for Card { |
5
|
60 |
/// This is used for sorting cards. |
4
|
61 |
fn eq(&self, other: &Self) -> bool { |
|
62 |
self.value == other.value |
|
63 |
} |
|
64 |
} |
|
65 |
|
5
|
66 |
/// This is used for sorting cards. Eq is required some by some strict sorting methods. |
4
|
67 |
impl Eq for Card {} |
|
68 |
|
|
69 |
impl PartialOrd for Card { |
5
|
70 |
/// This is used for sorting cards. |
4
|
71 |
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
|
72 |
match self.value.partial_cmp(&other.value) { |
|
73 |
Some(core::cmp::Ordering::Equal) => {None} |
|
74 |
ord => return ord, |
|
75 |
} |
|
76 |
} |
|
77 |
} |
|
78 |
|
5
|
79 |
/// This is used for sorting cards. Ord (and Eq) is required some by some strict sorting methods. |
4
|
80 |
impl Ord for Card { |
|
81 |
fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
|
82 |
self.value.cmp(&other.value) |
|
83 |
} |
|
84 |
} |