Skip to content

Commit

Permalink
refactor: refactor some code
Browse files Browse the repository at this point in the history
  • Loading branch information
ShenMian committed Jan 22, 2024
1 parent d9dc8ce commit 137d9f8
Show file tree
Hide file tree
Showing 9 changed files with 50 additions and 36 deletions.
2 changes: 1 addition & 1 deletion src/board.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ impl Board {
}

pub fn is_solved(&self) -> bool {
return self.level.crate_positions == self.level.target_positions;
self.level.crate_positions == self.level.target_positions
}

pub fn player_orientation(&self) -> Direction {
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ fn main() {
app.add_systems(
OnEnter(AppState::AutoSolve),
(
(setup_solver, spawn_lowerbound_marks).chain(),
(load_solver, spawn_lowerbound_marks).chain(),
clear_action_state,
),
)
Expand All @@ -135,6 +135,7 @@ fn main() {
reset_board,
update_grid_position,
move_tiles,
unload_solver,
despawn_lowerbound_marks,
)
.chain(),
Expand Down
6 changes: 5 additions & 1 deletion src/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ pub struct SolverState {
impl Default for SolverState {
fn default() -> Self {
Self {
solver: Mutex::new(Solver::new(Level::empty())),
solver: Mutex::new(Solver::new(
Level::empty(),
Strategy::Fast,
LowerBoundMethod::MinimumMove,
)),
level: Level::empty(),
stopwatch: Stopwatch::new(),
}
Expand Down
32 changes: 16 additions & 16 deletions src/solver/solver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,28 +61,24 @@ pub enum SolveError {
type Result<T> = std::result::Result<T, SolveError>;

impl Solver {
pub fn new(mut level: Level) -> Self {
pub fn new(mut level: Level, strategy: Strategy, lower_bound_method: LowerBoundMethod) -> Self {
level.clear(Tile::Player | Tile::Crate);
Self {
let mut instance = Self {
level,
strategy: Strategy::Fast,
lower_bound_method: LowerBoundMethod::MinimumMove,
strategy,
lower_bound_method,
lower_bounds: OnceCell::new(),
tunnels: OnceCell::new(),
visited: HashSet::new(),
heap: BinaryHeap::new(),
}
}

pub fn initial(&mut self, strategy: Strategy, lower_bound_method: LowerBoundMethod) {
self.strategy = strategy;
self.lower_bound_method = lower_bound_method;
self.heap.push(State::new(
self.level.player_position,
self.level.crate_positions.clone(),
};
instance.heap.push(State::new(
instance.level.player_position,
instance.level.crate_positions.clone(),
Movements::new(),
self,
&instance,
));
instance
}

pub fn solve(&mut self, timeout: Duration) -> Result<Movements> {
Expand Down Expand Up @@ -195,7 +191,7 @@ impl Solver {
{
continue;
}
if self.level.target_positions.contains(&position) {
if self.level.get_unchecked(&position).intersects(Tile::Target) {
lower_bounds.insert(position, 0);
continue;
}
Expand All @@ -205,7 +201,11 @@ impl Solver {
.crate_pushable_paths_with_crate_positions(&position, &HashSet::new());
if let Some(lower_bound) = paths
.iter()
.filter(|path| self.level.target_positions.contains(&path.0.crate_position))
.filter(|path| {
self.level
.get_unchecked(&path.0.crate_position)
.intersects(Tile::Target)
})
.map(|path| path.1.len() - 1)
.min()
{
Expand Down
6 changes: 4 additions & 2 deletions src/solver/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ impl State {
new_crate_positions.insert(new_crate_position);

// skip deadlocks
if !solver.level.target_positions.contains(&new_crate_position)
if !solver
.level
.get_unchecked(&new_crate_position)
.intersects(Tile::Target)
&& self.is_freeze_deadlock(
&new_crate_position,
&new_crate_positions,
Expand Down Expand Up @@ -237,7 +240,6 @@ impl State {
}

fn calculate_lower_bound(&self, solver: &Solver) -> usize {
// FIXME: Panic on Microban #155
self.crate_positions
.iter()
.map(|crate_position| solver.lower_bounds()[&crate_position])
Expand Down
13 changes: 10 additions & 3 deletions src/systems/auto_solve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::AppState;

use std::time::{Duration, Instant};

pub fn setup_solver(
pub fn load_solver(
mut solver_state: ResMut<SolverState>,
board: Query<&Board>,
settings: Res<Settings>,
Expand All @@ -21,11 +21,18 @@ pub fn setup_solver(
} = &mut *solver_state;
*level = board.level.clone();
let mut solver = solver.lock().unwrap();
*solver = Solver::new(level.clone());
solver.initial(settings.solver.strategy, settings.solver.lower_bound_method);
*solver = Solver::new(
level.clone(),
settings.solver.strategy,
settings.solver.lower_bound_method,
);
stopwatch.reset();
}

pub fn unload_solver(mut solver_state: ResMut<SolverState>) {
*solver_state = SolverState::default();
}

pub fn spawn_lowerbound_marks(
solver_state: Res<SolverState>,
mut commands: Commands,
Expand Down
16 changes: 8 additions & 8 deletions src/systems/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ pub enum Action {
ZoomOut,
ZoomIn,

InstantMove,
AutomaticSolution,
ToggleInstantMove,
ToggleAutomaticSolution,

ImportLevelsFromClipboard,
ExportLevelToClipboard,
Expand Down Expand Up @@ -118,11 +118,11 @@ impl Action {
),
(
UserInput::Single(InputKind::Keyboard(KeyCode::I)),
Self::InstantMove,
Self::ToggleInstantMove,
),
(
UserInput::Single(InputKind::Keyboard(KeyCode::P)),
Self::AutomaticSolution,
Self::ToggleAutomaticSolution,
),
(
UserInput::Chord(vec![
Expand Down Expand Up @@ -210,11 +210,11 @@ impl Action {
),
(
UserInput::Single(InputKind::GamepadButton(GamepadButtonType::West)),
Self::InstantMove,
Self::ToggleInstantMove,
),
(
UserInput::Single(InputKind::GamepadButton(GamepadButtonType::North)),
Self::AutomaticSolution,
Self::ToggleAutomaticSolution,
),
])
}
Expand Down Expand Up @@ -326,7 +326,7 @@ pub fn handle_other_action(
update_grid_position_events.send(UpdateGridPositionEvent);
}

if action_state.just_pressed(Action::InstantMove) {
if action_state.just_pressed(Action::ToggleInstantMove) {
settings.instant_move = !settings.instant_move;
}

Expand Down Expand Up @@ -373,7 +373,7 @@ pub fn handle_automatic_solution_action(
mut next_state: ResMut<NextState<AppState>>,
mut player_movement: ResMut<PlayerMovement>,
) {
if action_state.just_pressed(Action::AutomaticSolution) {
if action_state.just_pressed(Action::ToggleAutomaticSolution) {
player_movement.directions.clear();
if *state == AppState::Main {
next_state.set(AppState::AutoSolve);
Expand Down
4 changes: 2 additions & 2 deletions src/systems/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ pub fn button_input_to_action(
continue;
}
match *button {
MainButton::InstantMove => action_state.press(Action::InstantMove),
MainButton::AutomaticSolution => action_state.press(Action::AutomaticSolution),
MainButton::InstantMove => action_state.press(Action::ToggleInstantMove),
MainButton::AutomaticSolution => action_state.press(Action::ToggleAutomaticSolution),
MainButton::PreviousLevel => action_state.press(Action::PreviousLevel),
MainButton::NextLevel => action_state.press(Action::NextLevel),
}
Expand Down
4 changes: 2 additions & 2 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ mod tests {
}
println!("#{} ({})", id + 1, id);
let level = levels[id].clone();
let mut solver = Solver::new(level.clone());
solver.initial(Strategy::Fast, LowerBoundMethod::MinimumMove);
let mut solver =
Solver::new(level.clone(), Strategy::Fast, LowerBoundMethod::MinimumMove);
let solution = solver.solve(Duration::from_secs(time_limit));
if solution.is_err() {
println!("{}", level.export_map());
Expand Down

0 comments on commit 137d9f8

Please sign in to comment.