Skip to content

Commit

Permalink
fix(map): fix Map::from_actions
Browse files Browse the repository at this point in the history
  • Loading branch information
ShenMian committed Nov 16, 2024
1 parent fb232ac commit 71f3fe3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ impl Map {
player_position += &action.direction().into();
min_position = min_position.zip_map(&player_position, |a, b| a.min(b));
max_position = max_position.zip_map(&player_position, |a, b| a.max(b));
if action.is_push() {
min_position = min_position
.zip_map(&(player_position + &action.direction().into()), |a, b| {
a.min(b)
});
max_position = max_position
.zip_map(&(player_position + &action.direction().into()), |a, b| {
a.max(b)
});
}
}

// Reserve space for walls
Expand All @@ -69,6 +79,7 @@ impl Map {
instance[current_player_position] = Tiles::Floor;
current_player_position += &action.direction().into();
if action.is_push() {
instance[current_player_position + &action.direction().into()] = Tiles::Floor;
// The player pushed the box when moving, which means there is a box at the
// player's current position
if !current_box_positions.contains(&current_player_position) {
Expand Down Expand Up @@ -96,6 +107,9 @@ impl Map {
for goal_position in &goal_positions {
instance[*goal_position].insert(Tiles::Goal);
}
if box_positions.contains(&player_position) {
return Err(ParseMapError::InvalidActions);
}

instance.add_walls_around_floors();

Expand All @@ -110,6 +124,9 @@ impl Map {
.do_action(action.direction())
.map_err(|_| ParseMapError::InvalidActions)?;
}
if !level.map().is_solved() {
return Err(ParseMapError::InvalidActions);
}

Ok(instance)
}
Expand Down
8 changes: 7 additions & 1 deletion tests/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ mod utils;
use utils::*;

#[test]
fn parse_map_error() {
fn map_from_str() {
let no_player_map = r#"
#####
# $.#
Expand Down Expand Up @@ -63,6 +63,12 @@ fn parse_map_error() {
Map::from_str(invalid_character_map).unwrap_err(),
ParseMapError::InvalidCharacter('!')
);
}

#[test]
fn map_from_actions() {
assert!(Map::from_actions(&Actions::from_str("R").unwrap()).is_ok());
assert!(Map::from_actions(&Actions::from_str("DuLLrUUdrR").unwrap()).is_ok());

assert_eq!(
Map::from_actions(&Actions::from_str("RddrU").unwrap()).unwrap_err(),
Expand Down

0 comments on commit 71f3fe3

Please sign in to comment.