|
| 1 | +use std::ops::AddAssign; |
| 2 | + |
| 3 | +use crate::group::Fight; |
| 4 | +use crate::group::Group; |
| 5 | + |
| 6 | +#[derive(Debug, Clone)] |
| 7 | +pub struct Army { |
| 8 | + name: String, |
| 9 | + groups: Vec<Group>, |
| 10 | +} |
| 11 | + |
| 12 | +impl Army { |
| 13 | + #[must_use] |
| 14 | + pub fn new() -> Self { |
| 15 | + Self { |
| 16 | + name: String::new(), |
| 17 | + groups: vec![], |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +impl Default for Army { |
| 23 | + fn default() -> Self { |
| 24 | + Self::new() |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl std::str::FromStr for Army { |
| 29 | + type Err = Box<dyn std::error::Error>; |
| 30 | + |
| 31 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 32 | + let mut a = Army::new(); |
| 33 | + let mut id = 0; |
| 34 | + |
| 35 | + for line in s.lines() { |
| 36 | + if let Some(line) = line.strip_suffix(':') { |
| 37 | + a.name = line.to_string(); |
| 38 | + } else { |
| 39 | + let mut g: Group = line.parse()?; |
| 40 | + id.add_assign(1); |
| 41 | + g.set_id(&a.name, id); |
| 42 | + a.groups.push(g); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + Ok(a) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +impl Army { |
| 51 | + pub fn set_boost(&mut self, boost: u32) { |
| 52 | + for group in &mut self.groups { |
| 53 | + group.set_boost(boost); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + #[must_use] |
| 58 | + pub fn is_alive(&self) -> bool { |
| 59 | + self.groups.iter().any(Group::is_alive) |
| 60 | + } |
| 61 | + |
| 62 | + #[must_use] |
| 63 | + pub fn alive_units(&self) -> u32 { |
| 64 | + self.groups.iter().map(Group::alive_units).sum() |
| 65 | + } |
| 66 | + |
| 67 | + #[must_use] |
| 68 | + pub fn select_fights<'a>(&'a self, other: &'a Army) -> Vec<Fight<'a>> { |
| 69 | + let mut fights: Vec<Fight<'a>> = vec![]; |
| 70 | + |
| 71 | + let mut attackers = self.alive_groups(); |
| 72 | + let mut targets = other.alive_groups(); |
| 73 | + |
| 74 | + // sort by effective power then initiative |
| 75 | + attackers.sort_unstable(); |
| 76 | + |
| 77 | + for attacker in &attackers { |
| 78 | + if let Some(i) = attacker.select_target(&targets) { |
| 79 | + fights.push(Fight { |
| 80 | + attacker, |
| 81 | + opponent: targets[i], |
| 82 | + }); |
| 83 | + |
| 84 | + targets.remove(i); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + fights |
| 89 | + } |
| 90 | + |
| 91 | + #[must_use] |
| 92 | + pub fn alive_groups(&self) -> Vec<&Group> { |
| 93 | + self.groups.iter().filter(|g| g.is_alive()).collect() |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +impl std::fmt::Display for Army { |
| 98 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 99 | + for g in &self.groups { |
| 100 | + writeln!(f, "{g}")?; |
| 101 | + } |
| 102 | + Ok(()) |
| 103 | + } |
| 104 | +} |
0 commit comments