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.

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