Add centering of layouts.

This commit is contained in:
hal8174 2024-09-26 00:30:57 +02:00
parent b79d0dffb6
commit 907691685c
3 changed files with 101 additions and 17 deletions

View file

@ -15,18 +15,30 @@ impl Transformation {
Self { rot, pos }
}
pub fn transform_position(&self, pos: &Position) -> Position {
(match self.rot {
Direction::Up => *pos,
Direction::Right => Position::new(-pos.y, pos.x),
Direction::Down => Position::new(-pos.x, -pos.y),
Direction::Left => Position::new(pos.y, -pos.x),
}) + self.pos
}
pub fn rot(&self) -> Direction {
self.rot
}
pub fn invert(self) -> Self {
Self::new(
match self.rot {
Direction::Up => Direction::Up,
Direction::Right => Direction::Left,
Direction::Down => Direction::Down,
Direction::Left => Direction::Right,
},
match self.rot {
Direction::Up => Position::new(-self.pos.x, -self.pos.y),
Direction::Right => Position::new(-self.pos.y, self.pos.x),
Direction::Down => self.pos,
Direction::Left => Position::new(self.pos.y, -self.pos.x),
},
)
}
pub fn chain(self, other: Self) -> Self {
Self::new(self.rot.transform(other), self.pos.transform(other))
}
}
impl Transformable for Position {
@ -43,7 +55,7 @@ impl Transformable for Position {
impl Transformable for Direction {
fn transform(&self, t: Transformation) -> Self {
match (t.rot, self) {
(Direction::Up, _) => Direction::Up,
(Direction::Up, _) => *self,
(Direction::Right, Direction::Up) => Direction::Right,
(Direction::Right, Direction::Right) => Direction::Down,
(Direction::Right, Direction::Down) => Direction::Left,
@ -69,9 +81,34 @@ mod test {
let p = Position::new(3, 5);
let t = Transformation::new(Direction::Up, Position::new(-3, -5));
assert_eq!(t.transform_position(&p), Position::new(0, 0));
assert_eq!(p.transform(t), Position::new(0, 0));
let t = Transformation::new(Direction::Down, Position::new(-3, -5));
assert_eq!(t.transform_position(&p), Position::new(-6, -10));
assert_eq!(p.transform(t), Position::new(-6, -10));
}
#[test]
fn invert() {
let transformations = [
Transformation::new(Direction::Up, Position::new(-3, -5)),
Transformation::new(Direction::Right, Position::new(-3, -5)),
Transformation::new(Direction::Down, Position::new(-3, -5)),
Transformation::new(Direction::Left, Position::new(-3, -5)),
];
for o in transformations {
let i = o.invert();
let c = o.chain(i);
assert_eq!(c.rot, Direction::Up, "o: {:?}, i: {:?}, c: {:?}", o, i, c);
assert_eq!(
c.pos,
Position::new(0, 0),
"o: {:?}, i: {:?}, c: {:?}",
o,
i,
c
);
}
}
}