Struct GridEngine

Source
pub struct GridEngine { /* private fields */ }
Expand description

The main engine for managing a 2D grid system.

GridEngine provides functionality for:

  • Adding items to specific grid positions
  • Moving items while handling collisions
  • Removing items from the grid
  • Tracking changes through an event system
  • Expand the grid dynamically on the y axis

When items collide during placement or movement, the engine automatically repositions affected items to prevent overlapping, the default is to move the collided items down, increasing their y axis.

Implementations§

Source§

impl GridEngine

Source

pub fn new(rows: usize, cols: usize) -> GridEngine

Creates a new GridEngine with specified dimensions.

§Arguments
  • rows - Initial number of rows in the grid
  • cols - Initial number of columns in the grid
§Example
use grid_engine::grid_engine::GridEngine;

let grid = GridEngine::new(10, 10); // Creates a 10x10 grid
Examples found in repository?
examples/managing_grid.rs (line 56)
53fn main() {
54    println!("Grid App");
55
56    let mut grid = GridEngine::new(10, 12);
57
58    grid.events_mut().add_changes_listener(Box::new(|event| {
59        println!("Event triggered: {:#?}", event);
60    }));
61
62    grid.add_item("a".to_string(), 2, 2, 2, 4).unwrap();
63    print_grid(&grid);
64    grid.add_item("b".to_string(), 4, 2, 2, 4).unwrap();
65    print_grid(&grid);
66    grid.add_item("c".to_string(), 0, 2, 2, 2).unwrap();
67    print_grid(&grid);
68    grid.remove_item("b").unwrap();
69    print_grid(&grid);
70    grid.move_item("a", 1, 0).unwrap();
71    print_grid(&grid);
72}
Source

pub fn get_nodes(&self) -> Vec<Node>

Get the nodes sorted by id

§Example
use grid_engine::grid_engine::GridEngine;

let mut grid = GridEngine::new(10, 10);
grid.add_item("b".to_string(), 0, 0, 2, 2).unwrap();
grid.add_item("a".to_string(), 0, 2, 2, 2).unwrap();

let nodes = grid.get_nodes();
assert_eq!(nodes.len(), 2);
assert_eq!(nodes[0].id(), "a");
assert_eq!(nodes[1].id(), "b");
Source

pub fn get_inner_grid(&self) -> &InnerGrid

Gets a reference to the underlying grid structure.

This provides access to the raw grid data for inspection purposes. Note that modifications should be made through GridEngine’s public methods rather than directly manipulating the inner grid.

§Returns

A reference to the InnerGrid instance

§Example
use grid_engine::grid_engine::GridEngine;
use std::error::Error;

let grid = GridEngine::new(10, 10);
let inner_grid = grid.get_inner_grid();
assert_eq!(inner_grid.rows(), 10);
assert_eq!(inner_grid.cols(), 10);
Examples found in repository?
examples/managing_grid.rs (line 25)
22fn print_grid(grid: &GridEngine) {
23    let mut grid_str_formatted = String::new();
24    grid_str_formatted.push_str("  ");
25    for i in 0..grid.get_inner_grid().cols() {
26        grid_str_formatted.push_str(&format!(" {} ", i));
27    }
28    grid_str_formatted.push('\n');
29
30    grid.get_inner_grid()
31        .iter_rows()
32        .enumerate()
33        .for_each(|(row_number, row)| {
34            row.enumerate().for_each(|(index, cell)| {
35                if index == 0 {
36                    grid_str_formatted.push_str(&format!("{:0>2}", row_number));
37                }
38                match cell {
39                    Some(item) => {
40                        grid_str_formatted.push_str(&format!("[{}]", item));
41                    }
42                    None => {
43                        grid_str_formatted.push_str(&format!("[{}]", " "));
44                    }
45                };
46            });
47            grid_str_formatted.push('\n');
48        });
49
50    println!("{}", grid_str_formatted);
51}
Source

pub fn add_item( &mut self, id: String, x: usize, y: usize, w: usize, h: usize, ) -> Result<&Node, GridEngineError>

Adds an item to the grid at the specified position.

If the new item would collide with existing items, those items are automatically repositioned to avoid overlap.

§Arguments
  • id - Unique identifier for the item
  • x - X coordinate (column) for item placement
  • y - Y coordinate (row) for item placement
  • w - Width of the item in grid cells
  • h - Height of the item in grid cells
§Returns
  • Ok(&Node) - Reference to the newly added node
  • Err(GridEngineError) - If item already exists or placement fails
§Example
use grid_engine::grid_engine::GridEngine;
use std::error::Error;

let mut grid = GridEngine::new(10, 10);
grid.add_item("box1".to_string(), 0, 0, 2, 2)?; // 2x2 item at top-left

// Check if the item was added correctly
let item = grid.get_nodes();
assert_eq!(item.len(), 1);
assert_eq!(item[0].id(), "box1");
Examples found in repository?
examples/managing_grid.rs (line 62)
53fn main() {
54    println!("Grid App");
55
56    let mut grid = GridEngine::new(10, 12);
57
58    grid.events_mut().add_changes_listener(Box::new(|event| {
59        println!("Event triggered: {:#?}", event);
60    }));
61
62    grid.add_item("a".to_string(), 2, 2, 2, 4).unwrap();
63    print_grid(&grid);
64    grid.add_item("b".to_string(), 4, 2, 2, 4).unwrap();
65    print_grid(&grid);
66    grid.add_item("c".to_string(), 0, 2, 2, 2).unwrap();
67    print_grid(&grid);
68    grid.remove_item("b").unwrap();
69    print_grid(&grid);
70    grid.move_item("a", 1, 0).unwrap();
71    print_grid(&grid);
72}
Source

pub fn remove_item(&mut self, id: &str) -> Result<Node, GridEngineError>

Removes an item from the grid by its ID.

§Arguments
  • id - ID of the item to remove
§Returns
  • Ok(Node) - The removed node
  • Err(GridEngineError) - If item doesn’t exist
§Example
use grid_engine::grid_engine::GridEngine;
use std::error::Error;


let mut grid = GridEngine::new(10, 10);
grid.add_item("box1".to_string(), 0, 0, 2, 2)?;
grid.remove_item("box1")?; // Removes the item
Examples found in repository?
examples/managing_grid.rs (line 68)
53fn main() {
54    println!("Grid App");
55
56    let mut grid = GridEngine::new(10, 12);
57
58    grid.events_mut().add_changes_listener(Box::new(|event| {
59        println!("Event triggered: {:#?}", event);
60    }));
61
62    grid.add_item("a".to_string(), 2, 2, 2, 4).unwrap();
63    print_grid(&grid);
64    grid.add_item("b".to_string(), 4, 2, 2, 4).unwrap();
65    print_grid(&grid);
66    grid.add_item("c".to_string(), 0, 2, 2, 2).unwrap();
67    print_grid(&grid);
68    grid.remove_item("b").unwrap();
69    print_grid(&grid);
70    grid.move_item("a", 1, 0).unwrap();
71    print_grid(&grid);
72}
Source

pub fn move_item( &mut self, id: &str, new_x: usize, new_y: usize, ) -> Result<(), GridEngineError>

Moves an existing item to a new position in the grid.

If the move would cause collisions, affected items are automatically repositioned to prevent overlap.

§Arguments
  • id - ID of the item to move
  • new_x - New X coordinate
  • new_y - New Y coordinate
§Returns
  • Ok(()) - If move successful
  • Err(GridEngineError) - If item doesn’t exist or move invalid
§Example
use grid_engine::grid_engine::GridEngine;


let mut grid = GridEngine::new(10, 10);
grid.add_item("box1".to_string(), 0, 0, 2, 2)?;
grid.move_item("box1", 2, 2)?; // Moves box to position 2,2

// Check if the item was moved correctly
let item = grid.get_nodes();
assert_eq!(item.len(), 1);
assert_eq!(item[0].x(), &2);
assert_eq!(item[0].y(), &2);

Examples found in repository?
examples/managing_grid.rs (line 70)
53fn main() {
54    println!("Grid App");
55
56    let mut grid = GridEngine::new(10, 12);
57
58    grid.events_mut().add_changes_listener(Box::new(|event| {
59        println!("Event triggered: {:#?}", event);
60    }));
61
62    grid.add_item("a".to_string(), 2, 2, 2, 4).unwrap();
63    print_grid(&grid);
64    grid.add_item("b".to_string(), 4, 2, 2, 4).unwrap();
65    print_grid(&grid);
66    grid.add_item("c".to_string(), 0, 2, 2, 2).unwrap();
67    print_grid(&grid);
68    grid.remove_item("b").unwrap();
69    print_grid(&grid);
70    grid.move_item("a", 1, 0).unwrap();
71    print_grid(&grid);
72}
Source

pub fn events(&self) -> &GridEvents

Returns a reference to the grid events system.

Source

pub fn events_mut(&mut self) -> &mut GridEvents

Returns a mutable reference to the grid events system.

Examples found in repository?
examples/managing_grid.rs (line 58)
53fn main() {
54    println!("Grid App");
55
56    let mut grid = GridEngine::new(10, 12);
57
58    grid.events_mut().add_changes_listener(Box::new(|event| {
59        println!("Event triggered: {:#?}", event);
60    }));
61
62    grid.add_item("a".to_string(), 2, 2, 2, 4).unwrap();
63    print_grid(&grid);
64    grid.add_item("b".to_string(), 4, 2, 2, 4).unwrap();
65    print_grid(&grid);
66    grid.add_item("c".to_string(), 0, 2, 2, 2).unwrap();
67    print_grid(&grid);
68    grid.remove_item("b").unwrap();
69    print_grid(&grid);
70    grid.move_item("a", 1, 0).unwrap();
71    print_grid(&grid);
72}

Trait Implementations§

Source§

impl Debug for GridEngine

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.