1use std::cmp::Reverse;
2use std::collections::HashMap;
3
4use super::attack_requirement::{self, AttackRequirement};
5use super::attack_restriction::{self, AttackRestrictionType};
6use super::global_attack_restrictions::GlobalAttackRestrictions;
7use super::DefenderId;
8use crate::card::Card;
9use crate::ids::{CardId, PlayerId};
10
11#[derive(Debug, Clone)]
17pub struct AttackConstraints {
18 pub possible_attackers: Vec<CardId>,
19 pub possible_defenders: Vec<DefenderId>,
20 pub global_restrictions: GlobalAttackRestrictions,
21 pub restrictions: HashMap<CardId, AttackRestriction>,
22 pub requirements: HashMap<CardId, AttackRequirement>,
23}
24
25#[derive(Debug, Clone)]
28pub struct AttackRestriction {
29 pub attacker: CardId,
30 pub types: std::collections::HashSet<AttackRestrictionType>,
31 pub cant_attack: bool,
32 pub cant_attack_defenders: Vec<DefenderId>,
33}
34
35impl AttackRestriction {
36 pub fn new(
37 attacker: CardId,
38 cards: &[Card],
39 possible_defenders: &[DefenderId],
40 game: &crate::game::GameState,
41 ) -> Self {
42 let card = &cards[attacker.index()];
43 let types = attack_restriction::get_restrictions(card);
44
45 let mut cant_attack_defenders = Vec::new();
47 for &defender in possible_defenders {
48 if !super::combat_util::can_attack_defender(game, attacker, defender) {
49 cant_attack_defenders.push(defender);
50 }
51 }
52
53 let cant_attack = types.contains(&AttackRestrictionType::Never)
55 || (types.contains(&AttackRestrictionType::OnlyAlone)
56 && (types.contains(&AttackRestrictionType::NeedGreaterPower)
57 || types.contains(&AttackRestrictionType::NeedBlackOrGreen)
58 || types.contains(&AttackRestrictionType::NotAlone)
59 || types.contains(&AttackRestrictionType::NeedTwoOthers)))
60 || cant_attack_defenders.len() == possible_defenders.len();
61
62 AttackRestriction {
63 attacker,
64 types,
65 cant_attack,
66 cant_attack_defenders,
67 }
68 }
69
70 pub fn can_attack(&self, defender: DefenderId) -> bool {
72 !self.cant_attack && !self.cant_attack_defenders.contains(&defender)
73 }
74
75 pub fn can_attack_with(
78 &self,
79 defender: DefenderId,
80 attackers: &[(CardId, DefenderId)],
81 cards: &[Card],
82 ) -> bool {
83 if !self.can_attack(defender) {
84 return false;
85 }
86 self.get_violations(attackers, cards).is_empty()
87 }
88
89 pub fn get_violations(
91 &self,
92 attackers: &[(CardId, DefenderId)],
93 cards: &[Card],
94 ) -> std::collections::HashSet<AttackRestrictionType> {
95 let mut violations = std::collections::HashSet::new();
96 let n = attackers.len();
97
98 if self.types.contains(&AttackRestrictionType::OnlyAlone) && n > 1 {
99 violations.insert(AttackRestrictionType::OnlyAlone);
100 }
101 if self.types.contains(&AttackRestrictionType::NotAlone) && n <= 1 {
102 violations.insert(AttackRestrictionType::NotAlone);
103 }
104 if self.types.contains(&AttackRestrictionType::NeedTwoOthers) && n <= 2 {
105 violations.insert(AttackRestrictionType::NeedTwoOthers);
106 }
107 if self
108 .types
109 .contains(&AttackRestrictionType::NeedGreaterPower)
110 {
111 let my_power = cards[self.attacker.index()].power();
112 let has_greater = attackers
113 .iter()
114 .any(|&(cid, _)| cid != self.attacker && cards[cid.index()].power() > my_power);
115 if !has_greater {
116 violations.insert(AttackRestrictionType::NeedGreaterPower);
117 }
118 }
119 if self
120 .types
121 .contains(&AttackRestrictionType::NeedBlackOrGreen)
122 {
123 let has_bg = attackers.iter().any(|&(cid, _)| {
124 cid != self.attacker && {
125 let c = &cards[cid.index()];
126 c.color.has_black() || c.color.has_green()
127 }
128 });
129 if !has_bg {
130 violations.insert(AttackRestrictionType::NeedBlackOrGreen);
131 }
132 }
133 violations
134 }
135
136 pub fn get_types(&self) -> &std::collections::HashSet<AttackRestrictionType> {
137 &self.types
138 }
139}
140
141#[derive(Debug, Clone)]
143struct Attack {
144 attacker: CardId,
145 defender: DefenderId,
146 requirements: i32,
147}
148
149impl AttackConstraints {
150 pub fn new(
153 game: &crate::game::GameState,
154 attacking_player: PlayerId,
155 possible_defenders: &[DefenderId],
156 ) -> Self {
157 let possible_attackers: Vec<CardId> = game
158 .creatures_on_battlefield(attacking_player)
159 .into_iter()
160 .collect();
161
162 let global_restrictions = GlobalAttackRestrictions::get_global_restrictions(
163 &game.cards,
164 attacking_player,
165 possible_defenders,
166 );
167
168 let mut restrictions = HashMap::new();
169 let mut requirements = HashMap::new();
170
171 for &attacker in &possible_attackers {
172 restrictions.insert(
173 attacker,
174 AttackRestriction::new(attacker, &game.cards, possible_defenders, game),
175 );
176 }
177
178 let reqs = attack_requirement::compute_attack_requirements_with_defenders(
179 &game.cards,
180 &possible_attackers,
181 possible_defenders,
182 );
183 for req in reqs {
184 requirements.insert(req.attacker, req);
185 }
186
187 AttackConstraints {
188 possible_attackers,
189 possible_defenders: possible_defenders.to_vec(),
190 global_restrictions,
191 restrictions,
192 requirements,
193 }
194 }
195
196 pub fn get_restrictions(&self) -> &HashMap<CardId, AttackRestriction> {
197 &self.restrictions
198 }
199
200 pub fn get_global_restrictions(&self) -> &GlobalAttackRestrictions {
201 &self.global_restrictions
202 }
203
204 pub fn get_requirements(&self) -> &HashMap<CardId, AttackRequirement> {
205 &self.requirements
206 }
207
208 pub fn get_legal_attackers(&self, cards: &[Card]) -> (Vec<(CardId, DefenderId)>, i32) {
216 let max = self
217 .global_restrictions
218 .get_max()
219 .unwrap_or(i32::MAX)
220 .min(self.possible_attackers.len() as i32);
221
222 if max == 0 {
223 return (Vec::new(), 0);
224 }
225
226 let mut reqs = self.get_sorted_filtered_requirements(cards);
228
229 reqs.retain(|a| {
231 let restriction = self.restrictions.get(&a.attacker);
232 if let Some(r) = restriction {
233 if r.cant_attack {
234 return false;
235 }
236 let types = &r.types;
237 if (types.contains(&AttackRestrictionType::NeedTwoOthers) && max <= 2)
239 || (types.contains(&AttackRestrictionType::NotAlone) && max <= 1)
240 || (types.contains(&AttackRestrictionType::NeedBlackOrGreen) && max <= 1)
241 || (types.contains(&AttackRestrictionType::NeedGreaterPower) && max <= 1)
242 {
243 return false;
244 }
245 }
246 true
247 });
248
249 let mut best_result: Option<(Vec<(CardId, DefenderId)>, i32)> = None;
251
252 for req in &reqs {
253 if let Some(r) = self.restrictions.get(&req.attacker) {
254 if r.types.contains(&AttackRestrictionType::OnlyAlone) && req.requirements > 0 {
255 let attack_map = vec![(req.attacker, req.defender)];
256 let violations = self.count_violations(&attack_map, cards);
257 if violations != -1 {
258 match &best_result {
259 None => best_result = Some((attack_map, violations)),
260 Some((_, best_v)) if violations < *best_v => {
261 best_result = Some((attack_map, violations));
262 }
263 _ => {}
264 }
265 }
266 }
267 }
268 }
269
270 reqs.retain(|a| {
272 self.restrictions
273 .get(&a.attacker)
274 .is_none_or(|r| !r.types.contains(&AttackRestrictionType::OnlyAlone))
275 });
276
277 let mut attack_map: Vec<(CardId, DefenderId)> = Vec::new();
279 let mut used: std::collections::HashSet<CardId> = std::collections::HashSet::new();
280 let mut remaining_max = max;
281
282 for req in &reqs {
283 if remaining_max <= 0 {
284 break;
285 }
286 if used.contains(&req.attacker) {
287 continue;
288 }
289 if req.requirements == 0 {
290 continue;
291 }
292
293 if let Some(&def_max) = self
295 .global_restrictions
296 .get_defender_max()
297 .get(&req.defender)
298 {
299 let count = attack_map
300 .iter()
301 .filter(|(_, d)| *d == req.defender)
302 .count() as i32;
303 if count >= def_max {
304 continue;
305 }
306 }
307
308 attack_map.push((req.attacker, req.defender));
309 used.insert(req.attacker);
310 remaining_max -= 1;
311 }
312
313 let greedy_violations = self.count_violations(&attack_map, cards);
314 if greedy_violations != -1 {
315 match &best_result {
316 None => best_result = Some((attack_map.clone(), greedy_violations)),
317 Some((_, best_v)) if greedy_violations < *best_v => {
318 best_result = Some((attack_map.clone(), greedy_violations));
319 }
320 _ => {}
321 }
322 }
323
324 let empty_violations = self.count_violations(&[], cards);
326 if empty_violations != -1 {
327 match &best_result {
328 None => best_result = Some((Vec::new(), empty_violations)),
329 Some((_, best_v)) if empty_violations < *best_v => {
330 best_result = Some((Vec::new(), empty_violations));
331 }
332 _ => {}
333 }
334 }
335
336 best_result.unwrap_or((Vec::new(), 0))
337 }
338
339 pub fn count_violations(&self, attackers: &[(CardId, DefenderId)], cards: &[Card]) -> i32 {
344 if !self.global_restrictions.is_legal(attackers) {
345 return -1;
346 }
347
348 for &(attacker_id, defender) in attackers {
350 if let Some(restriction) = self.restrictions.get(&attacker_id) {
351 if !restriction.can_attack_with(defender, attackers, cards) {
352 return -1;
353 }
354 }
355 }
356
357 let mut violations = 0;
359 for &possible_attacker in &self.possible_attackers {
360 if let Some(requirement) = self.requirements.get(&possible_attacker) {
361 let defender = attackers
362 .iter()
363 .find(|(a, _)| *a == possible_attacker)
364 .map(|(_, d)| *d);
365 violations += requirement.count_violations(defender);
366 }
367 }
368
369 violations
370 }
371
372 fn get_sorted_filtered_requirements(&self, _cards: &[Card]) -> Vec<Attack> {
375 let mut result = Vec::new();
376
377 for (&attacker_id, req) in &self.requirements {
378 let restriction = self.restrictions.get(&attacker_id);
379 let sorted_reqs = req.get_sorted_requirements();
380
381 for (defender, count) in sorted_reqs {
382 let can_attack = restriction.is_none_or(|r| r.can_attack(defender));
383 if can_attack {
384 result.push(Attack {
385 attacker: attacker_id,
386 defender,
387 requirements: count,
388 });
389 }
390 }
391 }
392
393 result.sort_by_key(|attack| Reverse(attack.requirements));
395 result
396 }
397}