Skip to main content

unbanished_game/behaviour/
loiter_order.rs

1//! The original's Loiter picks, measured in a run of the original, for comparing draws past them.
2//!
3//! `Activity::Loiter` picks one of the objects near a citizen from a set that the original keys
4//! by each object's `Object::Internal` address (docs/ITERATION-ORDER.md). The port keeps the set
5//! in creation order, so the same draw can pick another object. A comparison run can give the
6//! map rectangle of each object the original picked, in order; each pick then takes the set
7//! member with that rectangle.
8//!
9//! Deviation: not in the original; a check run from the command line (`--loiter-picks`).
10
11use super::activities::MapRect;
12use std::cell::RefCell;
13use std::collections::VecDeque;
14
15thread_local! {
16    static PICKS: RefCell<Option<VecDeque<MapRect>>> = const { RefCell::new(None) };
17}
18
19/// Take the original's picks on this thread, in the order the original made them.
20pub fn set(picks: impl IntoIterator<Item = MapRect>) {
21    PICKS.with(|p| *p.borrow_mut() = Some(picks.into_iter().collect()));
22}
23
24/// The place in the set to take: the member with the original's next rectangle, or `k` (the
25/// drawn place) when no picks were given, they ran out, or no member has that rectangle.
26pub(crate) fn place(k: usize, rects: impl Iterator<Item = Option<MapRect>>) -> usize {
27    let Some(want) = PICKS.with(|p| p.borrow_mut().as_mut().and_then(VecDeque::pop_front)) else {
28        return k;
29    };
30    let mut rects = rects;
31    rects.position(|r| r == Some(want)).unwrap_or_else(|| {
32        eprintln!("no object near the citizen has the original's pick {want:?}");
33        k
34    })
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    /// With picks given, each takes the member with its rectangle in turn, then the drawn place.
42    #[test]
43    fn picks_take_the_member_with_their_rectangle() {
44        let rects = [Some((1, 1, 2, 2)), None, Some((5, 5, 1, 1))];
45        assert_eq!(place(0, rects.iter().copied()), 0);
46        set([(5, 5, 1, 1), (9, 9, 1, 1)]);
47        assert_eq!(place(0, rects.iter().copied()), 2);
48        assert_eq!(place(1, rects.iter().copied()), 1, "no member has it");
49        assert_eq!(place(1, rects.iter().copied()), 1, "the picks ran out");
50    }
51}