Author SHA1 Message Date
lemon-cat a02b40c043 relese global intention 2026-05-27 12:48:31 +03:00
lemon-cat 60bd764bcf add vec gloval_it and push in this 2026-05-27 11:22:25 +03:00
lemon-cat 93b0c65fed relase local inteintoon 2026-05-26 13:37:05 +03:00
lemon-cat d4cfb25c8d add local itention for agent 2026-05-26 13:01:56 +03:00
vova-rs c6b1b68572 intention is dote 2026-05-26 12:28:00 +03:00
vova-rs 580894ed0a m_container: is done 2026-05-22 12:37:41 +03:00
vova-rs 25af75b381 refactor add_agent 2026-05-15 17:33:20 +03:00
10 changed files with 263 additions and 319 deletions

No files matched your search

+3 -2
View File
@@ -4,5 +4,6 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
crossterm = "0.29" smallvec = "1.15"
rand = "0.8"
-117
View File
@@ -1,117 +0,0 @@
use std::sync::{Arc, Mutex};
use std::{
error,
fmt::format,
io::{Stdout, Write, stdout},
process::Output,
};
use crossterm::{
cursor::MoveTo,
execute, queue,
style::{Color, Print, ResetColor, SetBackgroundColor, SetForegroundColor},
terminal::{Clear, ClearType, enable_raw_mode},
};
use super::Agent;
use super::TorusGrid;
pub enum PosCom {
UP,
DW,
LF,
RH,
}
pub struct Render {
out: Stdout,
rez: (usize, usize),
pos: (i32, i32),
}
impl Render {
pub fn new() -> Self {
Render {
out: stdout(),
rez: (10, 10),
pos: (0, 0),
}
}
pub fn set_rez(&mut self, a: usize, b: usize) -> Result<(), String> {
if a == 0 || b == 0 {
return Err("Invalid resolution\n".to_string());
}
self.rez = (a, b);
Ok(())
}
pub fn set_pos(&mut self, a: i32, b: i32) {
self.pos = (a, b);
}
pub fn offset_pos(&mut self, a: PosCom) {
match a {
PosCom::LF => {
self.pos.1 -= 1;
}
PosCom::UP => {
self.pos.0 -= 1;
}
PosCom::DW => {
self.pos.0 += 1;
}
PosCom::RH => {
self.pos.1 += 1;
}
}
}
pub fn clear(&mut self) {
_ = execute!(self.out, Clear(ClearType::All), MoveTo(0, 0));
}
pub fn print(&mut self, out_str: &str) {
_ = execute!(self.out, Print(out_str));
}
pub fn print_c(&mut self, out_str: &str, c: Color) {
_ = execute!(self.out, SetForegroundColor(c), Print(out_str), ResetColor);
}
pub fn print_err(&mut self, out_err: &str) {
_ = execute!(
self.out,
SetForegroundColor(Color::Red),
Print(out_err),
ResetColor
);
}
pub fn frame(&mut self, grid: &TorusGrid<bool>, a_grid: &TorusGrid<Option<Arc<Mutex<Agent>>>>) {
let mut out = self.out.lock();
_ = queue!(out, MoveTo(0, 0));
for i in 0..self.rez.0 {
for j in 0..self.rez.1 {
let ca: Color;
let cg: Color;
let a = a_grid.get_wrap((i as i32 + self.pos.0, j as i32 + self.pos.1));
let g = grid.get_wrap((i as i32 + self.pos.0, j as i32 + self.pos.1));
let c = *g as u8 * 200;
cg = Color::Rgb { r: c, g: c, b: c };
if a.is_some() {
//c = Color::Red;
ca = Color::Red;
} else {
ca = cg;
}
_ = queue!(
out,
SetBackgroundColor(cg),
SetForegroundColor(ca),
Print("#"),
ResetColor
);
}
_ = queue!(out, Print("\r\n"));
}
_ = out.flush();
self.print_c(
&format!("pos is: {} {} \n", self.pos.1, self.pos.0),
Color::Yellow,
);
}
}
-83
View File
@@ -1,83 +0,0 @@
use core::error;
use crossterm::{
event::{self, Event, KeyCode},
terminal::{disable_raw_mode, enable_raw_mode},
};
use std::io::{self, Write, stdout};
use crate::input;
pub enum ComandEvent {
//who is this
None,
Exit,
Key,
}
pub fn Comand_pars() -> Result<ComandEvent, String> {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("error input scan\n");
let mut words: Vec<&str> = input.trim().split(" ").collect();
if words.len() == 0 {
return Err(String::from("Zerro lenth comand\n"));
}
match words[0] {
"q" => {
return Ok(ComandEvent::Exit);
}
"key" => {
_ = enable_raw_mode();
let mut out = stdout();
_ = crossterm::execute!(out, crossterm::cursor::Hide);
return Ok(ComandEvent::Key);
}
_ => {}
}
Ok(ComandEvent::None)
}
pub enum KeyEvent {
//KeuEvent for your input
None,
Exit,
Comand,
A,
W,
S,
D,
}
pub fn Key_pars() -> Result<Option<KeyEvent>, std::io::Error> {
if let Event::Key(key) = event::read()? {
match key.code {
KeyCode::Char('q') => {
_ = disable_raw_mode();
let mut out = stdout();
_ = crossterm::execute!(out, crossterm::cursor::Show);
return Ok(Some(KeyEvent::Exit));
}
KeyCode::Char('c') => {
_ = disable_raw_mode();
let mut out = stdout();
_ = crossterm::execute!(out, crossterm::cursor::Show);
return Ok(Some(KeyEvent::Comand));
}
KeyCode::Char('a') => {
return Ok(Some(KeyEvent::A));
}
KeyCode::Char('w') => {
return Ok(Some(KeyEvent::W));
}
KeyCode::Char('s') => {
return Ok(Some(KeyEvent::S));
}
KeyCode::Char('d') => {
return Ok(Some(KeyEvent::D));
}
_ => {}
}
}
Ok(Some(KeyEvent::None))
}
+32 -91
View File
@@ -1,102 +1,43 @@
use std::{clone, sync::atomic::AtomicI32};
use rand::Rng;
mod world; mod world;
pub use world::*; use world::*;
mod input;
use input::*;
mod console_render;
use console_render::*;
enum InputType {
comand,
keybard,
}
fn main() { fn main() {
let mut rnd = rand::thread_rng(); println!("Hello, dev!");
let mut it = InputType::comand;
let mut R = Render::new();
R.clear();
_ = R.set_rez(40, 80);
let rez: (usize, usize) = (100, 100); let mut ma: MagicContainer<i32> = MagicContainer::new();
let mut w = world::World::new(rez);
for i in 0..rez.0 { ma.add(2);
for j in 0..rez.1 { ma.add(3);
if let Some(a) = w.get_mut_grid().get_mut((i as i32, j as i32)) { ma.add(4);
*a = rnd.gen_range(0..=1) == 1; ma.add(5);
} ma.add(6);
}
ma.debug_log();
if let Err(a) = ma.rm(1) {
println!("ERROR: {:?}", a);
return;
} }
for mut i in 0..20 { ma.debug_log();
let x = rnd.gen_range(0..=rez.0) as i32;
let y = rnd.gen_range(0..=rez.1) as i32; if let Err(a) = ma.rm(0) {
let a = w.add_agent(world::Agent::new(x, y, 0)); println!("ERROR: {:?}", a);
if a.is_err() { return;
R.print_err(a.err().unwrap());
i -= 1;
}
} }
loop { ma.debug_log();
//R.clear();
R.frame(w.get_grid(), w.get_a_grid());
match it { ma.add(8);
InputType::comand => {
R.print("Input your comand: "); ma.debug_log();
let input = Comand_pars();
if input.is_err() { ma.add(9);
R.print_err(&format!("ERROR: {}\n", input.err().unwrap())); ma.add(10);
} else { ma.add(11);
match input.unwrap() {
ComandEvent::Exit => { ma.debug_log();
R.print("progarm is end\n");
return;
}
ComandEvent::Key => {
R.print("jamp to keybard\n");
it = InputType::keybard
}
_ => {}
}
}
}
InputType::keybard => {
let input = Key_pars();
if input.is_err() {
R.print_err(&format!("ERROR: {}", input.err().unwrap()));
} else {
if let Some(k) = input.unwrap() {
match k {
KeyEvent::Exit => {
R.print("progarm is end\n");
return;
}
KeyEvent::Comand => {
R.print("jamp to comand");
it = InputType::comand
}
KeyEvent::A => {
R.offset_pos(PosCom::LF);
}
KeyEvent::W => {
R.offset_pos(PosCom::UP);
}
KeyEvent::S => {
R.offset_pos(PosCom::DW);
}
KeyEvent::D => {
R.offset_pos(PosCom::RH);
}
_ => {}
}
}
}
}
}
}
} }
Binary file not shown.
+7 -17
View File
@@ -1,5 +1,5 @@
const dir: [(i32, i32); 4] = [(1, 0), (0, 1), (-1, 0), (0, -1)];
#[derive(Clone)] #[derive(Clone)]
pub struct Agent{ pub struct Agent{
@@ -15,22 +15,12 @@ impl Agent {
ang: a, ang: a,
} }
} }
pub fn wolk_a(&mut self){ pub fn wolk_a(&self) -> (i32, i32){
match self.ang { let a = dir[self.ang as usize].clone();
0 => { (a.0 + self.pos.0, a.1 + self.pos.1)
self.pos.0 += 1; }
} pub fn move_to(&mut self, pos: (i32, i32)){
1 => { self.pos = pos;
self.pos.1 += 1;
}
2 => {
self.pos.0 -= 1;
}
3 => {
self.pos.1 -= 1;
}
_ => {}
}
} }
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;
File renamed without changes.
+21
View File
@@ -0,0 +1,21 @@
// use super::Agent;
// use super::{MagicContainer, MCError};
// use super::TorusGrid;
#[derive(PartialEq, Clone)]
pub enum Intention {
MoveTo,
StakedOut,
}
#[derive(PartialEq, Clone)]
pub enum LocalItentoin {
Rotate(i8),
SwapCell((i32, i32)),
}
#[derive(PartialEq, Clone)]
pub struct LinkIntention<T: Clone> {
pub it: T,
pub lin: usize,
}
+124
View File
@@ -0,0 +1,124 @@
use std::fmt::Debug;
#[derive(Debug)]
pub enum MCError {
BrocenLen,
EntityNotExisit,
}
pub struct MagicContainer<T>{
data_index: Vec<usize>,
id: Vec<usize>,
data: Vec<T>,
}
impl<T: Clone> MagicContainer<T>{
pub fn new() -> Self {
MagicContainer {
data_index: Vec::new(),
id: Vec::new(),
data: Vec::new(),
}
}
}
impl<T> MagicContainer<T> {
pub fn len(&self) -> usize {
self.data_index.len()
}
pub fn add(&mut self, value: T){
let l = self.data_index.len();
if l == self.data.len() {
self.data_index.push(l);
self.id.push(l);
self.data.push(value);
} else if l > self.data.len() {
self.data.push(value);
} else {
panic!("data_index < data");
}
}
pub fn add_and_id(&mut self, value: T) -> usize{
let l = self.data_index.len();
if l == self.data.len() {
self.data_index.push(l);
self.id.push(l);
self.data.push(value);
} else if l > self.data.len() {
self.data.push(value);
} else {
panic!("data_index < data");
}
self.id[self.data.len() -1]
}
pub fn rm(&mut self, entity_id: usize) -> Result<(), MCError>{
let index = self.data_index[entity_id];
let last = self.data.len() - 1;
if self.data.len() > self.data_index.len() {
return Err(MCError::BrocenLen);
}
if index > last {
return Err(MCError::EntityNotExisit);
}
self.id.swap(last, index);
self.data.swap(last, index);
self.data_index[self.id[index]] = index;
self.data_index[self.id[last]] = last;
self.data.pop();
Ok(())
}
pub fn get(&self, entity_id: usize) -> Option<&T> {
let index = *self.data_index.get(entity_id)?;
if index >= self.data.len() {
return None;
}
Some(&self.data[index])
}
pub fn get_mut(&mut self, entity_id: usize) -> Option<&mut T> {
let index = *self.data_index.get(entity_id)?;
if index >= self.data.len() {
return None;
}
Some(&mut self.data[index])
}
}
impl<T: Debug> MagicContainer<T>{
pub fn _debug(&self) {
println!("data_index: {:?}", self.data_index);
println!("id: {:?}", self.id);
println!("data: {:?}", self.data);
}
pub fn debug_log(&self){
println!("--- access test ---");
for id in 0..self.data_index.len() {
match self.get(id) {
Some(v) => println!("ID {} => {:?}", id, v),
None => println!("ID {} => <deleted>", id),
}
}
println!("-------------------");
}
}
impl<T> IntoIterator for MagicContainer<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.data.into_iter()
}
}
+76 -9
View File
@@ -1,3 +1,5 @@
use smallvec::{SmallVec, smallvec};
mod grid; mod grid;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -6,10 +8,16 @@ pub use grid::TorusGrid;
mod agent; mod agent;
pub use agent::Agent; pub use agent::Agent;
mod m_container;
pub use m_container::*;
mod intention;
pub use intention::*;
pub struct World { pub struct World {
grid: TorusGrid<bool>, grid: TorusGrid<bool>,
agents: Vec<Arc<Mutex<Agent>>>, agents: MagicContainer<Agent>,
a_grid: TorusGrid<Option<Arc<Mutex<Agent>>>>, a_grid: TorusGrid<Option<usize>>,
size: (usize, usize), size: (usize, usize),
} }
@@ -17,7 +25,7 @@ impl World {
pub fn new(s: (usize, usize)) -> Self { pub fn new(s: (usize, usize)) -> Self {
World { World {
grid: TorusGrid::new(false, s), grid: TorusGrid::new(false, s),
agents: Vec::new(), agents: MagicContainer::new(),
a_grid: TorusGrid::new(None, s), a_grid: TorusGrid::new(None, s),
size: s, size: s,
} }
@@ -28,14 +36,11 @@ impl World {
pub fn add_agent(&mut self, ag: Agent) -> Result<(), &str> { pub fn add_agent(&mut self, ag: Agent) -> Result<(), &str> {
let pos = ag.get_pos(); let pos = ag.get_pos();
let p = self.a_grid.get_mut_wrap(pos); let p = self.a_grid.get_mut_wrap(pos);
// if *p != None {
// return Err("w");
// }
if p.is_some() { if p.is_some() {
return Err("ERROR: pos занято"); return Err("ERROR: pos занято");
} }
self.agents.push(Arc::new(Mutex::new(ag))); let id = self.agents.add_and_id(ag);
*p = Some(Arc::clone(&self.agents[self.agents.len() - 1])); *p = Some(id);
Ok(()) Ok(())
} }
pub fn get_grid(&self) -> &TorusGrid<bool> { pub fn get_grid(&self) -> &TorusGrid<bool> {
@@ -44,7 +49,69 @@ impl World {
pub fn get_mut_grid(&mut self) -> &mut TorusGrid<bool> { pub fn get_mut_grid(&mut self) -> &mut TorusGrid<bool> {
&mut self.grid &mut self.grid
} }
pub fn get_a_grid(&self) -> &TorusGrid<Option<Arc<Mutex<Agent>>>> { pub fn get_a_grid(&self) -> &TorusGrid<Option<usize>> {
&self.a_grid &self.a_grid
} }
pub fn update(&mut self) {
let mut plane_of_intentions: TorusGrid<SmallVec<[LinkIntention<Intention>; 4]>> =
TorusGrid::new(SmallVec::new(), self.size.clone());
let mut local_it: Vec<LinkIntention<LocalItentoin>> = Vec::new();
for i in 0..self.agents.len() {
if let Some(ag) = self.agents.get(i) {
let cell = self.grid.get_wrap(ag.get_pos());
local_it.push(LinkIntention {
it: LocalItentoin::Rotate((-1 * *cell as i8) + (1 * !*cell as i8)),
lin: i,
});
local_it.push(LinkIntention {
it: LocalItentoin::SwapCell(ag.get_pos()),
lin: i,
});
}
}
for i in 0..local_it.len() {
match local_it[i].it {
LocalItentoin::Rotate(r) => {
if let Some(ag) = self.agents.get_mut(local_it[i].lin) {
ag.rotate(r);
}
}
LocalItentoin::SwapCell(cell) => {
let g = self.get_mut_grid();
if let Some(s) = g.get_mut(cell) {
*s = !*s;
}
}
}
}
for i in 0..self.agents.len() {
if let Some(ag) = self.agents.get(i) {
let pos = ag.get_pos();
let mut p = plane_of_intentions.get_mut_wrap(pos);
p.push(LinkIntention {
it: Intention::StakedOut,
lin: i,
});
let mv = ag.wolk_a();
p = plane_of_intentions.get_mut_wrap(mv);
p.push(LinkIntention {
it: Intention::MoveTo,
lin: i,
});
}
}
for i in 0..self.size.0 {
for j in 0..self.size.1 {
let cell = plane_of_intentions.get_mut_wrap((i as i32, j as i32));
if cell.len() == 1 {
if cell[0].it == Intention::MoveTo {
let ag = self.agents.get_mut(cell[0].lin).unwrap();
ag.move_to(ag.wolk_a());
}
}
}
}
}
} }