71 lines
2.0 KiB
Rust
71 lines
2.0 KiB
Rust
use super::Snake;
|
|
use crate::{audio, level::LevelState, AppState};
|
|
use bevy::prelude::*;
|
|
use leafwing_input_manager::prelude::*;
|
|
|
|
#[derive(Actionlike, Reflect, Component, Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
|
pub(super) enum Direction {
|
|
Up,
|
|
Down,
|
|
Left,
|
|
Right,
|
|
}
|
|
|
|
#[derive(Component, Copy, Clone, Debug, PartialEq, Eq)]
|
|
#[component(storage = "SparseSet")]
|
|
pub(super) struct NextDirection(Direction);
|
|
|
|
pub(super) fn start_game_system(
|
|
query: Query<&ActionState<Direction>>,
|
|
mut next_state: ResMut<NextState<AppState>>,
|
|
) {
|
|
let action_state = query.single();
|
|
|
|
if !action_state.get_just_pressed().is_empty() {
|
|
next_state.set(AppState::InGame(LevelState::InGame));
|
|
}
|
|
}
|
|
|
|
pub(super) fn apply_direction_system(
|
|
mut commands: Commands,
|
|
mut query: Query<(Entity, &NextDirection), With<Snake>>,
|
|
) {
|
|
for (snake, new_direction) in query.iter_mut() {
|
|
commands
|
|
.entity(snake)
|
|
.insert(new_direction.0)
|
|
.remove::<NextDirection>();
|
|
}
|
|
}
|
|
|
|
pub(super) fn change_direction_system(
|
|
mut commands: Commands,
|
|
mut query: Query<(Entity, &ActionState<Direction>, Option<&Direction>), With<Snake>>,
|
|
audio_assets: Res<audio::Assets>,
|
|
) {
|
|
let (snake, action_state, direction) = query.single_mut();
|
|
let new_direction = action_state.get_just_pressed().iter().cloned().last();
|
|
|
|
if let Some(new_direction) = new_direction {
|
|
if let Some(¤t_direction) = direction {
|
|
if let (Direction::Up, Direction::Down)
|
|
| (Direction::Down, Direction::Up)
|
|
| (Direction::Left, Direction::Right)
|
|
| (Direction::Right, Direction::Left) = (current_direction, new_direction)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if new_direction == current_direction {
|
|
return;
|
|
}
|
|
}
|
|
|
|
commands.entity(snake).insert(NextDirection(new_direction));
|
|
commands.spawn(AudioBundle {
|
|
source: audio_assets.tick.clone(),
|
|
..Default::default()
|
|
});
|
|
}
|
|
}
|