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.

193 lines
5.1 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
  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: 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. .collect(),
  72. }),
  73. )
  74. })
  75. .collect();
  76. let mut new_state = WorldState {
  77. agent_positions: HashMap::with_capacity(self.state.agent_positions.len()),
  78. tagged: self.state.tagged,
  79. tagged_by: self.state.tagged_by,
  80. };
  81. for (id, mv) in moves {
  82. if self.validating {
  83. self.check_move(id, &mv);
  84. }
  85. let mut new_pos = None;
  86. let pos = self.state.agent_positions.get(&id).unwrap();
  87. match mv {
  88. Move::Noop => {}
  89. Move::TryTag(other_id) => {
  90. new_state.tagged = other_id;
  91. new_state.tagged_by = Some(id);
  92. }
  93. Move::TryMove(dir) => {
  94. new_pos = Some((pos.x + dir.x, pos.y + dir.y).into());
  95. }
  96. }
  97. new_state
  98. .agent_positions
  99. .insert(id, new_pos.unwrap_or_else(|| pos.clone()));
  100. }
  101. self.state = new_state;
  102. }
  103. fn check_move(&self, id: AgentId, mv: &Move) {
  104. match mv {
  105. Move::Noop => {}
  106. Move::TryTag(other_id) => {
  107. let my_pos = self.state.agent_positions.get(&id).unwrap();
  108. let other_pos = self.state.agent_positions.get(&other_id).unwrap();
  109. assert!((my_pos.x - other_pos.x).abs() <= 1);
  110. assert!((my_pos.y - other_pos.y).abs() <= 1);
  111. assert_eq!(self.state.tagged, id);
  112. assert_ne!(self.state.tagged_by, Some(*other_id));
  113. assert!(
  114. self.agents.contains_key(&other_id),
  115. "Trying to tag a nonexisting agent"
  116. );
  117. }
  118. Move::TryMove(dir) => {
  119. assert!(dir.x.abs() <= 1);
  120. assert!(dir.y.abs() <= 1);
  121. let pos = self.state.agent_positions.get(&id).unwrap();
  122. let size = &self.size;
  123. assert!(pos.x + dir.x > 0);
  124. assert!(pos.x + dir.x < size.x);
  125. assert!(pos.y + dir.y > 0);
  126. assert!(pos.y + dir.y < size.y);
  127. }
  128. }
  129. }
  130. }
  131. #[cfg(test)]
  132. mod test {
  133. use crate::agent::{Move, NullAgent, Position, ScriptedAgent};
  134. use crate::world::ActualWorld;
  135. #[test]
  136. #[should_panic]
  137. fn empty() {
  138. ActualWorld::new(Position { x: 0, y: 0 }, vec![], true);
  139. }
  140. #[test]
  141. fn trivial() {
  142. let mut world = ActualWorld::new(
  143. Position { x: 0, y: 0 },
  144. vec![(Position { x: 0, y: 0 }, Box::new(NullAgent))],
  145. true,
  146. );
  147. world.do_step();
  148. assert_eq!(world.state.tagged, 0);
  149. assert_eq!(world.state.tagged_by, None);
  150. }
  151. #[test]
  152. fn scripted_tagging() {
  153. let mut world = ActualWorld::new(
  154. Position { x: 0, y: 0 },
  155. vec![
  156. (
  157. Position { x: 0, y: 0 },
  158. Box::new(ScriptedAgent::new(vec![Move::Noop])),
  159. ),
  160. (
  161. Position { x: 0, y: 0 },
  162. Box::new(ScriptedAgent::new(vec![Move::TryTag(0)])),
  163. ),
  164. ],
  165. true,
  166. );
  167. world.do_step();
  168. assert_eq!(world.state.tagged, 0);
  169. assert_eq!(world.state.tagged_by, Some(1));
  170. }
  171. #[test]
  172. #[should_panic]
  173. fn move_out_of_bounds() {
  174. let mut world = ActualWorld::new(
  175. Position { x: 1, y: 1 },
  176. vec![(
  177. Position { x: 0, y: 0 },
  178. Box::new(ScriptedAgent::new(vec![Move::TryMove((-1, -1).into())])),
  179. )],
  180. true,
  181. );
  182. world.do_step();
  183. }
  184. }