move player

This commit is contained in:
Joachim Lusiardi 2023-11-11 18:55:31 +01:00
parent 9101e0ae6d
commit 62040642eb
4 changed files with 31 additions and 3 deletions

View File

@ -4,4 +4,11 @@ use crate::player::Player;
pub struct Game { pub struct Game {
pub player: Player, pub player: Player,
pub levels: [Level; 25] pub levels: [Level; 25]
}
impl Game {
pub fn move_player(&mut self, dx: i8, dy: i8) {
// check if move is allowed first
self.player.change_position(dx, dy);
}
} }

View File

@ -23,7 +23,7 @@ mod position;
mod level_widget; mod level_widget;
fn main() -> Result<()> { fn main() -> Result<()> {
let g = Game { let mut g = Game {
player: Player::new("Teddy Tester", 10), player: Player::new("Teddy Tester", 10),
levels: [Level::new(); 25], levels: [Level::new(); 25],
}; };
@ -62,10 +62,11 @@ fn main() -> Result<()> {
height: 25, height: 25,
}; };
frame.render_widget( frame.render_widget(
Paragraph::new(format!("{}\nHealth: {}/{}", Paragraph::new(format!("{}\nHealth: {}/{}\n{}",
g.player.get_name(), g.player.get_name(),
g.player.get_life(), g.player.get_life(),
g.player.get_max_life())) g.player.get_max_life(),
g.player.get_position().get_x()))
.white() .white()
.on_blue(), .on_blue(),
stats_area, stats_area,
@ -76,6 +77,18 @@ fn main() -> Result<()> {
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') { if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
break; break;
} }
if key.kind == KeyEventKind::Press && key.code == KeyCode::Left {
g.move_player(-1, 0);
}
if key.kind == KeyEventKind::Press && key.code == KeyCode::Right {
g.move_player(1, 0);
}
if key.kind == KeyEventKind::Press && key.code == KeyCode::Up {
g.move_player(0, -1);
}
if key.kind == KeyEventKind::Press && key.code == KeyCode::Down {
g.move_player(0, 1);
}
} }
} }
} }

View File

@ -28,6 +28,9 @@ impl Player {
pub fn get_position(&self) -> Position { pub fn get_position(&self) -> Position {
self.position self.position
} }
pub fn change_position(&mut self, dx: i8, dy: i8) {
self.position.change(dx, dy);
}
} }
#[test] #[test]

View File

@ -24,4 +24,9 @@ impl Position {
pub fn get_y(&self) -> u16 { pub fn get_y(&self) -> u16 {
self.y self.y
} }
pub fn change(&mut self, dx: i8, dy: i8) {
self.x = ((self.x as i16) + dx as i16) as u16;
self.y = ((self.y as i16) + dy as i16) as u16;
}
} }