|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +use crate::{ |
| 4 | + task::{Task, TaskStatus}, |
| 5 | + trick::Trick, |
| 6 | +}; |
| 7 | + |
| 8 | +#[derive(Debug)] |
| 9 | +pub struct TaskWinCardsAmountNumber { |
| 10 | + constraints: HashMap<usize, usize>, |
| 11 | + exactly: bool, |
| 12 | +} |
| 13 | + |
| 14 | +fn count_won_except_submarine(tricks: &[Trick], value: usize) -> usize { |
| 15 | + tricks.iter().fold(0, |acc, trick| { |
| 16 | + acc + trick |
| 17 | + .iter() |
| 18 | + .filter(|c| c.val() == value && !c.is_submarine()) |
| 19 | + .count() |
| 20 | + }) |
| 21 | +} |
| 22 | + |
| 23 | +impl TaskWinCardsAmountNumber { |
| 24 | + pub fn new(exactly: bool, constraints: HashMap<usize, usize>) -> Self { |
| 25 | + Self { |
| 26 | + exactly, |
| 27 | + constraints, |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + pub fn new_at_least_three_5s() -> Self { |
| 32 | + let constraints = HashMap::from([(5, 3)]); |
| 33 | + Self::new(false, constraints) |
| 34 | + } |
| 35 | + |
| 36 | + pub fn new_at_least_three_9s() -> Self { |
| 37 | + let constraints = HashMap::from([(9, 3)]); |
| 38 | + Self::new(false, constraints) |
| 39 | + } |
| 40 | + |
| 41 | + pub fn new_at_least_two_7s() -> Self { |
| 42 | + let constraints = HashMap::from([(7, 2)]); |
| 43 | + Self::new(false, constraints) |
| 44 | + } |
| 45 | + |
| 46 | + pub fn new_exactly_three_6s() -> Self { |
| 47 | + let constraints = HashMap::from([(6, 3)]); |
| 48 | + Self::new(true, constraints) |
| 49 | + } |
| 50 | + |
| 51 | + pub fn new_exactly_two_9s() -> Self { |
| 52 | + let constraints = HashMap::from([(9, 2)]); |
| 53 | + Self::new(true, constraints) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl Task for TaskWinCardsAmountNumber { |
| 58 | + fn eval(&self, state: &crate::state::State, ip: usize) -> super::TaskStatus { |
| 59 | + let mut done = true; |
| 60 | + for (&value, &amount) in &self.constraints { |
| 61 | + let won_by_ip = count_won_except_submarine(state.get_player(ip).get_tricks(), value); |
| 62 | + |
| 63 | + if self.exactly && won_by_ip > amount { |
| 64 | + return TaskStatus::Failed; |
| 65 | + } |
| 66 | + |
| 67 | + if !self.exactly && won_by_ip >= amount { |
| 68 | + continue; |
| 69 | + } |
| 70 | + |
| 71 | + let missing = amount - won_by_ip; |
| 72 | + let mut won_by_others = 0; |
| 73 | + for i in 0..state.n_players() { |
| 74 | + if i != ip { |
| 75 | + won_by_others += |
| 76 | + count_won_except_submarine(state.get_player(i).get_tricks(), value); |
| 77 | + } |
| 78 | + } |
| 79 | + let available = 4 - (won_by_ip + won_by_others); |
| 80 | + if available < missing { |
| 81 | + return TaskStatus::Failed; |
| 82 | + } |
| 83 | + done &= (self.exactly && available == 0) || (!self.exactly && won_by_ip >= amount); |
| 84 | + } |
| 85 | + |
| 86 | + if done { |
| 87 | + return TaskStatus::Done; |
| 88 | + } |
| 89 | + |
| 90 | + TaskStatus::Unknown |
| 91 | + } |
| 92 | +} |
0 commit comments