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.

67 lines
1.7 KiB

pub mod agent;
pub mod view;
pub mod world;
use agent::{Agent, SimpleAgent};
use std::error::Error;
use std::io;
use std::io::Read;
use std::process::exit;
use std::sync::{Arc, Mutex};
use std::thread;
use view::{RawTerminal, TerminalView, TermionBackend};
use world::ActualWorld;
pub fn get_world(width: isize, height: isize, spacing: usize, validating: bool) -> ActualWorld {
let mut agents: Vec<(_, Box<dyn Agent>)> = vec![];
for x in (0..width).step_by(spacing) {
for y in (0..height).step_by(spacing) {
agents.push(((x, y).into(), Box::new(SimpleAgent)));
}
}
ActualWorld::new((width, height).into(), agents, validating)
}
pub type DefaultView = Arc<Mutex<Option<TerminalView<TermionBackend<RawTerminal<io::Stdout>>>>>>;
pub fn get_view() -> DefaultView {
let view = Arc::new(Mutex::new(Some(TerminalView::try_new().unwrap())));
// Exit on q, ESC and Ctrl-C and reset terminal
let view2 = view.clone();
thread::spawn(move || {
let stdin = io::stdin();
for byte in stdin.bytes().flatten() {
if byte == b'q' || byte == 0x1b || byte == 0x03 {
if let Ok(mut view) = view2.lock() {
*view = None; // drop view
println!("\n");
}
exit(0);
}
}
});
view
}
pub fn draw_world(
world: &ActualWorld,
gen: usize,
view: &DefaultView,
) -> Result<bool, Box<dyn Error>> {
(*view.lock().unwrap()).as_mut().unwrap().draw(
gen,
world
.state
.agent_positions
.get(&world.state.tagged)
.map(|pos| (pos.x, pos.y))
.unwrap(),
world
.state
.agent_positions
.iter()
.map(|(_id, pos)| (pos.x, pos.y))
.collect::<Vec<_>>()
.as_ref(),
)
}