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.

75 lines
1.7 KiB

3 years ago
3 years ago
3 years ago
  1. use gntag::agent::{Agent, SimpleAgent};
  2. use gntag::view::{Backend, TerminalView};
  3. use gntag::world::ActualWorld;
  4. use std::io;
  5. use std::io::Read;
  6. use std::process::exit;
  7. use std::sync::{Arc, Mutex};
  8. use std::thread;
  9. fn main() {
  10. let view = Arc::new(Mutex::new(Some(TerminalView::try_new().unwrap())));
  11. // Exit on q, ESC and Ctrl-C and reset terminal
  12. let view2 = view.clone();
  13. thread::spawn(move || {
  14. let stdin = io::stdin();
  15. for byte in stdin.bytes().flatten() {
  16. if byte == b'q' || byte == 0x1b || byte == 0x03 {
  17. if let Ok(mut view) = view2.lock() {
  18. *view = None; // drop view
  19. println!("\n");
  20. }
  21. exit(0);
  22. }
  23. }
  24. });
  25. loop {
  26. run_simulation(&view);
  27. }
  28. }
  29. fn run_simulation(view: &Arc<Mutex<Option<TerminalView<impl Backend>>>>) {
  30. let (width, height) = (*view.lock().unwrap())
  31. .as_mut()
  32. .unwrap()
  33. .content_size()
  34. .unwrap();
  35. let mut agents: Vec<(_, Box<dyn Agent>)> = vec![];
  36. for x in (0..width).step_by(10) {
  37. for y in (0..height).step_by(10) {
  38. agents.push(((x, y).into(), Box::new(SimpleAgent)));
  39. }
  40. }
  41. let mut world = ActualWorld::new((width, height).into(), agents, true);
  42. let mut gen = 0;
  43. loop {
  44. let resized = (*view.lock().unwrap())
  45. .as_mut()
  46. .unwrap()
  47. .draw(
  48. gen,
  49. world
  50. .state
  51. .agent_positions
  52. .get(&world.state.tagged)
  53. .map(|pos| (pos.x, pos.y))
  54. .unwrap(),
  55. world
  56. .state
  57. .agent_positions
  58. .iter()
  59. .map(|(_id, pos)| (pos.x, pos.y))
  60. .collect::<Vec<_>>()
  61. .as_ref(),
  62. )
  63. .unwrap();
  64. if resized {
  65. return;
  66. };
  67. world.do_step();
  68. gen += 1;
  69. }
  70. }