108 lines
3.4 KiB
Rust
108 lines
3.4 KiB
Rust
use crate::prelude::*;
|
|
use components::CropVisual;
|
|
|
|
pub mod components;
|
|
pub mod consts;
|
|
pub mod errors;
|
|
pub mod utils;
|
|
|
|
pub struct GridPlugin;
|
|
|
|
impl Plugin for GridPlugin {
|
|
fn build(&self, app: &mut App) {
|
|
app.add_systems(OnEnter(AppState::GameScreen), setup);
|
|
app.add_systems(OnExit(AppState::GameScreen), cleanup);
|
|
|
|
app.add_systems(Update, update_tiles.run_if(in_state(AppState::GameScreen)));
|
|
}
|
|
}
|
|
|
|
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, config: Res<GameConfig>) {
|
|
let grid_width = config.grid_width;
|
|
let grid_height = config.grid_height;
|
|
let mut tiles = Vec::with_capacity(grid_width as usize);
|
|
|
|
for x in 0..grid_width {
|
|
let mut column = Vec::with_capacity(grid_height as usize);
|
|
|
|
for y in 0..grid_height {
|
|
let tile_entity = commands
|
|
.spawn((
|
|
Tile { x, y },
|
|
TileState::Unclaimed,
|
|
AseSlice {
|
|
name: "Unclaimed".into(),
|
|
aseprite: asset_server.load("tiles/tile-unclaimed.aseprite"),
|
|
},
|
|
Sprite::default(),
|
|
Transform::from_translation(grid_to_world_coords(
|
|
x,
|
|
y,
|
|
None,
|
|
grid_width,
|
|
grid_height,
|
|
)),
|
|
))
|
|
.with_children(|parent| {
|
|
parent.spawn((
|
|
CropVisual,
|
|
AseSlice {
|
|
name: "Crop".into(),
|
|
aseprite: asset_server.load("crop.aseprite"),
|
|
},
|
|
Sprite::default(),
|
|
Transform::default(),
|
|
Visibility::Hidden,
|
|
ZIndex(1),
|
|
));
|
|
})
|
|
.id();
|
|
column.push(tile_entity);
|
|
}
|
|
tiles.push(column);
|
|
}
|
|
|
|
commands.insert_resource(Grid {
|
|
width: grid_width,
|
|
height: grid_height,
|
|
tiles,
|
|
});
|
|
}
|
|
|
|
fn cleanup(mut commands: Commands, tile_query: Query<Entity, With<Tile>>) {
|
|
for tile_entity in tile_query.iter() {
|
|
commands.entity(tile_entity).despawn();
|
|
}
|
|
commands.remove_resource::<Grid>();
|
|
}
|
|
|
|
fn update_tiles(
|
|
mut query: Query<(&TileState, &mut AseSlice, &Children)>,
|
|
mut crop_query: Query<&mut Visibility, With<CropVisual>>,
|
|
asset_server: Res<AssetServer>,
|
|
) {
|
|
for (state, mut slice, children) in &mut query {
|
|
slice.name = match state {
|
|
TileState::Unclaimed => "Unclaimed",
|
|
TileState::Empty => "Empty",
|
|
TileState::Occupied { .. } => "Occupied",
|
|
}
|
|
.into();
|
|
|
|
slice.aseprite = match state {
|
|
TileState::Unclaimed => asset_server.load("tiles/tile-unclaimed.aseprite"),
|
|
TileState::Empty => asset_server.load("tiles/tile-empty.aseprite"),
|
|
TileState::Occupied { .. } => asset_server.load("tiles/tile-occupied.aseprite"),
|
|
};
|
|
|
|
for child in children.iter() {
|
|
if let Ok(mut visibility) = crop_query.get_mut(child) {
|
|
*visibility = match state {
|
|
TileState::Occupied { .. } => Visibility::Visible,
|
|
_ => Visibility::Hidden,
|
|
};
|
|
}
|
|
}
|
|
}
|
|
}
|