diff --git a/src/game/pathfinder.rs b/src/game/pathfinder.rs index 348a878..0d1ba89 100644 --- a/src/game/pathfinder.rs +++ b/src/game/pathfinder.rs @@ -1,13 +1,43 @@ use js_sys::{Array, Object}; use serde::{Deserialize, Serialize}; +use std::fmt; use wasm_bindgen::prelude::*; -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct Position { pub x: u8, pub y: u8, } +impl fmt::Display for Position { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[pos {},{}]", self.x, self.y) + } +} + +impl Position { + pub fn range_to(&self, pos: &Position) -> u8 { + let diff_x = if self.x > pos.x { + self.x - pos.x + } else { + pos.x - self.x + }; + let diff_y = if self.y > pos.y { + self.y - pos.y + } else { + pos.y - self.y + }; + + std::cmp::max(diff_x, diff_y) + } +} + +impl From for JsValue { + fn from(pos: Position) -> JsValue { + serde_wasm_bindgen::to_value(&pos).expect("serializable Position") + } +} + #[wasm_bindgen(module = "game/path-finder")] extern "C" { /// Find an optimal path between origin and goal. Note that searchPath diff --git a/src/objects/impls/game_object.rs b/src/objects/impls/game_object.rs index b845dfc..dd82565 100644 --- a/src/objects/impls/game_object.rs +++ b/src/objects/impls/game_object.rs @@ -1,5 +1,5 @@ use crate::{ - game::pathfinder::{FindPathOptions, SearchResults}, + game::pathfinder::{FindPathOptions, Position, SearchResults}, prelude::*, }; use js_sys::{Array, JsString, Object}; @@ -79,6 +79,13 @@ impl GameObject { } } } + + pub fn pos(&self) -> Position { + Position { + x: self.x(), + y: self.y(), + } + } } impl GameObjectProperties for T @@ -101,6 +108,10 @@ where GameObject::y(self.as_ref()) } + fn pos(&self) -> Position { + GameObject::pos(self.as_ref()) + } + fn ticks_to_decay(&self) -> Option { GameObject::ticks_to_decay(self.as_ref()) } diff --git a/src/traits.rs b/src/traits.rs index 2b91c68..f6590d7 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -3,7 +3,7 @@ use js_sys::{Array, JsString, Object}; use crate::{ enums::*, - game::pathfinder::{FindPathOptions, SearchResults}, + game::pathfinder::{FindPathOptions, Position, SearchResults}, objects::*, }; @@ -152,6 +152,8 @@ pub trait GameObjectProperties { /// The Y coordinate in the room. fn y(&self) -> u8; + fn pos(&self) -> Position; + /// If defined, then this object will disappear after this number of ticks. fn ticks_to_decay(&self) -> Option;