nil-core 0.6.7

Multiplayer strategy game
Documentation
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// Copyright (C) Call of Nil contributors
// SPDX-License-Identifier: AGPL-3.0-only

#[cfg(test)]
mod tests;

pub mod army;
pub mod maneuver;
pub mod squad;
pub mod unit;

use crate::continent::coord::Coord;
use crate::continent::index::{ContinentIndex, ContinentKey};
use crate::continent::size::ContinentSize;
use crate::error::{Error, Result};
use crate::military::army::personnel::ArmyPersonnel;
use crate::military::army::{Army, ArmyId, collapse_armies};
use crate::military::maneuver::{Maneuver, ManeuverId};
use crate::military::squad::Squad;
use crate::military::unit::stats::power::{AttackPower, DefensePower, Power};
use crate::ranking::score::Score;
use crate::resources::maintenance::Maintenance;
use crate::ruler::Ruler;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
pub struct Military {
  continent: HashMap<ContinentIndex, Vec<Army>>,
  continent_size: ContinentSize,
  maneuvers: HashMap<ManeuverId, Maneuver>,
}

impl Military {
  pub(crate) fn new(size: ContinentSize) -> Self {
    Self {
      continent: HashMap::new(),
      continent_size: size,
      maneuvers: HashMap::new(),
    }
  }

  pub(crate) fn spawn<K, R>(&mut self, key: K, owner: R, personnel: ArmyPersonnel)
  where
    K: ContinentKey,
    R: Into<Ruler>,
  {
    let ruler: Ruler = owner.into();
    let army = Army::builder()
      .owner(ruler)
      .personnel(personnel)
      .build();

    let index = key.into_index(self.continent_size);
    self
      .continent
      .entry(index)
      .or_default()
      .push(army);

    self.collapse_armies_in(index);
  }

  pub fn collapse_armies(&mut self) {
    self
      .continent
      .values_mut()
      .for_each(collapse_armies);

    self
      .continent
      .retain(|_, armies| !armies.is_empty());
  }

  pub fn collapse_armies_in<K>(&mut self, key: K)
  where
    K: ContinentKey,
  {
    let index = key.into_index(self.continent_size);
    if let Some(armies) = self.continent.get_mut(&index) {
      collapse_armies(armies);
    }
  }

  /// Creates a new instance containing only entries related to a given set of coords.
  pub fn intersection<K, I>(&self, keys: I) -> Result<Self>
  where
    K: ContinentKey,
    I: IntoIterator<Item = K>,
  {
    let mut military = Self::new(self.continent_size);
    for key in keys {
      let coord = key.into_coord(self.continent_size)?;
      let index = coord.into_index(self.continent_size);
      if let Some(armies) = self.continent.get(&index).cloned() {
        military.continent.insert(index, armies);
      }

      let maneuvers = self
        .maneuvers_at(coord)
        .map(|maneuver| (maneuver.id(), maneuver.clone()));

      military.maneuvers.extend(maneuvers);
    }

    Ok(military)
  }

  pub(crate) fn remove_army(&mut self, id: ArmyId) -> Result<Army> {
    let (curr_vec, pos) = self
      .continent
      .values_mut()
      .find_map(|armies| {
        armies
          .iter()
          .position(|army| army.id() == id)
          .map(|pos| (armies, pos))
      })
      .ok_or(Error::ArmyNotFound(id))?;

    Ok(curr_vec.swap_remove(pos))
  }

  pub(crate) fn remove_armies<I>(&mut self, armies: I) -> Result<Vec<Army>>
  where
    I: IntoIterator<Item = ArmyId>,
  {
    armies
      .into_iter()
      .map(|id| self.remove_army(id))
      .try_collect()
  }

  pub(crate) fn relocate_army<K>(&mut self, id: ArmyId, new_key: K) -> Result<()>
  where
    K: ContinentKey,
  {
    let army = self.remove_army(id)?;
    let index = new_key.into_index(self.continent_size);
    self
      .continent
      .entry(index)
      .or_default()
      .push(army);

    self.collapse_armies_in(index);

    Ok(())
  }

  pub fn continent(&self) -> impl Iterator<Item = (ContinentIndex, &[Army])> {
    self
      .continent
      .iter()
      .map(|(index, armies)| (*index, armies.as_slice()))
  }

  pub fn army(&self, id: ArmyId) -> Result<&Army> {
    self
      .armies()
      .find(|army| army.id() == id)
      .ok_or(Error::ArmyNotFound(id))
  }

  pub(crate) fn army_mut(&mut self, id: ArmyId) -> Result<&mut Army> {
    self
      .armies_mut()
      .find(|army| army.id() == id)
      .ok_or(Error::ArmyNotFound(id))
  }

  pub fn armies(&self) -> impl Iterator<Item = &Army> {
    self.continent.values().flatten()
  }

  pub(crate) fn armies_mut(&mut self) -> impl Iterator<Item = &mut Army> {
    self.continent.values_mut().flatten()
  }

  pub fn armies_at<K>(&self, key: K) -> &[Army]
  where
    K: ContinentKey,
  {
    let index = key.into_index(self.continent_size);
    self
      .continent
      .get(&index)
      .map(Vec::as_slice)
      .unwrap_or_default()
  }

  pub(crate) fn armies_mut_at<K>(&mut self, key: K) -> &mut [Army]
  where
    K: ContinentKey,
  {
    let index = key.into_index(self.continent_size);
    self
      .continent
      .get_mut(&index)
      .map(Vec::as_mut_slice)
      .unwrap_or_default()
  }

  pub fn armies_of<R>(&self, owner: R) -> impl Iterator<Item = &Army>
  where
    R: Into<Ruler>,
  {
    let owner: Ruler = owner.into();
    self
      .continent
      .values()
      .flatten()
      .filter(move |army| army.is_owned_by(&owner))
  }

  pub fn indexed_armies_of<R>(&self, owner: R) -> Vec<(ContinentIndex, &Army)>
  where
    R: Into<Ruler>,
  {
    let owner: Ruler = owner.into();
    let mut owner_armies = Vec::new();

    for (index, armies) in &self.continent {
      for army in armies {
        if army.is_owned_by(&owner) {
          owner_armies.push((*index, army));
        }
      }
    }

    owner_armies.sort_by_key(|(index, _)| *index);
    owner_armies
  }

  #[inline]
  pub fn count_armies(&self) -> usize {
    self.armies().count()
  }

  pub fn count_armies_at<K>(&self, key: K) -> usize
  where
    K: ContinentKey,
  {
    self.armies_at(key).iter().count()
  }

  pub fn idle_armies_at<K>(&self, key: K) -> impl Iterator<Item = &Army>
  where
    K: ContinentKey,
  {
    self
      .armies_at(key)
      .iter()
      .filter(|army| army.is_idle())
  }

  pub(crate) fn idle_armies_mut_at<K>(&mut self, key: K) -> impl Iterator<Item = &mut Army>
  where
    K: ContinentKey,
  {
    self
      .armies_mut_at(key)
      .iter_mut()
      .filter(|army| army.is_idle())
  }

  #[inline]
  pub fn personnel(&self, id: ArmyId) -> Result<&ArmyPersonnel> {
    self.army(id).map(Army::personnel)
  }

  pub fn personnel_at<K>(&self, key: K) -> impl Iterator<Item = &ArmyPersonnel>
  where
    K: ContinentKey,
  {
    self
      .armies_at(key)
      .iter()
      .map(Army::personnel)
  }

  pub fn fold_personnel_at<K>(&self, key: K) -> ArmyPersonnel
  where
    K: ContinentKey,
  {
    self.personnel_at(key).sum()
  }

  pub fn personnel_of<R>(&self, owner: R) -> impl Iterator<Item = &ArmyPersonnel>
  where
    R: Into<Ruler>,
  {
    self.armies_of(owner).map(Army::personnel)
  }

  pub fn fold_personnel_of<R>(&self, owner: R) -> ArmyPersonnel
  where
    R: Into<Ruler>,
  {
    self.personnel_of(owner).sum()
  }

  pub fn idle_personnel_at<K>(&self, key: K) -> impl Iterator<Item = &ArmyPersonnel>
  where
    K: ContinentKey,
  {
    self.idle_armies_at(key).map(Army::personnel)
  }

  pub fn fold_idle_personnel_at<K>(&self, key: K) -> ArmyPersonnel
  where
    K: ContinentKey,
  {
    self.idle_personnel_at(key).sum()
  }

  #[inline]
  pub fn squads(&self, id: ArmyId) -> Result<Vec<Squad>> {
    self
      .personnel(id)
      .cloned()
      .map(ArmyPersonnel::to_vec)
  }

  pub fn idle_squads_at<K>(&self, key: K) -> Vec<Squad>
  where
    K: ContinentKey,
  {
    self.fold_idle_personnel_at(key).to_vec()
  }

  #[inline]
  pub fn maneuver(&self, id: ManeuverId) -> Result<&Maneuver> {
    self
      .maneuvers
      .get(&id)
      .ok_or(Error::ManeuverNotFound(id))
  }

  fn maneuver_mut(&mut self, id: ManeuverId) -> Result<&mut Maneuver> {
    self
      .maneuvers
      .get_mut(&id)
      .ok_or(Error::ManeuverNotFound(id))
  }

  pub fn maneuvers(&self) -> impl Iterator<Item = &Maneuver> {
    self.maneuvers.values()
  }

  /// Find all maneuvers whose origin or destination matches the specified coord.
  pub fn maneuvers_at(&self, coord: Coord) -> impl Iterator<Item = &Maneuver> {
    self
      .maneuvers()
      .filter(move |maneuver| maneuver.matches_coord(coord))
  }

  #[inline]
  pub fn has_maneuver(&self, id: ManeuverId) -> bool {
    self.maneuvers.contains_key(&id)
  }

  pub(crate) fn insert_maneuver(&mut self, maneuver: Maneuver) {
    self
      .maneuvers
      .insert(maneuver.id(), maneuver);
  }

  pub(crate) fn advance_maneuvers(&mut self) -> Result<Vec<Maneuver>> {
    let mut done = Vec::new();
    for (id, maneuver) in &mut self.maneuvers {
      maneuver.advance()?;

      if maneuver.is_done() {
        done.push(*id);
      }
    }

    let done = done
      .into_iter()
      .filter_map(|id| self.maneuvers.remove(&id))
      .collect_vec();

    self.maneuvers.shrink_to_fit();

    Ok(done)
  }

  pub(crate) fn cancel_maneuver(&mut self, id: ManeuverId) -> Result<()> {
    self.maneuver_mut(id)?.cancel()
  }

  /// Retains only the maneuvers specified by the predicate.
  pub(crate) fn retain_maneuvers<F>(&mut self, f: F)
  where
    F: Fn(&Maneuver) -> bool,
  {
    self
      .maneuvers
      .retain(|_, maneuver| f(maneuver));
  }

  pub fn score_of<R>(&self, owner: R) -> Score
  where
    R: Into<Ruler>,
  {
    self.armies_of(owner).sum()
  }

  pub fn maintenance_of<R>(&self, owner: R) -> Maintenance
  where
    R: Into<Ruler>,
  {
    self.armies_of(owner).sum()
  }

  pub fn power_of<R>(&self, owner: R) -> Power
  where
    R: Into<Ruler>,
  {
    self.armies_of(owner).sum()
  }

  pub fn attack_of<R>(&self, owner: R) -> AttackPower
  where
    R: Into<Ruler>,
  {
    self.armies_of(owner).sum()
  }

  pub fn defense_of<R>(&self, owner: R) -> DefensePower
  where
    R: Into<Ruler>,
  {
    self.armies_of(owner).sum()
  }
}