Monsters can attack player now

This commit is contained in:
Joachim Lusiardi 2023-12-30 16:31:27 +01:00
parent b88bc67c50
commit b3d64f7438
3 changed files with 20 additions and 12 deletions

View File

@ -43,8 +43,6 @@ impl Game {
g
}
/// returns true if the player is dead (life <= 0)
fn player_is_dead(&self) -> bool { self.get_player().get_life() <= 0 }
/// returns true if the player is standing on the End element
fn player_reached_goal(&mut self) -> bool {
match self.next_element(0, 0) {
@ -60,7 +58,7 @@ impl Game {
}
/// returns the state of the game (depending on player's life and position)
pub fn get_game_state(&mut self) -> GameState {
if self.player_is_dead() {
if self.player.is_dead() {
return GameState::LOST;
}
if self.player_reached_goal() {

View File

@ -1,5 +1,8 @@
use std::cmp::{max, min};
use rand::Rng;
use rand::rngs::ThreadRng;
#[cfg(test)]
use crate::artifacts::{Chest, Potion};
use crate::artifacts::Artifact;
@ -9,8 +12,6 @@ use crate::monster::Monster;
use crate::player::Player;
use crate::position::HasPosition;
use crate::position::Position;
use rand::Rng;
use rand::rngs::ThreadRng;
pub const LEVEL_WIDTH: usize = 50;
pub const LEVEL_HEIGHT: usize = 25;
@ -118,13 +119,10 @@ impl Level {
break;
}
}
for (index, m) in &mut self.monsters.iter().enumerate() {
if m.is_dead() {
self.monsters.remove(index);
break;
}
}
for index in 0..self.monsters.len() {
if self.monsters[index].is_dead() {
continue;
}
if ticks % self.monsters[index].get_ticks_between_steps() != 0 {
continue;
}
@ -142,11 +140,21 @@ impl Level {
if player.get_immutable_position().get_x() == new_x && player.get_immutable_position().get_y() == new_y {
self.monsters[index].decrease_life(1);
player.change_life(-1);
// if the attack did not kill the opponent, back down
if !player.is_dead() {
self.monsters[index].get_position().change(-dx, -dy);
}
}
break;
}
}
}
for (index, m) in &mut self.monsters.iter().enumerate() {
if m.is_dead() {
self.monsters.remove(index);
break;
}
}
}
pub fn can_monster_move(&self, agent: &dyn Monster, dx: i16, dy: i16) -> bool {
@ -154,7 +162,7 @@ impl Level {
let new_x: usize = (agent_pos.get_x() as i16 + dx) as usize;
let new_y: usize = (agent_pos.get_y() as i16 + dy) as usize;
if new_x < 0 || new_y < 0 || new_x >= LEVEL_WIDTH || new_y >= LEVEL_HEIGHT {
if new_x >= LEVEL_WIDTH || new_y >= LEVEL_HEIGHT {
return false;
}

View File

@ -28,9 +28,11 @@ impl Player {
pub fn change_life(&mut self, by: i16) {
self.life = max(0, min(self.max_life, self.life + by));
}
/// returns true if the player is dead (life <= 0)
pub fn get_life(&self) -> i16 {
self.life
}
pub fn is_dead(&self) -> bool { self.life <= 0 }
pub fn get_max_life(&self) -> i16 {
self.max_life
}