Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. use std::rc::{Rc, Weak};
  2. use std::ops::{Index, IndexMut};
  3.  
  4. #[derive(Debug)]
  5. enum GridCell {
  6. None,
  7. Wall,
  8. Entity(Weak<Entity>)
  9. }
  10.  
  11. #[derive(Debug)]
  12. struct Entity {}
  13.  
  14. struct Grid {
  15. size_x: usize,
  16. size_y: usize,
  17. vec: Vec<GridCell>
  18. }
  19.  
  20. impl Grid {
  21. fn new(size_x: usize, size_y: usize) -> Grid {
  22. let mut vec = Vec::with_capacity(size_x * size_y);
  23. for _ in 0..size_x * size_y {
  24. vec.push(GridCell::None);
  25. }
  26. Grid {
  27. size_x, size_y,
  28. vec
  29. }
  30. }
  31. }
  32.  
  33. impl Index<(usize, usize)> for Grid {
  34. type Output = GridCell;
  35.  
  36. fn index(&self, index: (usize, usize)) -> &GridCell {
  37. let (x, y) = index;
  38. if x >= self.size_x || y >= self.size_y {
  39. panic!("out of bounds")
  40. } else {
  41. &self.vec[x*self.size_y+y]
  42. }
  43. }
  44. }
  45.  
  46. impl IndexMut<(usize, usize)> for Grid {
  47. fn index_mut(&mut self, index: (usize, usize)) -> &mut GridCell {
  48. let (x, y) = index;
  49. if x >= self.size_x || y >= self.size_y {
  50. panic!("out of bounds")
  51. } else {
  52. &mut self.vec[x*self.size_y+y]
  53. }
  54. }
  55. }
  56.  
  57. impl GridCell {
  58. fn get_type(&self) -> &str {
  59. match self {
  60. GridCell::None => "None",
  61. GridCell::Wall => "Wall",
  62. GridCell::Entity(_) => "Entity"
  63. }
  64. }
  65.  
  66. fn get_ent(&self) -> Rc<Entity> {
  67. match self {
  68. GridCell::Entity(ent) => ent.upgrade().unwrap(),
  69. _ => panic!()
  70. }
  71. }
  72. }
  73.  
  74. fn main() {
  75. let mut grid = Grid::new(128, 128);
  76.  
  77. grid[(12, 12)] = GridCell::Wall;
  78.  
  79. let mut ent = Rc::new(Entity{});
  80. grid[(12, 13)] = GridCell::Entity(Rc::downgrade(&ent));
  81. grid[(12, 14)] = GridCell::Entity(Rc::downgrade(&ent));
  82.  
  83. let cell = &grid[(12, 12)];
  84. println!("{}", cell.get_type());
  85. println!("{}", grid[(12, 13)].get_type());
  86. println!("{}", grid[(12, 14)].get_type());
  87. println!("{}", grid[(12, 15)].get_type());
  88.  
  89. let entity_cell_a = &grid[(12, 13)].get_ent();
  90. let entity_cell_b = &grid[(12, 14)].get_ent();
  91.  
  92. if Rc::ptr_eq(entity_cell_a, entity_cell_b) {
  93. println!("Eq");
  94. } else {
  95. println!("Ne");
  96. }
  97.  
  98.  
  99. ()
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement