Skip to content

Commit

Permalink
feat: Position traits + GameObject.pos()
Browse files Browse the repository at this point in the history
add equality/hash traits to Position so that it can be used as keys in
collections such as HashSet

give every GameObject a pos() method which returns Position
  • Loading branch information
wtfrank committed Apr 2, 2024
1 parent f140eed commit 75391ea
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
32 changes: 31 additions & 1 deletion src/game/pathfinder.rs
Original file line number Diff line number Diff line change
@@ -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<Position> 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
Expand Down
13 changes: 12 additions & 1 deletion src/objects/impls/game_object.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
game::pathfinder::{FindPathOptions, SearchResults},
game::pathfinder::{FindPathOptions, Position, SearchResults},
prelude::*,
};
use js_sys::{Array, JsString, Object};
Expand Down Expand Up @@ -79,6 +79,13 @@ impl GameObject {
}
}
}

pub fn pos(&self) -> Position {
Position {
x: self.x(),
y: self.y(),
}
}
}

impl<T> GameObjectProperties for T
Expand All @@ -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<u32> {
GameObject::ticks_to_decay(self.as_ref())
}
Expand Down
4 changes: 3 additions & 1 deletion src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use js_sys::{Array, JsString, Object};

use crate::{
enums::*,
game::pathfinder::{FindPathOptions, SearchResults},
game::pathfinder::{FindPathOptions, Position, SearchResults},
objects::*,
};

Expand Down Expand Up @@ -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<u32>;

Expand Down

0 comments on commit 75391ea

Please sign in to comment.