Created
September 28, 2019 23:28
-
-
Save Kixiron/9ddc98decafde1574bb23dd60be57388 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use pyo3::prelude::*; | |
use pyo3::wrap_pyfunction; | |
/// The lib_pacman_utils module | |
#[pymodule] | |
fn lib_pacman_utils(_py: Python, module: &PyModule) -> PyResult<()> { | |
module.add_wrapped(wrap_pyfunction!(circle_collision))?; | |
module.add_wrapped(wrap_pyfunction!(rect_collision))?; | |
Ok(()) | |
} | |
#[derive(Debug, Copy, Clone, PartialEq, Eq)] | |
struct Circle { | |
x: i32, | |
y: i32, | |
radius: i32, | |
} | |
impl From<(i32, i32, i32)> for Circle { | |
fn from(tuple: (i32, i32, i32)) -> Self { | |
Self { | |
x: tuple.0, | |
y: tuple.1, | |
radius: tuple.2 | |
} | |
} | |
} | |
/// Returns whether or not two circles are colliding | |
#[pyfunction] | |
pub fn circle_collision( | |
circle_one: (i32, i32, i32), | |
circle_two: (i32, i32, i32), | |
) -> PyResult<bool> { | |
let circle_one = Circle::from(circle_one); | |
let circle_two = Circle::from(circle_two); | |
if circle_one == circle_two { | |
return Ok(true); | |
} | |
let mut side_a = (circle_one.x - circle_two.x).abs(); | |
let mut side_b = (circle_one.y - circle_two.y).abs(); | |
side_a = side_a * side_a; | |
side_b = side_b * side_b; | |
let distance = ((side_a + side_b) as f64).sqrt(); | |
Ok(distance < (circle_one.radius + circle_two.radius).into()) | |
} | |
#[derive(Debug, Copy, Clone, PartialEq, Eq)] | |
struct Rectangle { | |
x: i32, | |
y: i32, | |
width: i32, | |
height: i32, | |
} | |
impl From<(i32, i32, i32, i32)> for Rectangle { | |
fn from(tuple: (i32, i32, i32, i32)) -> Self { | |
Self { | |
x: tuple.0, | |
y: tuple.1, | |
width: tuple.2, | |
height: tuple.3, | |
} | |
} | |
} | |
/// Returns whether or not two rectangles are colliding | |
#[pyfunction] | |
pub fn rect_collision( | |
rect_one: (i32, i32, i32, i32), | |
rect_two: (i32, i32, i32, i32), | |
) -> PyResult<bool> { | |
let rect_one = Rectangle::from(rect_one); | |
let rect_two = Rectangle::from(rect_two); | |
if rect_one == rect_two { | |
return Ok(true); | |
} | |
let (top_one, right_one, left_one, bottom_one) = { | |
( | |
rect_one.y + rect_one.height, | |
rect_one.x + rect_one.width, | |
rect_one.x, | |
rect_one.y, | |
) | |
}; | |
let (top_two, right_two, left_two, bottom_two) = { | |
( | |
rect_two.y + rect_two.height, | |
rect_two.x + rect_two.width, | |
rect_two.x, | |
rect_two.y, | |
) | |
}; | |
let colliding = left_one < right_two | |
&& right_one > left_two | |
&& bottom_one < top_two | |
&& top_one > bottom_two; | |
Ok(colliding) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment