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

@ -5,3 +5,10 @@ pub struct Game {
pub player: Player,
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;
fn main() -> Result<()> {
let g = Game {
let mut g = Game {
player: Player::new("Teddy Tester", 10),
levels: [Level::new(); 25],
};
@ -62,10 +62,11 @@ fn main() -> Result<()> {
height: 25,
};
frame.render_widget(
Paragraph::new(format!("{}\nHealth: {}/{}",
Paragraph::new(format!("{}\nHealth: {}/{}\n{}",
g.player.get_name(),
g.player.get_life(),
g.player.get_max_life()))
g.player.get_max_life(),
g.player.get_position().get_x()))
.white()
.on_blue(),
stats_area,
@ -76,6 +77,18 @@ fn main() -> Result<()> {
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
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 {
self.position
}
pub fn change_position(&mut self, dx: i8, dy: i8) {
self.position.change(dx, dy);
}
}
#[test]

View File

@ -24,4 +24,9 @@ impl Position {
pub fn get_y(&self) -> u16 {
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;
}
}