A simple actor-based simulation of tag, implemented in rust.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

192 lines
5.0 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. use crate::agent::{Agent, AgentId, Direction, Move, Position, WorldView};
  2. use std::collections::hash_map::HashMap;
  3. pub struct ActualWorld {
  4. size: Position,
  5. pub agents: HashMap<AgentId, Box<dyn Agent>>,
  6. pub state: WorldState,
  7. validating: bool,
  8. }
  9. pub struct WorldState {
  10. pub agent_positions: HashMap<AgentId, Position>,
  11. pub tagged: AgentId,
  12. pub tagged_by: Option<AgentId>,
  13. }
  14. impl ActualWorld {
  15. /// Agents receive incrementing ids starting with 0
  16. /// The last agent is 'It'
  17. pub fn new(
  18. size: Position,
  19. input_agents: Vec<(Position, Box<dyn Agent>)>,
  20. validating: bool,
  21. ) -> Self {
  22. let agent_count = input_agents.len();
  23. assert!(agent_count > 0);
  24. let mut id = 0;
  25. let mut agent_positions = HashMap::with_capacity(agent_count);
  26. let mut agents = HashMap::with_capacity(agent_count);
  27. for (pos, agent) in input_agents.into_iter() {
  28. agent_positions.insert(id, pos);
  29. agents.insert(id, agent);
  30. id += 1;
  31. }
  32. let state = WorldState {
  33. tagged_by: None,
  34. tagged: id - 1,
  35. agent_positions,
  36. };
  37. Self {
  38. size,
  39. agents,
  40. state,
  41. validating,
  42. }
  43. }
  44. pub fn do_step(&mut self) {
  45. let moves: Vec<_> = self
  46. .agents
  47. .iter()
  48. .map(|(id, agent)| {
  49. let pos = self.state.agent_positions.get(id).unwrap();
  50. (
  51. *id,
  52. agent.next_move(WorldView {
  53. self_id: *id,
  54. tagged_by: self.state.tagged_by,
  55. tagged: self.state.tagged,
  56. bounds_distance: (pos.y, self.size.x - pos.x, self.size.y - pos.y, pos.x),
  57. other_agents: &mut self
  58. .state
  59. .agent_positions
  60. .iter()
  61. .filter(|(other_id, _)| id != *other_id)
  62. .map(|(id, other_pos)| {
  63. (
  64. Direction {
  65. x: other_pos.x - pos.x,
  66. y: other_pos.y - pos.y,
  67. },
  68. *id,
  69. )
  70. }),
  71. }),
  72. )
  73. })
  74. .collect();
  75. let mut new_state = WorldState {
  76. agent_positions: HashMap::with_capacity(self.state.agent_positions.len()),
  77. tagged: self.state.tagged,
  78. tagged_by: self.state.tagged_by,
  79. };
  80. for (id, mv) in moves {
  81. if self.validating {
  82. self.check_move(id, &mv);
  83. }
  84. let mut new_pos = None;
  85. let pos = self.state.agent_positions.get(&id).unwrap();
  86. match mv {
  87. Move::Noop => {}
  88. Move::TryTag(other_id) => {
  89. new_state.tagged = other_id;
  90. new_state.tagged_by = Some(id);
  91. }
  92. Move::TryMove(dir) => {
  93. new_pos = Some((pos.x + dir.x, pos.y + dir.y).into());
  94. }
  95. }
  96. new_state
  97. .agent_positions
  98. .insert(id, new_pos.unwrap_or_else(|| pos.clone()));
  99. }
  100. self.state = new_state;
  101. }
  102. fn check_move(&self, id: AgentId, mv: &Move) {
  103. match mv {
  104. Move::Noop => {}
  105. Move::TryTag(other_id) => {
  106. let my_pos = self.state.agent_positions.get(&id).unwrap();
  107. let other_pos = self.state.agent_positions.get(&other_id).unwrap();
  108. assert!((my_pos.x - other_pos.x).abs() <= 1);
  109. assert!((my_pos.y - other_pos.y).abs() <= 1);
  110. assert_eq!(self.state.tagged, id);
  111. assert_ne!(self.state.tagged_by, Some(*other_id));
  112. assert!(
  113. self.agents.contains_key(&other_id),
  114. "Trying to tag a nonexisting agent"
  115. );
  116. }
  117. Move::TryMove(dir) => {
  118. assert!(dir.x.abs() <= 1);
  119. assert!(dir.y.abs() <= 1);
  120. let pos = self.state.agent_positions.get(&id).unwrap();
  121. let size = &self.size;
  122. assert!(pos.x + dir.x > 0);
  123. assert!(pos.x + dir.x < size.x);
  124. assert!(pos.y + dir.y > 0);
  125. assert!(pos.y + dir.y < size.y);
  126. }
  127. }
  128. }
  129. }
  130. #[cfg(test)]
  131. mod test {
  132. use crate::agent::{Move, NullAgent, Position, ScriptedAgent};
  133. use crate::world::ActualWorld;
  134. #[test]
  135. #[should_panic]
  136. fn empty() {
  137. ActualWorld::new(Position { x: 0, y: 0 }, vec![], true);
  138. }
  139. #[test]
  140. fn trivial() {
  141. let mut world = ActualWorld::new(
  142. Position { x: 0, y: 0 },
  143. vec![(Position { x: 0, y: 0 }, Box::new(NullAgent))],
  144. true,
  145. );
  146. world.do_step();
  147. assert_eq!(world.state.tagged, 0);
  148. assert_eq!(world.state.tagged_by, None);
  149. }
  150. #[test]
  151. fn scripted_tagging() {
  152. let mut world = ActualWorld::new(
  153. Position { x: 0, y: 0 },
  154. vec![
  155. (
  156. Position { x: 0, y: 0 },
  157. Box::new(ScriptedAgent::new(vec![Move::Noop])),
  158. ),
  159. (
  160. Position { x: 0, y: 0 },
  161. Box::new(ScriptedAgent::new(vec![Move::TryTag(0)])),
  162. ),
  163. ],
  164. true,
  165. );
  166. world.do_step();
  167. assert_eq!(world.state.tagged, 0);
  168. assert_eq!(world.state.tagged_by, Some(1));
  169. }
  170. #[test]
  171. #[should_panic]
  172. fn move_out_of_bounds() {
  173. let mut world = ActualWorld::new(
  174. Position { x: 1, y: 1 },
  175. vec![(
  176. Position { x: 0, y: 0 },
  177. Box::new(ScriptedAgent::new(vec![Move::TryMove((-1, -1).into())])),
  178. )],
  179. true,
  180. );
  181. world.do_step();
  182. }
  183. }