Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::rc::{Rc, Weak};
- use std::ops::{Index, IndexMut};
- #[derive(Debug)]
- enum GridCell {
- None,
- Wall,
- Entity(Weak<Entity>)
- }
- #[derive(Debug)]
- struct Entity {}
- struct Grid {
- size_x: usize,
- size_y: usize,
- vec: Vec<GridCell>
- }
- impl Grid {
- fn new(size_x: usize, size_y: usize) -> Grid {
- let mut vec = Vec::with_capacity(size_x * size_y);
- for _ in 0..size_x * size_y {
- vec.push(GridCell::None);
- }
- Grid {
- size_x, size_y,
- vec
- }
- }
- }
- impl Index<(usize, usize)> for Grid {
- type Output = GridCell;
- fn index(&self, index: (usize, usize)) -> &GridCell {
- let (x, y) = index;
- if x >= self.size_x || y >= self.size_y {
- panic!("out of bounds")
- } else {
- &self.vec[x*self.size_y+y]
- }
- }
- }
- impl IndexMut<(usize, usize)> for Grid {
- fn index_mut(&mut self, index: (usize, usize)) -> &mut GridCell {
- let (x, y) = index;
- if x >= self.size_x || y >= self.size_y {
- panic!("out of bounds")
- } else {
- &mut self.vec[x*self.size_y+y]
- }
- }
- }
- impl GridCell {
- fn get_type(&self) -> &str {
- match self {
- GridCell::None => "None",
- GridCell::Wall => "Wall",
- GridCell::Entity(_) => "Entity"
- }
- }
- fn get_ent(&self) -> Rc<Entity> {
- match self {
- GridCell::Entity(ent) => ent.upgrade().unwrap(),
- _ => panic!()
- }
- }
- }
- fn main() {
- let mut grid = Grid::new(128, 128);
- grid[(12, 12)] = GridCell::Wall;
- let mut ent = Rc::new(Entity{});
- grid[(12, 13)] = GridCell::Entity(Rc::downgrade(&ent));
- grid[(12, 14)] = GridCell::Entity(Rc::downgrade(&ent));
- let cell = &grid[(12, 12)];
- println!("{}", cell.get_type());
- println!("{}", grid[(12, 13)].get_type());
- println!("{}", grid[(12, 14)].get_type());
- println!("{}", grid[(12, 15)].get_type());
- let entity_cell_a = &grid[(12, 13)].get_ent();
- let entity_cell_b = &grid[(12, 14)].get_ent();
- if Rc::ptr_eq(entity_cell_a, entity_cell_b) {
- println!("Eq");
- } else {
- println!("Ne");
- }
- ()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement