diff --git a/src/game.rs b/src/game.rs index 58d67c4..57eb053 100644 --- a/src/game.rs +++ b/src/game.rs @@ -18,6 +18,7 @@ impl Plugin for GamePlugin { }), select_sync.run_if(any_component_added::), deselect_sync.run_if(any_component_removed::()), + move_piece.run_if(any_component_added::), ), ) .add_systems( @@ -333,12 +334,37 @@ fn deselect_sync( }) } -fn cancel_place( - current: Query, With)>, - mut commands: Commands, -) { +fn cancel_place(current: Query, With)>, mut commands: Commands) { current.iter().for_each(|entity| { info!("De-selecting {:?}", entity); - commands.entity(entity).remove::(); + commands.entity(entity).remove::(); + }); +} + +/// When a tile is selected, move all selected pieces to that index +fn move_piece( + events: Query<(Entity, &BoardIndex), (With, Added)>, + selected_pieces: Query<(Entity, &BoardIndex), (With, With)>, + mut board: ResMut, + mut commands: Commands, + mut move_events: EventWriter, +) { + events.iter().for_each(|(tile, to)| { + selected_pieces.iter().for_each(|(piece, from)| { + // Move piece + match board.move_piece(from, to) { + Ok(moves) => { + // De-select the piece + commands.entity(piece).remove::(); + moves.iter().for_each(|m| move_events.send(m.clone())); + } + Err(GameError::NullMove) => warn!("Null move!"), + Err(GameError::InvalidMove) => warn!("Invalid move!"), + Err(GameError::InvalidIndex) => warn!("Invalid index!"), + } + }); + + // De-select the tile + commands.entity(tile).remove::(); }); }