add fn add_agent(), temporary mutable access privileges in Word

This commit is contained in:
vova-rs committed 2026-05-15 16:06:03 +03:00
1 parent 63f2ba31d0
commit f9842f635b
2 files changed
+49 -4

No files matched your search

+4 -1
View File
@@ -1,7 +1,7 @@
#[derive(Clone)]
pub struct Agent{ pub struct Agent{
pos: (i32, i32), pos: (i32, i32),
ang: i8, ang: i8,
@@ -35,4 +35,7 @@ impl Agent {
pub fn rotate(&mut self, a: i8){ pub fn rotate(&mut self, a: i8){
self.ang = ((self.ang + a) % 4 + 4) % 4; self.ang = ((self.ang + a) % 4 + 4) % 4;
} }
pub fn get_pos(&self) -> (i32, i32) {
self.pos.clone()
}
} }
+45 -3
View File
@@ -1,9 +1,51 @@
mod grid; mod grid;
use grid::TorusGrid; use std::sync::{Arc, Mutex};
pub use grid::TorusGrid;
mod agent; mod agent;
use agent::Agent; pub use agent::Agent;
pub struct World{ pub struct World{
grid: TorusGrid<bool>,
agents: Vec<Arc<Mutex<Agent>>>,
a_grid: TorusGrid<Option<Arc<Mutex<Agent>>>>,
size: (usize, usize),
} }
impl World {
pub fn new(s: (usize, usize)) -> Self {
World {
grid: TorusGrid::new(false, s),
agents: Vec::new(),
a_grid: TorusGrid::new(None, s),
size: s,
}
}
pub fn get_size(&self) -> (usize, usize){
self.size.clone()
}
pub fn add_agent(&mut self, ag: Agent) -> Result<(), &str> {
let pos = ag.get_pos();
let p = self.a_grid.get_mut_wrap(pos);
// if *p != None {
// return Err("w");
// }
if p.is_some() {
return Err("ERROR: pos занято");
}
self.agents.push(Arc::new(Mutex::new(ag)));
*p = Some(Arc::clone(&self.agents[self.agents.len() -1]));
Ok(())
}
pub fn get_grid(&self) -> &TorusGrid<bool>{
&self.grid
}
pub fn get_mut_grid(&mut self) -> &mut TorusGrid<bool>{
&mut self.grid
}
pub fn get_a_grid(&self) -> &TorusGrid<Option<Arc<Mutex<Agent>>>>{
&self.a_grid
}
}