Hello humans. I'm writing up a simple labyrinth struct, only allowing vertical and horizontal walls. I have two very similar methods get_wall
and get_wall_mut
(code is below). Do you have any suggestions for how to reduce code duplication here? Each tile in the vector has the wall information ("wallyness") for its east and south wall.
pub fn get_wall(&self, point: &Vec2, direction: Direction) -> Wallyness {
let (x, y) = point.to_tuple();
// Normalize direction by a single recursion step.
use Direction::*;
match direction {
North => return self.get_wall(&Vec2::new(x, y-1), South),
West => return self.get_wall(&Vec2::new(x-1, y), East),
_ => ()
}
// At this point, the direction is either South or East.
if let Some(i) = self.point_to_index(point) {
if x == (self.width - 1) as i32 && direction == East {
return Wallyness::Wall;
}
if y == (self.height - 1) as i32 && direction == South {
return Wallyness::Wall;
}
let t = &self.data[i];
match direction {
East => t.east,
South => t.south,
_ => panic!("illegal state"),
}
} else {
Wallyness::Wall
}
}
pub fn get_wall_mut(&mut self, point: &Vec2, direction: Direction) -> Option<&mut Wallyness> {
let (x, y) = point.to_tuple();
// Normalize direction by a single recursion step.
use Direction::*;
match direction {
North => return self.get_wall_mut(&Vec2::new(x, y-1), South),
West => return self.get_wall_mut(&Vec2::new(x-1, y), East),
_ => ()
}
// At this point, the direction is either South or East.
if let Some(i) = self.point_to_index(point) {
if x == (self.width - 1) as i32 && direction == East {
return None;
}
if y == (self.height - 1) as i32 && direction == South {
return None;
}
let t = &mut self.data[i];
match direction {
East => Some(&mut t.east),
South => Some(&mut t.south),
_ => panic!("illegal state"),
}
} else {
None
}
}