summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: d1014f960adeff37d0e29256146cd84a24553615 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use std::{collections::HashMap, fmt::Display};

use rand::{seq::SliceRandom, thread_rng};

const MIN_CARD: u8 = 1;
const MAX_CARD: u8 = 104;

fn main() {
    let mut players = Vec::from([
        Player {
            name: String::from("Curie"),
            value_function: |card, line| line.push_cost(card).unwrap_or_default(),
            hand: Default::default(),
            score: 0,
        },
        Player {
            name: String::from("Joe"),
            value_function: |card, line| line.push_cost(card).unwrap_or_default(),
            hand: Default::default(),
            score: 0,
        },
        Player {
            name: String::from("Jim"),
            value_function: |card, line| line.push_cost(card).unwrap_or_default(),
            hand: Default::default(),
            score: 0,
        },
        Player {
            name: String::from("Jill"),
            value_function: |card, line| line.push_cost(card).unwrap_or_default(),
            hand: Default::default(),
            score: 0,
        },
    ]);

    let mut n = 0;
    while players.iter().all(|p| p.score < 66) {
        n += 1;
        round(&mut players);

        println!("Round {n}");
        println!("Name   Score");
        for player in &mut *players {
            println!("{:<6} {:02}", player.name, player.score);
        }
    }
}

fn round(players: &mut [Player]) {
    let mut cards: Vec<u8> = (MIN_CARD..MAX_CARD).collect();
    cards.shuffle(&mut thread_rng());
    let deck = &mut cards.iter();

    let mut state = deck
        .take(5)
        .copied()
        .enumerate()
        .map(Line::from)
        .collect::<Vec<Line>>();

    for player in &mut *players {
        player.set_hand(deck.take(10).copied().collect());
        println!("{}: {:?}", player.name, player.hand);
    }

    for (i, line) in state.iter().enumerate() {
        println!("Line {i}: {line}");
    }

    while !players.iter().any(|p| p.hand.is_empty()) {
        let cards: Vec<u8> = players.iter_mut().map(|p| p.evaluate(&state)).collect();
        let mut played: Vec<(&mut Player, u8)> = players.iter_mut().zip(cards).collect();

        played.sort_by_key(|p| p.1);

        let mut actions = vec![HashMap::new(); state.len()];
        let mut player_names = Vec::new();
        print!("{:37}", "Table");

        for (player, card) in played {
            print!("{:>10}", player.name);
            player_names.push(&player.name);

            let line = state
                .iter_mut()
                .min_by_key(|line| (player.value_function)(card, line))
                .unwrap();

            actions[line.id].insert(&player.name, card);

            if let Some(score) = line.push(card) {
                player.score += score;
            }
        }

        println!();
        for (line, actions) in state.iter().zip(actions) {
            let cards: String = line
                .cards
                .iter()
                .fold(String::new(), |buf, c| format!("{buf}[{c:>3}]"));

            print!("Line {cards:<32}");
            for name in &player_names {
                let card = actions
                    .get(name)
                    .map(|c| format!("[{c:>3}]"))
                    .unwrap_or("".to_string());
                print!("{:>10}", card);
            }

            println!();
        }
    }
}

#[derive(Debug, Default)]
struct Line {
    id: usize,
    cards: Vec<u8>,
}

impl Line {
    fn head(&self) -> &u8 {
        self.cards.last().unwrap()
    }

    fn count(&self) -> u8 {
        self.cards.len().try_into().unwrap()
    }

    fn push(&mut self, card: u8) -> Option<u8> {
        let cost = self.push_cost(card);
        if cost.is_some() {
            self.cards.clear();
        }

        self.cards.push(card);

        cost
    }

    fn push_cost(&self, card: u8) -> Option<u8> {
        (self.count() >= 5 || card <= *self.head()).then_some(self.count())
    }
}

impl Display for Line {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: ", self.id)?;
        self.cards
            .iter()
            .try_for_each(|card| write!(f, "[{card:03}]"))
    }
}

impl From<(usize, u8)> for Line {
    fn from((id, value): (usize, u8)) -> Self {
        Self {
            id,
            cards: Vec::from([value]),
        }
    }
}

struct Player {
    name: String,
    value_function: fn(card: u8, line: &Line) -> u8,
    hand: Vec<u8>,
    score: u8,
}

impl Player {
    fn set_hand(&mut self, mut hand: Vec<u8>) {
        hand.sort();
        self.hand = hand
    }

    fn evaluate(&mut self, state: &[Line]) -> u8 {
        let value_function = self.value_function;
        let mut cards = HashMap::new();

        for card in &self.hand {
            let mut valid_play_found = false;
            for line in state {
                if line.head() < card {
                    valid_play_found = true
                } else if valid_play_found {
                    continue;
                }

                let value = value_function(*card, line);
                cards
                    .entry(card)
                    .and_modify(|o| {
                        *o = value.max(*o);
                    })
                    .or_insert(value);
            }
        }

        cards
            .iter()
            .max_by_key(|e| e.1)
            .and_then(|e| self.hand.iter().position(|c| c == *e.0))
            .map(|index| self.hand.remove(index))
            .unwrap()
    }
}