diff options
author | Toby Vincent <tobyv13@gmail.com> | 2022-08-09 15:32:27 -0500 |
---|---|---|
committer | Toby Vincent <tobyv13@gmail.com> | 2022-08-10 12:08:40 -0500 |
commit | 37c88bfc0b6dcb4a32e33b3dc35d8eba456388c4 (patch) | |
tree | 9169e04bd87aa4059861b3cc265ed2c9ef8274ae /src/entity/player.rs | |
parent | 26eb05dbf181b22897a43c88e1d3fa75502780ac (diff) |
Diffstat (limited to 'src/entity/player.rs')
-rw-r--r-- | src/entity/player.rs | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/src/entity/player.rs b/src/entity/player.rs new file mode 100644 index 0000000..45f3e13 --- /dev/null +++ b/src/entity/player.rs @@ -0,0 +1,82 @@ +use std::{ + collections::HashMap, + fmt::{Display, Formatter}, +}; + +use termion::event::Key; + +use crate::{ + game::Command, + physics::{Point, Vector}, + Position, Render, Velocity, +}; + +use crate::entity::Controllable; + +#[derive(Debug, Default)] +pub struct Player { + pub position: Point, + pub velocity: Vector, + render_map: HashMap<Point, char>, +} + +impl Player { + pub fn new(position: Point, velocity: Vector) -> Self { + Self { + position, + velocity, + render_map: HashMap::from([(position, '@')]), + } + } +} + +impl Display for Player { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { + return write!( + f, + "{}@", + termion::cursor::Goto(self.position.x, self.position.y) + ); + } +} + +impl Render for Player { + fn render_map(&self) -> &HashMap<Point, char> { + &self.render_map + } +} + +impl Controllable for Player { + fn handle_input(&mut self, key: Key) -> Option<Command> { + match key { + Key::Up | Key::Char('w') | Key::Char('k') => self.velocity.y -= 1, + Key::Down | Key::Char('s') | Key::Char('j') => self.velocity.y += 1, + Key::Left | Key::Char('a') | Key::Char('h') => self.velocity.x -= 1, + Key::Right | Key::Char('d') | Key::Char('l') => self.velocity.x += 1, + _ => return None, + }; + Some(Command::UpdatePlayer) + } +} + +impl Position for Player { + fn get_position(&self) -> Point { + self.position + } + + fn set_position<P: Into<crate::physics::Point>>(&mut self, position: P) -> crate::Result<()> { + self.position = position.into(); + Ok(()) + } +} + +impl Velocity for Player { + fn get_velocity(&self) -> Vector { + self.velocity + } + + fn set_velocity<V: Into<crate::physics::Vector>>(&mut self, velocity: V) -> crate::Result<()> { + self.velocity = velocity.into(); + Ok(()) + } +} |