From 4fe231fcc252f19e3fa5e50d369571f1caf6ad33 Mon Sep 17 00:00:00 2001 From: Tom Barrett Date: Sat, 20 Mar 2021 15:35:18 +0100 Subject: gems now fall --- src/main.rs | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index f3d41b0..56f2ea9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use rand::{ Rng, }; -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Clone)] enum Occupant { None, Green, @@ -38,7 +38,7 @@ impl Distribution for Standard { } } -#[derive(Debug)] +#[derive(Debug, Clone)] struct Cell { x: u8, y: u8, @@ -55,7 +55,7 @@ impl Cell { } } -fn cell_falling_system(mut cell_query: Query<(&mut Cell, &mut TextureAtlasSprite)>) { +fn cell_insert_system(mut cell_query: Query<(&mut Cell, &mut TextureAtlasSprite)>) { for (mut cell, mut sprite) in cell_query.iter_mut() { if cell.occupant == Occupant::None { if cell.y == 7 { @@ -66,6 +66,36 @@ fn cell_falling_system(mut cell_query: Query<(&mut Cell, &mut TextureAtlasSprite } } +fn cell_falling_system(mut cell_query: Query<(&mut Cell, &mut TextureAtlasSprite)>) { + let mut have_gems = Vec::new(); + for (cell, _sprite) in cell_query.iter_mut() { + if cell.occupant != Occupant::None { + have_gems.push(cell.clone()); + } + } + + let mut moved_gems = Vec::new(); + for (mut cell, mut sprite) in cell_query.iter_mut() { + if cell.occupant == Occupant::None { + if let Some(c) = have_gems + .iter() + .find(|&c| (c.x, c.y) == (cell.x, cell.y + 1)) + { + cell.occupant = c.occupant.clone(); + sprite.index = cell.occupant.to_index(); + moved_gems.push(c.clone()); + } + } + } + + for (mut cell, mut sprite) in cell_query.iter_mut() { + if moved_gems.iter().any(|c| (c.x, c.y) == (cell.x, cell.y)) { + cell.occupant = Occupant::None; + sprite.index = cell.occupant.to_index(); + } + } +} + pub fn setup( commands: &mut Commands, asset_server: Res, @@ -148,6 +178,7 @@ pub struct GemsPlugin; impl Plugin for GemsPlugin { fn build(&self, app: &mut AppBuilder) { app.add_startup_system(setup.system()); + app.add_system(cell_insert_system.system()); app.add_system(cell_falling_system.system()); } } -- cgit v1.2.3