Проектная работа - MVP
Создание нового проекта
This commit is contained in:
@@ -1,2 +1,2 @@
|
|||||||
/target/
|
/target/
|
||||||
/Cargo.lock
|
/*.log
|
||||||
|
|||||||
Generated
+4662
File diff suppressed because it is too large
Load Diff
@@ -4,8 +4,14 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bevy = "0.18"
|
bevy = { version = "0.18", default-features = false, features = ["2d_bevy_render", "bevy_log", "bevy_winit", "bevy_text", "bevy_ui", "debug"] }
|
||||||
|
# bevy = { version = "0.18" }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = "0.3"
|
||||||
|
rand = "0.10"
|
||||||
|
|
||||||
|
# for examples
|
||||||
|
rand_chacha = "0.10"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
opt-level = "z"
|
opt-level = "z"
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
/// Эксперименты в ходе прохождения туториала:
|
||||||
|
/// https://github.com/fogarecious/bevy_tutorial
|
||||||
|
use bevy::{prelude::*, winit::WinitSettings};
|
||||||
|
use tracing::Level;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
App::new()
|
||||||
|
// .add_plugins(MinimalPlugins)
|
||||||
|
.add_plugins(
|
||||||
|
DefaultPlugins
|
||||||
|
.build()
|
||||||
|
.set(bevy::log::LogPlugin {
|
||||||
|
level: Level::INFO,
|
||||||
|
filter: "wgpu_hal=warn,bevy_learning=trace".to_string(),
|
||||||
|
// fmt_layer: |_| snake_game::define_log_layer(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.set(TaskPoolPlugin {
|
||||||
|
task_pool_options: TaskPoolOptions::with_num_threads(1),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.insert_resource(WinitSettings::desktop_app())
|
||||||
|
.insert_resource(ClearColor(Color::srgb(0.3, 0.6, 0.8)))
|
||||||
|
.add_systems(Startup, setup)
|
||||||
|
.add_systems(PostStartup, (print_all_entities, inspect))
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup(mut commands: Commands, _window: Query<&Window>, _world: &World) {
|
||||||
|
let _window = _window.single().unwrap();
|
||||||
|
|
||||||
|
let _root = commands
|
||||||
|
.spawn((
|
||||||
|
Sprite::from_color(Color::srgb(1., 1., 1.), Vec2::new(100., 100.)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(0., 0., 0.),
|
||||||
|
// scale: Vec3::new(1., 1., 1.),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.id();
|
||||||
|
let _red = commands
|
||||||
|
.spawn((
|
||||||
|
Sprite::from_color(Color::srgb(1., 0., 0.), Vec2::new(30., 30.)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(-20., 30., 0.),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ChildOf(_root),
|
||||||
|
))
|
||||||
|
.id();
|
||||||
|
let _blue = commands
|
||||||
|
.spawn((
|
||||||
|
Sprite::from_color(Color::srgb(0., 0., 1.), Vec2::new(20., 20.)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(20., 30., 0.),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ChildOf(_root),
|
||||||
|
))
|
||||||
|
.id();
|
||||||
|
|
||||||
|
commands.spawn(Camera2d);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_all_entities(mut commands: Commands, query: Query<Entity>) {
|
||||||
|
for entity in query {
|
||||||
|
commands.entity(entity).log_components();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inspect(mut _commands: Commands, _query: Query<Entity>) {}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
App::new().add_plugins(DefaultPlugins).add_plugins(HelloPlugin).run();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
struct Person;
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
struct Name(String);
|
||||||
|
|
||||||
|
#[derive(Resource)]
|
||||||
|
struct GreetTimer(Timer);
|
||||||
|
|
||||||
|
fn add_people(mut commands: Commands) {
|
||||||
|
commands.spawn((Person, Name("Elaina Proctor".to_string())));
|
||||||
|
commands.spawn((Person, Name("Renzo Hume".to_string())));
|
||||||
|
commands.spawn((Person, Name("Zaina Nieves".to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn greet_people(time: Res<Time>, mut timer: ResMut<GreetTimer>, query: Query<&Name, With<Person>>) {
|
||||||
|
// update uor timer with the time elapsed since the last update
|
||||||
|
// if that causes the timer to finish, we say hello to everyone
|
||||||
|
if timer.0.tick(time.delta()).just_finished() {
|
||||||
|
for name in &query {
|
||||||
|
info!("hello {}!", name.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_people(mut query: Query<&mut Name, With<Person>>) {
|
||||||
|
for mut name in &mut query {
|
||||||
|
if name.0 == "Elaina Proctor" {
|
||||||
|
name.0 = "Elaina Hume".to_string();
|
||||||
|
break; // We don't need to change any other names.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct HelloPlugin;
|
||||||
|
|
||||||
|
impl Plugin for HelloPlugin {
|
||||||
|
fn build(&self, app: &mut App) {
|
||||||
|
app.insert_resource(GreetTimer(Timer::from_seconds(2.0, TimerMode::Repeating)));
|
||||||
|
app.add_systems(Startup, add_people);
|
||||||
|
app.add_systems(Update, (update_people, greet_people).chain());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
//! Example of how to draw to a texture from the CPU.
|
||||||
|
//!
|
||||||
|
//! You can set the values of individual pixels to whatever you want.
|
||||||
|
//! Bevy provides user-friendly APIs that work with [`Color`]
|
||||||
|
//! values and automatically perform any necessary conversions and encoding
|
||||||
|
//! into the texture's native pixel format.
|
||||||
|
|
||||||
|
use bevy::asset::RenderAssetUsages;
|
||||||
|
use bevy::color::{color_difference::EuclideanDistance, palettes::css};
|
||||||
|
use bevy::prelude::*;
|
||||||
|
use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
|
||||||
|
use rand::{RngExt, SeedableRng};
|
||||||
|
use rand_chacha::ChaCha8Rng;
|
||||||
|
|
||||||
|
const IMAGE_WIDTH: u32 = 256;
|
||||||
|
const IMAGE_HEIGHT: u32 = 256;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
App::new()
|
||||||
|
.add_plugins(DefaultPlugins)
|
||||||
|
// In this example, we will use a fixed timestep to draw a pattern on the screen
|
||||||
|
// one pixel at a time, so the pattern will gradually emerge over time, and
|
||||||
|
// the speed at which it appears is not tied to the framerate.
|
||||||
|
// Let's make the fixed update very fast, so it doesn't take too long. :)
|
||||||
|
.insert_resource(Time::<Fixed>::from_hz(1024.0))
|
||||||
|
.add_systems(Startup, setup)
|
||||||
|
.add_systems(FixedUpdate, draw)
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Store the image handle that we will draw to, here.
|
||||||
|
#[derive(Resource)]
|
||||||
|
struct MyProcGenImage(Handle<Image>);
|
||||||
|
|
||||||
|
#[derive(Resource)]
|
||||||
|
struct SeededRng(ChaCha8Rng);
|
||||||
|
|
||||||
|
fn setup(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
|
||||||
|
commands.spawn(Camera2d);
|
||||||
|
|
||||||
|
// Create an image that we are going to draw into
|
||||||
|
let mut image = Image::new_fill(
|
||||||
|
// 2D image of size 256x256
|
||||||
|
Extent3d {
|
||||||
|
width: IMAGE_WIDTH,
|
||||||
|
height: IMAGE_HEIGHT,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
},
|
||||||
|
TextureDimension::D2,
|
||||||
|
// Initialize it with a beige color
|
||||||
|
&(css::BEIGE.to_u8_array()),
|
||||||
|
// Use the same encoding as the color we set
|
||||||
|
TextureFormat::Rgba8UnormSrgb,
|
||||||
|
RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD,
|
||||||
|
);
|
||||||
|
|
||||||
|
// To make it extra fancy, we can set the Alpha of each pixel,
|
||||||
|
// so that it fades out in a circular fashion.
|
||||||
|
for y in 0..IMAGE_HEIGHT {
|
||||||
|
for x in 0..IMAGE_WIDTH {
|
||||||
|
let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
|
||||||
|
let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
|
||||||
|
let r = Vec2::new(x as f32, y as f32).distance(center);
|
||||||
|
let a = 1.0 - (r / max_radius).clamp(0.0, 1.0);
|
||||||
|
|
||||||
|
// Here we will set the A value by accessing the raw data bytes.
|
||||||
|
// (it is the 4th byte of each pixel, as per our `TextureFormat`)
|
||||||
|
|
||||||
|
// Find our pixel by its coordinates
|
||||||
|
let pixel_bytes = image.pixel_bytes_mut(UVec3::new(x, y, 0)).unwrap();
|
||||||
|
// Convert our f32 to u8
|
||||||
|
pixel_bytes[3] = (a * u8::MAX as f32) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add it to Bevy's assets, so it can be used for rendering
|
||||||
|
// this will give us a handle we can use
|
||||||
|
// (to display it in a sprite, or as part of UI, etc.)
|
||||||
|
let handle = images.add(image);
|
||||||
|
|
||||||
|
// Create a sprite entity using our image
|
||||||
|
commands.spawn(Sprite::from_image(handle.clone()));
|
||||||
|
commands.insert_resource(MyProcGenImage(handle));
|
||||||
|
|
||||||
|
// We're seeding the PRNG here to make this example deterministic for testing purposes.
|
||||||
|
// This isn't strictly required in practical use unless you need your app to be deterministic.
|
||||||
|
let seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712);
|
||||||
|
commands.insert_resource(SeededRng(seeded_rng));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every fixed update tick, draw one more pixel to make a spiral pattern
|
||||||
|
fn draw(
|
||||||
|
my_handle: Res<MyProcGenImage>,
|
||||||
|
mut images: ResMut<Assets<Image>>,
|
||||||
|
// Used to keep track of where we are
|
||||||
|
mut i: Local<u32>,
|
||||||
|
mut draw_color: Local<Color>,
|
||||||
|
mut seeded_rng: ResMut<SeededRng>,
|
||||||
|
) {
|
||||||
|
if *i == 0 {
|
||||||
|
// Generate a random color on first run.
|
||||||
|
*draw_color = Color::linear_rgb(seeded_rng.0.random(), seeded_rng.0.random(), seeded_rng.0.random());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the image from Bevy's asset storage.
|
||||||
|
let image = images.get_mut(&my_handle.0).expect("Image not found");
|
||||||
|
|
||||||
|
// Compute the position of the pixel to draw.
|
||||||
|
|
||||||
|
let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
|
||||||
|
let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
|
||||||
|
let rot_speed = 0.0123;
|
||||||
|
let period = 0.12345;
|
||||||
|
|
||||||
|
let r = ops::sin(*i as f32 * period) * max_radius;
|
||||||
|
let xy = Vec2::from_angle(*i as f32 * rot_speed) * r + center;
|
||||||
|
let (x, y) = (xy.x as u32, xy.y as u32);
|
||||||
|
|
||||||
|
// Get the old color of that pixel.
|
||||||
|
let old_color = image.get_color_at(x, y).unwrap();
|
||||||
|
|
||||||
|
// If the old color is our current color, change our drawing color.
|
||||||
|
let tolerance = 1.0 / 255.0;
|
||||||
|
if old_color.distance(&draw_color) <= tolerance {
|
||||||
|
*draw_color = Color::linear_rgb(seeded_rng.0.random(), seeded_rng.0.random(), seeded_rng.0.random());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the new color, but keep old alpha value from image.
|
||||||
|
image.set_color_at(x, y, draw_color.with_alpha(old_color.alpha())).unwrap();
|
||||||
|
|
||||||
|
*i += 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
use bevy::{
|
||||||
|
platform::collections::{HashMap, HashSet},
|
||||||
|
prelude::*,
|
||||||
|
};
|
||||||
|
use rand::{RngExt, SeedableRng};
|
||||||
|
use rand_chacha::ChaCha8Rng;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
App::new()
|
||||||
|
.add_plugins(DefaultPlugins)
|
||||||
|
.init_resource::<SpatialIndex>()
|
||||||
|
.add_systems(Startup, setup)
|
||||||
|
.add_systems(Update, (draw_shapes, handle_click))
|
||||||
|
// Observers are systems that run when an event is "triggered". This observer runs whenever
|
||||||
|
// `ExplodeMines` is triggered.
|
||||||
|
.add_observer(
|
||||||
|
|explode_mines: On<ExplodeMines>, mines: Query<&Mine>, index: Res<SpatialIndex>, mut commands: Commands| {
|
||||||
|
// Access resources
|
||||||
|
for entity in index.get_nearby(explode_mines.pos) {
|
||||||
|
// Run queries
|
||||||
|
let mine = mines.get(entity).unwrap();
|
||||||
|
if mine.pos.distance(explode_mines.pos) < mine.size + explode_mines.radius {
|
||||||
|
// And queue commands, including triggering additional events
|
||||||
|
// Here we trigger the `Explode` event for entity `e`
|
||||||
|
commands.trigger(Explode { entity });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
// This observer runs whenever the `Mine` component is added to an entity, and places it in a simple spatial index.
|
||||||
|
.add_observer(on_add_mine)
|
||||||
|
// This observer runs whenever the `Mine` component is removed from an entity (including despawning it)
|
||||||
|
// and removes it from the spatial index.
|
||||||
|
.add_observer(on_remove_mine)
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
struct Mine {
|
||||||
|
pos: Vec2,
|
||||||
|
size: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mine {
|
||||||
|
fn random(rand: &mut ChaCha8Rng) -> Self {
|
||||||
|
Mine {
|
||||||
|
pos: Vec2::new((rand.random::<f32>() - 0.5) * 1200.0, (rand.random::<f32>() - 0.5) * 600.0),
|
||||||
|
size: 4.0 + rand.random::<f32>() * 16.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This is a normal [`Event`]. Any observer that watches for it will run when it is triggered.
|
||||||
|
#[derive(Event)]
|
||||||
|
struct ExplodeMines {
|
||||||
|
pos: Vec2,
|
||||||
|
radius: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An [`EntityEvent`] is a specialized type of [`Event`] that can target a specific entity. In addition to
|
||||||
|
/// running normal "top level" observers when it is triggered (which target _any_ entity that Explodes), it will
|
||||||
|
/// also run any observers that target the _specific_ entity for that event.
|
||||||
|
#[derive(EntityEvent)]
|
||||||
|
struct Explode {
|
||||||
|
entity: Entity,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup(mut commands: Commands) {
|
||||||
|
commands.spawn(Camera2d);
|
||||||
|
commands.spawn((
|
||||||
|
Text::new(
|
||||||
|
"Click on a \"Mine\" to trigger it.\n\
|
||||||
|
When it explodes it will trigger all overlapping mines.",
|
||||||
|
),
|
||||||
|
Node {
|
||||||
|
position_type: PositionType::Absolute,
|
||||||
|
top: px(12),
|
||||||
|
left: px(12),
|
||||||
|
..default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
|
||||||
|
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
|
||||||
|
|
||||||
|
commands
|
||||||
|
.spawn(Mine::random(&mut rng))
|
||||||
|
// Observers can watch for events targeting a specific entity.
|
||||||
|
// This will create a new observer that runs whenever the Explode event
|
||||||
|
// is triggered for this spawned entity.
|
||||||
|
.observe(explode_mine);
|
||||||
|
|
||||||
|
// We want to spawn a bunch of mines. We could just call the code above for each of them.
|
||||||
|
// That would create a new observer instance for every Mine entity. Having duplicate observers
|
||||||
|
// generally isn't worth worrying about as the overhead is low. But if you want to be maximally efficient,
|
||||||
|
// you can reuse observers across entities.
|
||||||
|
//
|
||||||
|
// First, observers are actually just entities with the Observer component! The `observe()` functions
|
||||||
|
// you've seen so far in this example are just shorthand for manually spawning an observer.
|
||||||
|
let mut observer = Observer::new(explode_mine);
|
||||||
|
|
||||||
|
// As we spawn entities, we can make this observer watch each of them:
|
||||||
|
for _ in 0..1000 {
|
||||||
|
let entity = commands.spawn(Mine::random(&mut rng)).id();
|
||||||
|
observer.watch_entity(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
// By spawning the Observer component, it becomes active!
|
||||||
|
commands.spawn(observer);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_add_mine(add: On<Add, Mine>, query: Query<&Mine>, mut index: ResMut<SpatialIndex>) {
|
||||||
|
let mine = query.get(add.entity).unwrap();
|
||||||
|
let tile = ((mine.pos.x / CELL_SIZE).floor() as i32, (mine.pos.y / CELL_SIZE).floor() as i32);
|
||||||
|
index.map.entry(tile).or_default().insert(add.entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove despawned mines from our index
|
||||||
|
fn on_remove_mine(remove: On<Remove, Mine>, query: Query<&Mine>, mut index: ResMut<SpatialIndex>) {
|
||||||
|
let mine = query.get(remove.entity).unwrap();
|
||||||
|
let tile = ((mine.pos.x / CELL_SIZE).floor() as i32, (mine.pos.y / CELL_SIZE).floor() as i32);
|
||||||
|
index.map.entry(tile).and_modify(|set| {
|
||||||
|
set.remove(&remove.entity);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn explode_mine(explode: On<Explode>, query: Query<&Mine>, mut commands: Commands) {
|
||||||
|
// Explode is an EntityEvent. `explode.entity` is the entity that Explode was triggered for.
|
||||||
|
let Ok(mut entity) = commands.get_entity(explode.entity) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
info!("Boom! {} exploded.", explode.entity);
|
||||||
|
entity.despawn();
|
||||||
|
let mine = query.get(explode.entity).unwrap();
|
||||||
|
// Trigger another explosion cascade.
|
||||||
|
commands.trigger(ExplodeMines {
|
||||||
|
pos: mine.pos,
|
||||||
|
radius: mine.size,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Draw a circle for each mine using `Gizmos`
|
||||||
|
fn draw_shapes(mut gizmos: Gizmos, mines: Query<&Mine>) {
|
||||||
|
for mine in &mines {
|
||||||
|
gizmos.circle_2d(mine.pos, mine.size, Color::hsl((mine.size - 4.0) / 16.0 * 360.0, 1.0, 0.8));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trigger `ExplodeMines` at the position of a given click
|
||||||
|
fn handle_click(
|
||||||
|
mouse_button_input: Res<ButtonInput<MouseButton>>,
|
||||||
|
camera: Single<(&Camera, &GlobalTransform)>,
|
||||||
|
windows: Query<&Window>,
|
||||||
|
mut commands: Commands,
|
||||||
|
) {
|
||||||
|
let Ok(windows) = windows.single() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let (camera, camera_transform) = *camera;
|
||||||
|
if let Some(pos) = windows
|
||||||
|
.cursor_position()
|
||||||
|
.and_then(|cursor| camera.viewport_to_world(camera_transform, cursor).ok())
|
||||||
|
.map(|ray| ray.origin.truncate())
|
||||||
|
&& mouse_button_input.just_pressed(MouseButton::Left)
|
||||||
|
{
|
||||||
|
commands.trigger(ExplodeMines { pos, radius: 1.0 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Resource, Default)]
|
||||||
|
struct SpatialIndex {
|
||||||
|
map: HashMap<(i32, i32), HashSet<Entity>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cell size has to be bigger than any `TriggerMine::radius`
|
||||||
|
const CELL_SIZE: f32 = 64.0;
|
||||||
|
|
||||||
|
impl SpatialIndex {
|
||||||
|
// Lookup all entities within adjacent cells of our spatial index
|
||||||
|
fn get_nearby(&self, pos: Vec2) -> Vec<Entity> {
|
||||||
|
let tile = ((pos.x / CELL_SIZE).floor() as i32, (pos.y / CELL_SIZE).floor() as i32);
|
||||||
|
let mut nearby = Vec::new();
|
||||||
|
for x in -1..2 {
|
||||||
|
for y in -1..2 {
|
||||||
|
if let Some(mines) = self.map.get(&(tile.0 + x, tile.1 + y)) {
|
||||||
|
nearby.extend(mines.iter());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nearby
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
use bevy::math::bounding::{Aabb2d, BoundingCircle, BoundingVolume, IntersectsVolume};
|
||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
App::new()
|
||||||
|
.add_plugins(DefaultPlugins)
|
||||||
|
.insert_resource(ClearColor(Color::srgb(0.8, 0.8, 1.0)))
|
||||||
|
.add_systems(Startup, setup)
|
||||||
|
.add_systems(FixedUpdate, (move_paddle, apply_velocity, check_for_collisions))
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
const PADDLE_GAP_Y: f32 = 50.0;
|
||||||
|
const PADDLE_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
|
||||||
|
const PADDLE_SIZE: Vec2 = Vec2::new(120.0, 20.0);
|
||||||
|
const PADDLE_SPEED: f32 = 500.0;
|
||||||
|
const PADDLE_PADDING: f32 = 10.0;
|
||||||
|
|
||||||
|
const LEFT_WALL: f32 = -600.0;
|
||||||
|
const RIGHT_WALL: f32 = 600.0;
|
||||||
|
const BOTTOM_WALL: f32 = -300.0;
|
||||||
|
const TOP_WALL: f32 = 300.0;
|
||||||
|
const WALL_WIDTH: f32 = 20.0;
|
||||||
|
|
||||||
|
const BALL_START_POS: Vec2 = Vec2::new(0.0, -100.0);
|
||||||
|
const BALL_COLOR: Color = Color::srgb(0.2, 0.5, 0.2);
|
||||||
|
const BALL_DIAMETER: f32 = 20.0;
|
||||||
|
const INIT_BALL_SPEED: Vec2 = Vec2::new(100.0, 100.0);
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
struct Paddle;
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
struct Ball;
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
struct Collider;
|
||||||
|
|
||||||
|
fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>) {
|
||||||
|
commands.spawn(Camera2d);
|
||||||
|
|
||||||
|
let paddle_y = BOTTOM_WALL + PADDLE_GAP_Y;
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(PADDLE_COLOR, Vec2::ONE),
|
||||||
|
Transform {
|
||||||
|
translation: Vec3::new(0.0, paddle_y, 0.0),
|
||||||
|
scale: PADDLE_SIZE.extend(1.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
Paddle,
|
||||||
|
Collider,
|
||||||
|
));
|
||||||
|
|
||||||
|
commands.spawn((
|
||||||
|
Mesh2d(meshes.add(Circle::default())),
|
||||||
|
MeshMaterial2d(materials.add(BALL_COLOR)),
|
||||||
|
Transform {
|
||||||
|
translation: BALL_START_POS.extend(0.0),
|
||||||
|
scale: Vec3::splat(BALL_DIAMETER),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
Velocity(INIT_BALL_SPEED),
|
||||||
|
Ball,
|
||||||
|
));
|
||||||
|
|
||||||
|
commands.spawn(Wall::new(WallLocation::Left));
|
||||||
|
commands.spawn(Wall::new(WallLocation::Right));
|
||||||
|
commands.spawn(Wall::new(WallLocation::Top));
|
||||||
|
commands.spawn(Wall::new(WallLocation::Bottom));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_paddle(input: Res<ButtonInput<KeyCode>>, time: Res<Time>, mut paddle_transform: Single<&mut Transform, With<Paddle>>) {
|
||||||
|
let direction = if input.pressed(KeyCode::ArrowLeft) {
|
||||||
|
-1.0
|
||||||
|
} else if input.pressed(KeyCode::ArrowRight) {
|
||||||
|
1.0
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
|
||||||
|
let new_pos = paddle_transform.translation.x + direction * PADDLE_SPEED * time.delta_secs();
|
||||||
|
|
||||||
|
const LEFT_BOUND: f32 = LEFT_WALL + WALL_WIDTH / 2.0 + PADDLE_SIZE.x / 2.0 + PADDLE_PADDING;
|
||||||
|
const RIGHT_BOUND: f32 = RIGHT_WALL - WALL_WIDTH / 2.0 - PADDLE_SIZE.x / 2.0 - PADDLE_PADDING;
|
||||||
|
|
||||||
|
paddle_transform.translation.x = new_pos.clamp(LEFT_BOUND, RIGHT_BOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Component, Deref, DerefMut)]
|
||||||
|
struct Velocity(Vec2);
|
||||||
|
|
||||||
|
fn apply_velocity(time: Res<Time>, mut query: Query<(&mut Transform, &Velocity)>) {
|
||||||
|
for (mut transform, velocity) in &mut query {
|
||||||
|
transform.translation += velocity.extend(0.0) * time.delta_secs();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_for_collisions(ball_query: Single<(&mut Velocity, &Transform), With<Ball>>, collider_query: Query<&Transform, With<Collider>>) {
|
||||||
|
let (mut ball_velocity, ball_transform) = ball_query.into_inner();
|
||||||
|
|
||||||
|
for collider_transform in &collider_query {
|
||||||
|
let collision = ball_collision(
|
||||||
|
BoundingCircle::new(ball_transform.translation.truncate(), BALL_DIAMETER / 2.0),
|
||||||
|
Aabb2d::new(collider_transform.translation.truncate(), collider_transform.scale.truncate() / 2.0),
|
||||||
|
);
|
||||||
|
|
||||||
|
if let Some(collision) = collision {
|
||||||
|
let mut reflect_x = false;
|
||||||
|
let mut reflect_y = false;
|
||||||
|
|
||||||
|
match collision {
|
||||||
|
Collision::Left => reflect_x = ball_velocity.x > 0.0,
|
||||||
|
Collision::Right => reflect_x = ball_velocity.x < 0.0,
|
||||||
|
Collision::Top => reflect_y = ball_velocity.y < 0.0,
|
||||||
|
Collision::Bottom => reflect_y = ball_velocity.y > 0.0,
|
||||||
|
};
|
||||||
|
|
||||||
|
if reflect_x {
|
||||||
|
ball_velocity.x *= -1.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if reflect_y {
|
||||||
|
ball_velocity.y *= -1.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Collision {
|
||||||
|
Left,
|
||||||
|
Right,
|
||||||
|
Top,
|
||||||
|
Bottom,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ball_collision(circle: BoundingCircle, rect: Aabb2d) -> Option<Collision> {
|
||||||
|
if !circle.intersects(&rect) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let closest = rect.closest_point(circle.center());
|
||||||
|
let offset = circle.center() - closest;
|
||||||
|
|
||||||
|
let side = if offset.x.abs() > offset.y.abs() {
|
||||||
|
if offset.x < 0.0 { Collision::Left } else { Collision::Right }
|
||||||
|
} else if offset.y > 0.0 {
|
||||||
|
Collision::Top
|
||||||
|
} else {
|
||||||
|
Collision::Bottom
|
||||||
|
};
|
||||||
|
|
||||||
|
Some(side)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
#[require(Sprite, Transform)]
|
||||||
|
struct Wall;
|
||||||
|
|
||||||
|
impl Wall {
|
||||||
|
pub fn new(location: WallLocation) -> (Wall, Sprite, Transform, Collider) {
|
||||||
|
(
|
||||||
|
Wall,
|
||||||
|
Sprite::from_color(Color::srgb(1.0, 0.4, 0.4), Vec2::ONE),
|
||||||
|
Transform {
|
||||||
|
translation: location.position().extend(0.0),
|
||||||
|
scale: location.size().extend(1.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
Collider,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum WallLocation {
|
||||||
|
Left,
|
||||||
|
Right,
|
||||||
|
Top,
|
||||||
|
Bottom,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WallLocation {
|
||||||
|
fn position(&self) -> Vec2 {
|
||||||
|
match self {
|
||||||
|
WallLocation::Left => Vec2::new(LEFT_WALL, 0.0),
|
||||||
|
WallLocation::Right => Vec2::new(RIGHT_WALL, 0.0),
|
||||||
|
WallLocation::Top => Vec2::new(0.0, TOP_WALL),
|
||||||
|
WallLocation::Bottom => Vec2::new(0.0, BOTTOM_WALL),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size(&self) -> Vec2 {
|
||||||
|
match self {
|
||||||
|
WallLocation::Left | WallLocation::Right => Vec2::new(WALL_WIDTH, TOP_WALL - BOTTOM_WALL),
|
||||||
|
WallLocation::Top | WallLocation::Bottom => Vec2::new(RIGHT_WALL - LEFT_WALL, WALL_WIDTH),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
App::new() //
|
||||||
|
.add_plugins(DefaultPlugins)
|
||||||
|
.add_systems(PreStartup, pre_startup)
|
||||||
|
.add_systems(Startup, (startup, setup))
|
||||||
|
.add_systems(PostStartup, post_startup)
|
||||||
|
.add_systems(First, first)
|
||||||
|
.add_systems(PreUpdate, pre_update)
|
||||||
|
.add_systems(Update, (update, check_space_pressed))
|
||||||
|
.add_systems(PostUpdate, post_update)
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pre_startup() {
|
||||||
|
info!("PreStartup");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn startup() {
|
||||||
|
info!("Startup");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn post_startup() {
|
||||||
|
info!("PostStartup");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first() {
|
||||||
|
info!("First");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pre_update() {
|
||||||
|
info!("PreUpdate");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update() {
|
||||||
|
info!("Update");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn post_update() {
|
||||||
|
info!("PostUpdate");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_space_pressed(input: Res<ButtonInput<KeyCode>>, mut commands: Commands) {
|
||||||
|
if input.just_pressed(KeyCode::Space) {
|
||||||
|
commands.trigger(TestEvent0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup(mut commands: Commands) {
|
||||||
|
commands.spawn((Observer::new(test_event_0_handler),));
|
||||||
|
commands.spawn((Observer::new(test_event_1_handler),));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Event, Debug)]
|
||||||
|
struct TestEvent0;
|
||||||
|
|
||||||
|
#[derive(Event, Debug)]
|
||||||
|
struct TestEvent1;
|
||||||
|
|
||||||
|
fn test_event_0_handler(event: On<TestEvent0>, mut commands: Commands) {
|
||||||
|
info!("handle {:?}", event.event());
|
||||||
|
commands.trigger(TestEvent1);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_event_1_handler(event: On<TestEvent1>, mut commands: Commands) {
|
||||||
|
info!("handle {:?}", event.event());
|
||||||
|
commands.trigger(TestEvent0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
//! An example that illustrates how Time is handled in ECS.
|
||||||
|
|
||||||
|
use bevy::{app::AppExit, prelude::*};
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
io::{self, BufRead},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn banner() {
|
||||||
|
println!("This example is meant to intuitively demonstrate how Time works in Bevy.");
|
||||||
|
println!();
|
||||||
|
println!("Time will be printed in three different schedules in the app:");
|
||||||
|
println!("- PreUpdate: real time is printed");
|
||||||
|
println!("- FixedUpdate: fixed time step time is printed, may be run zero or multiple times");
|
||||||
|
println!("- Update: virtual game time is printed");
|
||||||
|
println!();
|
||||||
|
println!("Max delta time is set to 5 seconds. Fixed timestep is set to 1 second.");
|
||||||
|
println!();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn help() {
|
||||||
|
println!("The app reads commands line-by-line from standard input.");
|
||||||
|
println!();
|
||||||
|
println!("Commands:");
|
||||||
|
println!(" empty line: Run app.update() once on the Bevy App");
|
||||||
|
println!(" q: Quit the app.");
|
||||||
|
println!(" f: Set speed to fast, 2x");
|
||||||
|
println!(" n: Set speed to normal, 1x");
|
||||||
|
println!(" s: Set speed to slow, 0.5x");
|
||||||
|
println!(" p: Pause");
|
||||||
|
println!(" u: Unpause");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runner(mut app: App) -> AppExit {
|
||||||
|
banner();
|
||||||
|
help();
|
||||||
|
let stdin = io::stdin();
|
||||||
|
for line in stdin.lock().lines() {
|
||||||
|
if let Err(err) = line {
|
||||||
|
println!("read err: {err:#}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
match line.unwrap().as_str() {
|
||||||
|
"" => {
|
||||||
|
app.update();
|
||||||
|
}
|
||||||
|
"f" => {
|
||||||
|
println!("FAST: setting relative speed to 2x");
|
||||||
|
app.world_mut().resource_mut::<Time<Virtual>>().set_relative_speed(2.0);
|
||||||
|
}
|
||||||
|
"n" => {
|
||||||
|
println!("NORMAL: setting relative speed to 1x");
|
||||||
|
app.world_mut().resource_mut::<Time<Virtual>>().set_relative_speed(1.0);
|
||||||
|
}
|
||||||
|
"s" => {
|
||||||
|
println!("SLOW: setting relative speed to 0.5x");
|
||||||
|
app.world_mut().resource_mut::<Time<Virtual>>().set_relative_speed(0.5);
|
||||||
|
}
|
||||||
|
"p" => {
|
||||||
|
println!("PAUSE: pausing virtual clock");
|
||||||
|
app.world_mut().resource_mut::<Time<Virtual>>().pause();
|
||||||
|
}
|
||||||
|
"u" => {
|
||||||
|
println!("UNPAUSE: resuming virtual clock");
|
||||||
|
app.world_mut().resource_mut::<Time<Virtual>>().unpause();
|
||||||
|
}
|
||||||
|
"q" => {
|
||||||
|
println!("QUITTING!");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
help();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
AppExit::Success
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_real_time(time: Res<Time<Real>>) {
|
||||||
|
println!(
|
||||||
|
"PreUpdate: this is real time clock, delta is {:?} and elapsed is {:?}",
|
||||||
|
time.delta(),
|
||||||
|
time.elapsed()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_fixed_time(time: Res<Time>) {
|
||||||
|
println!(
|
||||||
|
"FixedUpdate: this is generic time clock inside fixed, delta is {:?} and elapsed is {:?}",
|
||||||
|
time.delta(),
|
||||||
|
time.elapsed()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_time(time: Res<Time>) {
|
||||||
|
println!(
|
||||||
|
"Update: this is generic time clock, delta is {:?} and elapsed is {:?}",
|
||||||
|
time.delta(),
|
||||||
|
time.elapsed()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
App::new()
|
||||||
|
.add_plugins(MinimalPlugins)
|
||||||
|
.insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
|
||||||
|
.insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
|
||||||
|
.add_systems(PreUpdate, print_real_time)
|
||||||
|
.add_systems(FixedUpdate, print_fixed_time)
|
||||||
|
.add_systems(Update, print_time)
|
||||||
|
.set_runner(runner)
|
||||||
|
.run();
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
max_width = 160
|
||||||
|
newline_style = "Unix"
|
||||||
|
fn_single_line = true
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
use bevy::{color::palettes::tailwind::*, prelude::*};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
domain::{End, FIELD_SIZE, GRID_SIZE, Tail},
|
||||||
|
observers::schedule_set_velocity,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Создать границу игрового поля
|
||||||
|
pub fn spawn_bounds(commands: &mut Commands) {
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(AMBER_500, vec2((FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32, 5.0)), //
|
||||||
|
Transform {
|
||||||
|
translation: vec3(0.0, (FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32 / 2.0, 0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(AMBER_500, vec2((FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32, 5.0)), //
|
||||||
|
Transform {
|
||||||
|
translation: vec3(0.0, -(FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32 / 2.0, 0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(AMBER_500, vec2(5.0, (FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32)), //
|
||||||
|
Transform {
|
||||||
|
translation: vec3((FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32 / 2.0, 0.0, 0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(AMBER_500, vec2(5.0, (FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32)), //
|
||||||
|
Transform {
|
||||||
|
translation: vec3(-(FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32 / 2.0, 0.0, 0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Создать змейку
|
||||||
|
pub fn spawn_snake(commands: &mut Commands) {
|
||||||
|
use crate::domain::{Direction, HEAD_SIZE, Head, SNAKE_VELOCITY, Velocity};
|
||||||
|
|
||||||
|
let head = commands
|
||||||
|
.spawn((
|
||||||
|
Head(Direction::default()),
|
||||||
|
Direction::default(),
|
||||||
|
Velocity(SNAKE_VELOCITY as f32),
|
||||||
|
Sprite::from_color(Color::srgb(1., 1., 1.), vec2(HEAD_SIZE as f32, HEAD_SIZE as f32)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(0.0, 0.0, 1.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.id();
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(Color::srgb(1., 0., 0.), vec2(HEAD_SIZE as f32 * 0.3, HEAD_SIZE as f32 * 0.3)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(HEAD_SIZE as f32 * -0.25, HEAD_SIZE as f32 * 0.25, 1.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ChildOf(head),
|
||||||
|
));
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(Color::srgb(0., 0., 1.), vec2(HEAD_SIZE as f32 * 0.2, HEAD_SIZE as f32 * 0.2)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(HEAD_SIZE as f32 * 0.25, HEAD_SIZE as f32 * 0.25, 1.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ChildOf(head),
|
||||||
|
));
|
||||||
|
|
||||||
|
let tail = commands
|
||||||
|
.spawn((
|
||||||
|
Tail(head),
|
||||||
|
End,
|
||||||
|
Direction::default(),
|
||||||
|
Velocity(0.0),
|
||||||
|
Sprite::from_color(YELLOW_500, vec2(HEAD_SIZE as f32 * 0.8, HEAD_SIZE as f32 * 0.8)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(0.0, 0.0, 0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.id();
|
||||||
|
commands.entity(head).observe(schedule_set_velocity(tail));
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
//! модуль с инструментами отладки
|
||||||
|
#![allow(unused)]
|
||||||
|
|
||||||
|
use bevy::{color::palettes::tailwind::*, prelude::*};
|
||||||
|
|
||||||
|
use crate::domain::{Collision, GridBarier, GrowUp, Meal, Position};
|
||||||
|
|
||||||
|
/// вывод всех сущностей мира
|
||||||
|
pub fn print_all_entities(mut commands: Commands, query: Query<Entity>) {
|
||||||
|
for entity in query {
|
||||||
|
commands.entity(entity).log_components();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// вывод всех сущностей мира по нажатию Enter
|
||||||
|
pub fn print_all_entities_by_press_enter(input: Res<ButtonInput<KeyCode>>, mut commands: Commands, query: Query<Entity>) {
|
||||||
|
if input.just_pressed(KeyCode::Enter) {
|
||||||
|
for entity in query {
|
||||||
|
commands.entity(entity).log_components();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Замедлить время и поставить на паузу
|
||||||
|
pub fn set_initial_time_speed_to_slow(mut time: ResMut<Time<Virtual>>) {
|
||||||
|
time.set_relative_speed(1.0 / 8.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// обертка над функцией [crate::tools::split_by_grid] для ее отладки
|
||||||
|
pub fn _split_by_grid_tracing(src: f32, dst: f32, grid: f32) -> Vec<(f32, f32)> {
|
||||||
|
let result = crate::tools::split_by_grid(src, dst, grid);
|
||||||
|
trace!("\tsplit_by_grid({:?}, {:?}, {:?}) -> {:?}", src, dst, grid, result);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Координатная сетка
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct Grid;
|
||||||
|
|
||||||
|
/// Создать координатную сетку
|
||||||
|
pub fn spawn_grid(commands: &mut Commands) {
|
||||||
|
use crate::domain::GRID_SIZE;
|
||||||
|
|
||||||
|
let grid = commands.spawn((Grid, Transform::default(), Visibility::default())).id();
|
||||||
|
|
||||||
|
for x in -20..=20 {
|
||||||
|
let color = if x % 5 == 0 { Color::srgb(1.0, 0.2, 0.5) } else { Color::srgb(1.0, 1.0, 0.5) };
|
||||||
|
let weight = if x % 5 == 0 { 1.0 } else { 0.5 };
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(color, vec2(weight, 2000.0)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(x as f32 * GRID_SIZE as f32, 0.0, -1.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ChildOf(grid),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
for y in -20..=20 {
|
||||||
|
let color = if y % 5 == 0 { Color::srgb(1.0, 0.2, 0.5) } else { Color::srgb(1.0, 1.0, 0.5) };
|
||||||
|
let weight = if y % 5 == 0 { 1.0 } else { 0.5 };
|
||||||
|
commands.spawn((
|
||||||
|
Sprite::from_color(color, vec2(2000.0, weight)),
|
||||||
|
Transform {
|
||||||
|
translation: vec3(0.0, y as f32 * GRID_SIZE as f32, -1.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ChildOf(grid),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// трассировка движения змеи
|
||||||
|
pub fn trace_snake_moving(e: On<GridBarier>) {
|
||||||
|
let entity = e.entity;
|
||||||
|
let position = e.position;
|
||||||
|
let direction = e.direction;
|
||||||
|
trace!("...<{entity:?}> is moving on {position} {direction:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// событие [GrowUp] по нажатию Tab
|
||||||
|
pub fn grow_up_on_tab(input: Res<ButtonInput<KeyCode>>, mut commands: Commands) {
|
||||||
|
if input.just_pressed(KeyCode::Tab) {
|
||||||
|
commands.trigger(GrowUp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Трасировка столкновений
|
||||||
|
pub fn trace_collisions(event: On<Collision>) {
|
||||||
|
trace!("collision detected: {event:?}")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn_some_meal(commands: &mut Commands) {
|
||||||
|
commands.spawn((
|
||||||
|
Meal,
|
||||||
|
Sprite::from_color(YELLOW_200, vec2(40.0, 40.0)), //
|
||||||
|
Transform {
|
||||||
|
translation: Position::new(5, 7).translation().extend(0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
commands.spawn((
|
||||||
|
Meal,
|
||||||
|
Sprite::from_color(YELLOW_200, vec2(40.0, 40.0)), //
|
||||||
|
Transform {
|
||||||
|
translation: Position::new(-3, -5).translation().extend(0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
commands.spawn((
|
||||||
|
Meal,
|
||||||
|
Sprite::from_color(YELLOW_200, vec2(40.0, 40.0)), //
|
||||||
|
Transform {
|
||||||
|
translation: Position::new(4, -5).translation().extend(0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
commands.spawn((
|
||||||
|
Meal,
|
||||||
|
Sprite::from_color(YELLOW_200, vec2(40.0, 40.0)), //
|
||||||
|
Transform {
|
||||||
|
translation: Position::new(-5, 6).translation().extend(0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
mod direction;
|
||||||
|
pub use direction::Direction;
|
||||||
|
|
||||||
|
mod events;
|
||||||
|
pub use events::{Collision, GridBarier, GrowUp};
|
||||||
|
|
||||||
|
mod snake_path;
|
||||||
|
pub use snake_path::SnakePath;
|
||||||
|
|
||||||
|
mod position;
|
||||||
|
pub use position::Position;
|
||||||
|
|
||||||
|
pub const GRID_SIZE: u8 = 32;
|
||||||
|
pub const HEAD_SIZE: u8 = (GRID_SIZE as f32 * 1.1).ceil() as u8;
|
||||||
|
pub const SNAKE_VELOCITY: u8 = (GRID_SIZE as f32 * 3.0).ceil() as u8;
|
||||||
|
pub const FIELD_SIZE: u8 = 20;
|
||||||
|
pub const MAX_MEALS_ON_FIELD: u8 = 5;
|
||||||
|
pub const MEAL_SIZE: u8 = (GRID_SIZE as f32 * 0.75).ceil() as u8;
|
||||||
|
|
||||||
|
/// Голова змеи
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct Head(pub Direction);
|
||||||
|
|
||||||
|
/// Сегмент змеиного хвоста
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct Tail(pub Entity);
|
||||||
|
|
||||||
|
/// Конец змеиного хвоста
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct End;
|
||||||
|
|
||||||
|
/// Скорость движения
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct Velocity(pub f32);
|
||||||
|
|
||||||
|
/// Еда
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct Meal;
|
||||||
|
|
||||||
|
/// Таймер респавна еды
|
||||||
|
#[derive(Resource, Deref, DerefMut)]
|
||||||
|
pub struct MealRespawnTimer(Timer);
|
||||||
|
|
||||||
|
impl MealRespawnTimer {
|
||||||
|
pub fn new(period: f32) -> Self {
|
||||||
|
Self(Timer::from_seconds(period, TimerMode::Repeating))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
/// Направление движения
|
||||||
|
#[derive(Component, PartialEq, Clone, Copy, Debug, Default)]
|
||||||
|
pub enum Direction {
|
||||||
|
#[default]
|
||||||
|
Up,
|
||||||
|
Left,
|
||||||
|
Down,
|
||||||
|
Right,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Direction {
|
||||||
|
/// Поворот налево
|
||||||
|
pub fn rotate_left(&mut self) {
|
||||||
|
*self = match self {
|
||||||
|
Direction::Up => Direction::Left,
|
||||||
|
Direction::Left => Direction::Down,
|
||||||
|
Direction::Down => Direction::Right,
|
||||||
|
Direction::Right => Direction::Up,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Поворот направо
|
||||||
|
pub fn rotate_right(&mut self) {
|
||||||
|
*self = match self {
|
||||||
|
Direction::Up => Direction::Right,
|
||||||
|
Direction::Right => Direction::Down,
|
||||||
|
Direction::Down => Direction::Left,
|
||||||
|
Direction::Left => Direction::Up,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Получить значение кооринаты соответствующей направлению движения
|
||||||
|
pub fn get_coord(&self, vec: &Transform) -> f32 {
|
||||||
|
match self {
|
||||||
|
Direction::Up | Direction::Down => vec.translation.y,
|
||||||
|
Direction::Left | Direction::Right => vec.translation.x,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Получить знак изменения соответствующий направлению движения
|
||||||
|
pub fn get_change_sign(&self) -> f32 {
|
||||||
|
match self {
|
||||||
|
Direction::Up | Direction::Right => 1.0,
|
||||||
|
Direction::Down | Direction::Left => -1.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Установить значение кооринаты соответствующей направлению движения
|
||||||
|
pub fn set_coord(&self, vec: &mut Transform, value: f32) {
|
||||||
|
match self {
|
||||||
|
Direction::Up | Direction::Down => vec.translation.y = value,
|
||||||
|
Direction::Left | Direction::Right => vec.translation.x = value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Получить ориентацию в пространстве
|
||||||
|
pub fn orientation(&self) -> Quat {
|
||||||
|
use std::f32::consts::PI;
|
||||||
|
|
||||||
|
match self {
|
||||||
|
Direction::Up => Quat::default(),
|
||||||
|
Direction::Left => Quat::from_rotation_z(PI / 2.0),
|
||||||
|
Direction::Down => Quat::from_rotation_z(PI),
|
||||||
|
Direction::Right => Quat::from_rotation_z(-PI / 2.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for Direction {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Direction::Up => write!(f, "Up"),
|
||||||
|
Direction::Left => write!(f, "Left"),
|
||||||
|
Direction::Down => write!(f, "Down"),
|
||||||
|
Direction::Right => write!(f, "Right"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
use crate::domain::{Direction, Position};
|
||||||
|
|
||||||
|
/// Событие прохождения границы сетки
|
||||||
|
#[derive(EntityEvent)]
|
||||||
|
pub struct GridBarier {
|
||||||
|
pub entity: Entity,
|
||||||
|
pub position: Position,
|
||||||
|
pub direction: Direction,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GridBarier {
|
||||||
|
pub fn new(entity: Entity, position: Position, direction: Direction) -> Self {
|
||||||
|
Self { entity, position, direction }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Событие роста змеи
|
||||||
|
#[derive(Event)]
|
||||||
|
pub struct GrowUp;
|
||||||
|
|
||||||
|
/// Событие столкновения змеи
|
||||||
|
#[derive(Event, Debug)]
|
||||||
|
pub enum Collision {
|
||||||
|
Bounds,
|
||||||
|
Tail,
|
||||||
|
Meal(Entity),
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
use std::{fmt::Display, ops::Deref};
|
||||||
|
|
||||||
|
use bevy::{
|
||||||
|
math::{Vec2, vec2},
|
||||||
|
transform::components::Transform,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::domain::GRID_SIZE;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub struct Position {
|
||||||
|
pub x: i8,
|
||||||
|
pub y: i8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Position {
|
||||||
|
pub fn new(x: i8, y: i8) -> Self {
|
||||||
|
Self { x, y }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn translation(&self) -> Vec2 {
|
||||||
|
vec2(self.x as f32 * GRID_SIZE as f32, self.y as f32 * GRID_SIZE as f32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Position {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "(x:{}, y:{})", self.x, self.y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Deref<Target = Transform>> From<T> for Position {
|
||||||
|
fn from(value: T) -> Self {
|
||||||
|
Self {
|
||||||
|
x: (value.translation.x / GRID_SIZE as f32).floor() as i8,
|
||||||
|
y: (value.translation.y / GRID_SIZE as f32).floor() as i8,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use crate::domain::{Direction, Position};
|
||||||
|
|
||||||
|
/// Путь змеи
|
||||||
|
#[derive(Resource, Default, Deref, DerefMut)]
|
||||||
|
pub struct SnakePath(HashMap<Position, Direction>);
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use bevy::{color::palettes::tailwind::*, prelude::*};
|
||||||
|
use rand::RngExt;
|
||||||
|
|
||||||
|
use crate::{domain::*, tools::split_by_grid};
|
||||||
|
|
||||||
|
/// Общая механика движения
|
||||||
|
fn moving(
|
||||||
|
velocity: &f32,
|
||||||
|
time: &Time<Fixed>,
|
||||||
|
direction: &mut Direction,
|
||||||
|
transform: &mut Transform,
|
||||||
|
entity: Entity,
|
||||||
|
commands: &mut Commands,
|
||||||
|
switch_direction: impl FnOnce(Position) -> Option<Direction>,
|
||||||
|
) {
|
||||||
|
// первая часть движения - до границы сетки
|
||||||
|
let delta = velocity * time.delta_secs();
|
||||||
|
let src = direction.get_coord(transform);
|
||||||
|
let sign = direction.get_change_sign();
|
||||||
|
let dst = src + sign * delta;
|
||||||
|
let mut splited = split_by_grid(src, dst, GRID_SIZE as f32).into_iter();
|
||||||
|
let first = splited.next().unwrap_or((0.0, 0.0));
|
||||||
|
direction.set_coord(transform, first.0);
|
||||||
|
|
||||||
|
// вторая часть движения - после границы сетки
|
||||||
|
if let Some(second) = splited.next() {
|
||||||
|
let delta = second.1.abs();
|
||||||
|
let pos = Position::from(&*transform);
|
||||||
|
if let Some(dir) = switch_direction(pos) {
|
||||||
|
trace!("set new direction for {entity} in {pos} --> {dir}");
|
||||||
|
*direction = dir;
|
||||||
|
}
|
||||||
|
let src = direction.get_coord(&*transform);
|
||||||
|
let sign = direction.get_change_sign();
|
||||||
|
let dst = src + sign * delta;
|
||||||
|
direction.set_coord(transform, dst);
|
||||||
|
|
||||||
|
// создать событие прохождения границы сетки
|
||||||
|
commands.entity(entity).trigger(|e| GridBarier::new(e, pos, *direction));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Система движения головы змеи
|
||||||
|
pub fn head_moving(
|
||||||
|
query: Query<(&mut Transform, &mut Direction, &Velocity, &Head, Entity)>,
|
||||||
|
time: Res<Time<Fixed>>,
|
||||||
|
mut snake_path: ResMut<SnakePath>,
|
||||||
|
mut commands: Commands,
|
||||||
|
) {
|
||||||
|
let _span = trace_span!("head_moving").entered();
|
||||||
|
for (mut transform, mut direction, Velocity(velocity), head, entity) in query.into_iter() {
|
||||||
|
let next_dir = head.0;
|
||||||
|
let dir = *direction;
|
||||||
|
let snake_path = &mut snake_path;
|
||||||
|
let switch_direction = move |pos: Position| {
|
||||||
|
if next_dir != dir {
|
||||||
|
snake_path.insert(pos, next_dir);
|
||||||
|
Some(next_dir)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
moving(velocity, &time, &mut direction, &mut transform, entity, &mut commands, switch_direction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
/// Система движения тела змеи
|
||||||
|
pub fn snake_moving(
|
||||||
|
query: Query<(&mut Transform, &mut Direction, &Velocity, Entity), (With<Tail>, Without<Head>)>,
|
||||||
|
time: Res<Time<Fixed>>,
|
||||||
|
snake_path: Res<SnakePath>,
|
||||||
|
mut commands: Commands,
|
||||||
|
) {
|
||||||
|
let _span = trace_span!("snake_moving").entered();
|
||||||
|
for (mut transform, mut direction, Velocity(velocity), entity) in query.into_iter() {
|
||||||
|
let snake_path = &snake_path;
|
||||||
|
let switch_direction = move |pos: Position| snake_path.get(&pos).cloned();
|
||||||
|
moving(velocity, &time, &mut direction, &mut transform, entity, &mut commands, switch_direction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Система спавна еды при необходимости
|
||||||
|
pub fn spawn_meal_if_needed(
|
||||||
|
time: Res<Time<Fixed>>, //
|
||||||
|
mut meal_timer: ResMut<MealRespawnTimer>,
|
||||||
|
query: Query<&Transform, With<Meal>>,
|
||||||
|
mut commands: Commands,
|
||||||
|
) {
|
||||||
|
if meal_timer.tick(time.elapsed()).just_finished() && query.count() < MAX_MEALS_ON_FIELD as usize {
|
||||||
|
let used_positions = query.iter().map(Position::from).collect::<HashSet<Position>>();
|
||||||
|
let mut rng = rand::rng();
|
||||||
|
let pos = loop {
|
||||||
|
const ABS: i8 = (FIELD_SIZE as f32 / 2.0) as i8;
|
||||||
|
let rand_x = rng.random::<i8>() % ABS;
|
||||||
|
let rand_y = rng.random::<i8>() % ABS;
|
||||||
|
let rand_pos = Position::new(rand_x, rand_y);
|
||||||
|
if !used_positions.contains(&rand_pos) {
|
||||||
|
break rand_pos;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
commands.spawn((
|
||||||
|
Meal,
|
||||||
|
Sprite::from_color(YELLOW_400, vec2(MEAL_SIZE as f32, MEAL_SIZE as f32)), //
|
||||||
|
Transform {
|
||||||
|
translation: pos.translation().extend(0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
trace!("new meal spawned at {pos}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
pub struct SnakeGame;
|
||||||
|
|
||||||
|
impl Plugin for SnakeGame {
|
||||||
|
fn build(&self, app: &mut bevy::app::App) {
|
||||||
|
app.add_plugins(
|
||||||
|
DefaultPlugins
|
||||||
|
.build()
|
||||||
|
.set(bevy::log::LogPlugin {
|
||||||
|
level: tracing::Level::INFO,
|
||||||
|
filter: "wgpu_hal=warn,snake_game=trace".to_string(),
|
||||||
|
fmt_layer: |_| crate::tools::define_log_layer(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.set(TaskPoolPlugin {
|
||||||
|
task_pool_options: TaskPoolOptions::with_num_threads(1),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
app.add_systems(Startup, crate::startup::setup_window);
|
||||||
|
app.add_systems(Startup, crate::startup::setup_time);
|
||||||
|
app.add_systems(Startup, crate::startup::pause_on_startup);
|
||||||
|
app.add_systems(Startup, crate::startup::startup);
|
||||||
|
|
||||||
|
app.add_systems(Update, crate::update::head_rotation);
|
||||||
|
app.add_systems(Update, crate::update::time_speed);
|
||||||
|
|
||||||
|
app.add_systems(PostUpdate, crate::post_update::check_bounds_colisions);
|
||||||
|
app.add_systems(PostUpdate, crate::post_update::check_tail_colisions);
|
||||||
|
app.add_systems(PostUpdate, crate::post_update::check_meal_collisions);
|
||||||
|
|
||||||
|
app.add_systems(FixedUpdate, crate::fixed_update::head_moving);
|
||||||
|
app.add_systems(FixedUpdate, crate::fixed_update::snake_moving);
|
||||||
|
app.add_systems(FixedUpdate, crate::fixed_update::spawn_meal_if_needed);
|
||||||
|
|
||||||
|
// DEBUG:
|
||||||
|
|
||||||
|
// app.add_systems(Startup, crate::debug::set_initial_time_speed_to_slow);
|
||||||
|
// app.add_systems(PostStartup, crate::debug::print_all_entities);
|
||||||
|
// app.add_systems(Update, crate::debug::grow_up_on_tab);
|
||||||
|
// app.add_systems(Update, crate::debug::print_all_entities_by_press_enter);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
mod core;
|
||||||
|
mod debug;
|
||||||
|
mod domain;
|
||||||
|
mod fixed_update;
|
||||||
|
mod game;
|
||||||
|
mod observers;
|
||||||
|
mod post_update;
|
||||||
|
mod startup;
|
||||||
|
mod tools;
|
||||||
|
mod update;
|
||||||
|
|
||||||
|
pub use game::SnakeGame;
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
fn main() {
|
fn main() {
|
||||||
println!("Hello, world!");
|
bevy::app::App::new().add_plugins(snake_game::SnakeGame).run();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
use crate::domain::*;
|
||||||
|
|
||||||
|
use bevy::{color::palettes::tailwind::*, prelude::*};
|
||||||
|
|
||||||
|
/// Запланировать установку скорости движения [Velocity] при следующем событии [GridBarier]
|
||||||
|
pub fn schedule_set_velocity(tail: Entity) -> impl Fn(On<GridBarier>, Commands, Query<(&mut Velocity, &Transform)>) {
|
||||||
|
move |event: On<GridBarier>, mut commands: Commands, mut query: Query<(&mut Velocity, &Transform)>| {
|
||||||
|
if let Ok((mut velocity, transform)) = query.get_mut(tail) {
|
||||||
|
let position = Position::from(transform);
|
||||||
|
if event.position != position {
|
||||||
|
velocity.0 = SNAKE_VELOCITY as f32;
|
||||||
|
commands.entity(event.observer()).despawn();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Очистка [SnakePath] от старых значений
|
||||||
|
pub fn clean_snake_path(event: On<GridBarier>, query: Query<&End>, mut snake_path: ResMut<SnakePath>) {
|
||||||
|
if query.contains(event.entity) {
|
||||||
|
let v = snake_path.remove(&event.position);
|
||||||
|
trace!("clean_snake_path: removed {v:?} for {}", &event.position);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Обработка события [GrowUp]
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
pub fn grow_up_snake(_: On<GrowUp>, mut commands: Commands, query: Single<(Entity, &Direction, &Transform, &mut Sprite), (With<Tail>, With<End>)>) {
|
||||||
|
let (entity, direction, transform, mut sprite) = query.into_inner();
|
||||||
|
sprite.color = GRAY_300.into();
|
||||||
|
commands.entity(entity).remove::<End>();
|
||||||
|
let pos = Position::from(transform);
|
||||||
|
let new_end = commands
|
||||||
|
.spawn((
|
||||||
|
Tail(entity),
|
||||||
|
End,
|
||||||
|
*direction,
|
||||||
|
Velocity(0.0),
|
||||||
|
Sprite::from_color(YELLOW_500, vec2(HEAD_SIZE as f32 * 0.8, HEAD_SIZE as f32 * 0.8)),
|
||||||
|
Transform {
|
||||||
|
translation: pos.translation().extend(0.0),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.id();
|
||||||
|
commands.entity(entity).observe(schedule_set_velocity(new_end));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Обработка столкновений
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
pub fn handle_collisions(
|
||||||
|
event: On<Collision>, //
|
||||||
|
query: Query<(&mut Velocity, &mut Sprite), Or<(With<Head>, With<Tail>, With<End>)>>,
|
||||||
|
mut commands: Commands,
|
||||||
|
) {
|
||||||
|
match event.event() {
|
||||||
|
Collision::Meal(entity) => {
|
||||||
|
commands.entity(*entity).despawn();
|
||||||
|
commands.trigger(GrowUp);
|
||||||
|
}
|
||||||
|
Collision::Bounds | Collision::Tail => {
|
||||||
|
for (mut velocity, mut sprite) in query.into_iter() {
|
||||||
|
velocity.0 = 0.0;
|
||||||
|
sprite.color = RED_300.into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
use crate::domain::*;
|
||||||
|
|
||||||
|
/// Система отслеживания столкновений с границей
|
||||||
|
pub fn check_bounds_colisions(
|
||||||
|
head: Single<(&Transform,), (With<Head>,)>,
|
||||||
|
mut commands: Commands, //
|
||||||
|
) {
|
||||||
|
let (head_transform,) = head.into_inner();
|
||||||
|
let (x, y) = (head_transform.translation.x, head_transform.translation.y);
|
||||||
|
const SIDE: f32 = (FIELD_SIZE as f32 / 2.0) * GRID_SIZE as f32;
|
||||||
|
if !(-SIDE..=SIDE).contains(&x) || !(-SIDE..=SIDE).contains(&y) {
|
||||||
|
commands.trigger(Collision::Bounds);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Система отслеживания столкновений c хвостом
|
||||||
|
pub fn check_tail_colisions(
|
||||||
|
head: Single<(&Transform, Entity), (With<Head>,)>,
|
||||||
|
query: Query<(&Transform, &Velocity, &Tail)>,
|
||||||
|
mut commands: Commands, //
|
||||||
|
) {
|
||||||
|
let (head_transform, head_entity) = head.into_inner();
|
||||||
|
for (tail_transform, velocity, tail) in query.into_iter() {
|
||||||
|
if velocity.0 == 0.0 || tail.0 == head_entity {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let distance = head_transform.translation.distance(tail_transform.translation);
|
||||||
|
if distance < GRID_SIZE as f32 {
|
||||||
|
commands.trigger(Collision::Tail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Система отслеживания столкновений с едой
|
||||||
|
pub fn check_meal_collisions(
|
||||||
|
head: Single<(&Transform,), (With<Head>,)>,
|
||||||
|
query: Query<(&Transform, Entity), (With<Meal>,)>,
|
||||||
|
mut commands: Commands, //
|
||||||
|
) {
|
||||||
|
let (head_transform,) = head.into_inner();
|
||||||
|
for (meal_transform, meal_entity) in query.into_iter() {
|
||||||
|
let distance = head_transform.translation.distance(meal_transform.translation);
|
||||||
|
if distance < GRID_SIZE as f32 {
|
||||||
|
commands.trigger(Collision::Meal(meal_entity));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
use bevy::{color::palettes::tailwind::*, prelude::*};
|
||||||
|
|
||||||
|
use crate::domain::{FIELD_SIZE, GRID_SIZE, MealRespawnTimer, SnakePath};
|
||||||
|
|
||||||
|
/// Настройка игрового окна
|
||||||
|
pub fn setup_window(mut window: Single<&mut Window>) {
|
||||||
|
window.resolution.set(
|
||||||
|
(FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32 + 20.0,
|
||||||
|
(FIELD_SIZE as f32 + 1.0) * GRID_SIZE as f32 + 20.0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Настройка игрового времени
|
||||||
|
pub fn setup_time(mut time: ResMut<Time<Fixed>>) {
|
||||||
|
time.set_timestep_hz(32.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Начать с паузы
|
||||||
|
pub fn pause_on_startup(mut time: ResMut<Time<Virtual>>) {
|
||||||
|
time.pause();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Инициализация игрового мира
|
||||||
|
pub fn startup(mut commands: Commands) {
|
||||||
|
commands.insert_resource(ClearColor(SKY_600.into()));
|
||||||
|
commands.insert_resource(SnakePath::default());
|
||||||
|
commands.insert_resource(MealRespawnTimer::new(2.0));
|
||||||
|
|
||||||
|
commands.spawn(Observer::new(crate::observers::clean_snake_path));
|
||||||
|
commands.spawn(Observer::new(crate::observers::grow_up_snake));
|
||||||
|
commands.spawn(Observer::new(crate::observers::handle_collisions));
|
||||||
|
|
||||||
|
crate::core::spawn_bounds(&mut commands);
|
||||||
|
crate::core::spawn_snake(&mut commands);
|
||||||
|
|
||||||
|
commands.spawn(Camera2d);
|
||||||
|
|
||||||
|
// DEBUG:
|
||||||
|
|
||||||
|
// commands.spawn(Observer::new(crate::debug::trace_collisions));
|
||||||
|
// commands.spawn(Observer::new(crate::debug::trace_snake_moving));
|
||||||
|
|
||||||
|
// crate::debug::spawn_grid(&mut commands);
|
||||||
|
// crate::debug::spawn_some_meal(&mut commands);
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
/// Инициализация логирования
|
||||||
|
pub fn define_log_layer() -> Option<bevy::log::BoxedFmtLayer> {
|
||||||
|
use std::fs::File;
|
||||||
|
use tracing::Level;
|
||||||
|
use tracing_subscriber::{Layer, filter::Targets, fmt::layer};
|
||||||
|
|
||||||
|
let targets = Targets::new().with_default(Level::TRACE);
|
||||||
|
|
||||||
|
let stdout = layer()
|
||||||
|
.compact()
|
||||||
|
.with_thread_names(true)
|
||||||
|
.with_file(false)
|
||||||
|
.with_line_number(false)
|
||||||
|
.with_filter(targets.clone())
|
||||||
|
.boxed();
|
||||||
|
let file = match File::options().create(true).append(true).open("snake-game.log") {
|
||||||
|
Ok(file) => file,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("No access to log file: {:?}", e);
|
||||||
|
return Some(stdout);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let log_file = layer()
|
||||||
|
.compact()
|
||||||
|
.with_ansi(false)
|
||||||
|
.with_thread_names(true)
|
||||||
|
.with_file(false)
|
||||||
|
.with_line_number(false)
|
||||||
|
.with_writer(file)
|
||||||
|
.with_filter(targets.clone())
|
||||||
|
.boxed();
|
||||||
|
Some(Box::new(vec![stdout, log_file]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Разбиение изменения координаты по границам сетки
|
||||||
|
/// Элементы выходного вектора представляют пары значений, где первое обозначает промежуточное значение координаты,
|
||||||
|
/// а второе - изменение координаты относительно предыдущего значения (дельта).
|
||||||
|
/// Если движение начинается на границе сетки и оно не нулевое (начальное и конечное значение координвты отличаются),
|
||||||
|
/// то размер выходного вектора всегда больше 1 и второе значение первой пары (дельта) равно 0.
|
||||||
|
/// На основе этой логики происходит в дальнейшем распознавание момента прохождения узла сетки и генерируется соответствующее событие.
|
||||||
|
pub fn split_by_grid(src: f32, dst: f32, grid: f32) -> Vec<(f32, f32)> {
|
||||||
|
if dst == src {
|
||||||
|
return vec![(dst, 0.0)];
|
||||||
|
}
|
||||||
|
if grid <= 0.0 {
|
||||||
|
return vec![(dst, dst - src)];
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut output = Vec::with_capacity(2);
|
||||||
|
if src < dst {
|
||||||
|
let src_grid = src / grid;
|
||||||
|
let dst_grid = dst / grid;
|
||||||
|
|
||||||
|
let src_grid_right = src_grid.ceil();
|
||||||
|
let dst_grid_left = dst_grid.floor();
|
||||||
|
|
||||||
|
let mut src: f32 = src;
|
||||||
|
for step in src_grid_right as i32..=dst_grid_left as i32 {
|
||||||
|
let step = step as f32 * grid;
|
||||||
|
output.push((step, step - src));
|
||||||
|
src = step;
|
||||||
|
}
|
||||||
|
if src != dst {
|
||||||
|
output.push((dst, dst - src));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let src_grid = src / grid;
|
||||||
|
let dst_grid = dst / grid;
|
||||||
|
|
||||||
|
let dst_grid_right = dst_grid.ceil();
|
||||||
|
let dst_grid_right = if dst_grid_right == dst { dst_grid_right + 1.0 } else { dst_grid_right };
|
||||||
|
let src_grid_left = src_grid.floor();
|
||||||
|
|
||||||
|
let mut dst: f32 = dst;
|
||||||
|
for step in dst_grid_right as i32..=src_grid_left as i32 {
|
||||||
|
let step = step as f32 * grid;
|
||||||
|
output.push((dst, dst - step));
|
||||||
|
dst = step;
|
||||||
|
}
|
||||||
|
output.push((dst, dst - src));
|
||||||
|
output.reverse();
|
||||||
|
}
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use crate::tools::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_split_by_grid() {
|
||||||
|
// движение вправо
|
||||||
|
assert_eq!(split_by_grid(1.0, 4.0, 5.0), vec![(4.0, 3.0)]);
|
||||||
|
assert_eq!(split_by_grid(3.0, 5.0, 5.0), vec![(5.0, 2.0)]);
|
||||||
|
assert_eq!(split_by_grid(3.0, 6.0, 5.0), vec![(5.0, 2.0), (6.0, 1.0)]);
|
||||||
|
assert_eq!(split_by_grid(3.0, 10.0, 5.0), vec![(5.0, 2.0), (10.0, 5.0)]);
|
||||||
|
assert_eq!(split_by_grid(3.0, 11.0, 5.0), vec![(5.0, 2.0), (10.0, 5.0), (11.0, 1.0)]);
|
||||||
|
assert_eq!(split_by_grid(-2.0, 3.0, 5.0), vec![(0.0, 2.0), (3.0, 3.0)]);
|
||||||
|
assert_eq!(split_by_grid(-6.0, 7.0, 5.0), vec![(-5.0, 1.0), (0.0, 5.0), (5.0, 5.0), (7.0, 2.0)]);
|
||||||
|
assert_eq!(split_by_grid(-6.0, -2.0, 5.0), vec![(-5.0, 1.0), (-2.0, 3.0)]);
|
||||||
|
|
||||||
|
// движение влево
|
||||||
|
assert_eq!(split_by_grid(4.0, 1.0, 5.0), vec![(1.0, -3.0)]);
|
||||||
|
assert_eq!(split_by_grid(5.0, 3.0, 5.0), vec![(5.0, 0.0), (3.0, -2.0)]);
|
||||||
|
assert_eq!(split_by_grid(6.0, 3.0, 5.0), vec![(5.0, -1.0), (3.0, -2.0)]);
|
||||||
|
assert_eq!(split_by_grid(10.0, 3.0, 5.0), vec![(10.0, 0.0), (5.0, -5.0), (3.0, -2.0)]);
|
||||||
|
assert_eq!(split_by_grid(11.0, 3.0, 5.0), vec![(10.0, -1.0), (5.0, -5.0), (3.0, -2.0)]);
|
||||||
|
assert_eq!(split_by_grid(3.0, -2.0, 5.0), vec![(0.0, -3.0), (-2.0, -2.0)]);
|
||||||
|
assert_eq!(split_by_grid(7.0, -6.0, 5.0), vec![(5.0, -2.0), (0.0, -5.0), (-5.0, -5.0), (-6.0, -1.0)]);
|
||||||
|
assert_eq!(split_by_grid(-2.0, -6.0, 5.0), vec![(-5.0, -3.0), (-6.0, -1.0)]);
|
||||||
|
|
||||||
|
// сценарии с нулевой сеткой
|
||||||
|
assert_eq!(split_by_grid(1.0, 4.0, 0.0), vec![(4.0, 3.0)]);
|
||||||
|
assert_eq!(split_by_grid(4.0, 1.0, 0.0), vec![(1.0, -3.0)]);
|
||||||
|
|
||||||
|
// сценарии со стартом в узле сетки
|
||||||
|
assert_eq!(split_by_grid(0.0, 1.5, 5.0), vec![(0.0, 0.0), (1.5, 1.5)]);
|
||||||
|
assert_eq!(split_by_grid(5.0, 7.0, 5.0), vec![(5.0, 0.0), (7.0, 2.0)]);
|
||||||
|
assert_eq!(split_by_grid(0.0, -1.5, 5.0), vec![(0.0, 0.0), (-1.5, -1.5)]);
|
||||||
|
assert_eq!(split_by_grid(5.0, 3.0, 5.0), vec![(5.0, 0.0), (3.0, -2.0)]);
|
||||||
|
|
||||||
|
// сценарии с нулевым движением
|
||||||
|
assert_eq!(split_by_grid(5.0, 5.0, 5.0), vec![(5.0, 0.0)]);
|
||||||
|
assert_eq!(split_by_grid(0.0, 0.0, 5.0), vec![(0.0, 0.0)]);
|
||||||
|
assert_eq!(split_by_grid(0.0, 0.0, 0.0), vec![(0.0, 0.0)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
use bevy::prelude::*;
|
||||||
|
|
||||||
|
use crate::domain::{Direction, Head};
|
||||||
|
|
||||||
|
/// Система поворота головы змеи
|
||||||
|
pub fn head_rotation(
|
||||||
|
input: Res<ButtonInput<KeyCode>>, //
|
||||||
|
query: Single<(&mut Transform, &mut Head, &Direction)>,
|
||||||
|
) {
|
||||||
|
if input.just_pressed(KeyCode::ArrowLeft) {
|
||||||
|
let (mut transform, mut head, direction) = query.into_inner();
|
||||||
|
let mut new_direction = *direction;
|
||||||
|
new_direction.rotate_left();
|
||||||
|
head.0 = new_direction;
|
||||||
|
transform.rotation = new_direction.orientation();
|
||||||
|
} else if input.just_pressed(KeyCode::ArrowRight) {
|
||||||
|
let (mut transform, mut head, direction) = query.into_inner();
|
||||||
|
let mut new_direction = *direction;
|
||||||
|
new_direction.rotate_right();
|
||||||
|
head.0 = new_direction;
|
||||||
|
transform.rotation = new_direction.orientation();
|
||||||
|
} else if input.just_pressed(KeyCode::ArrowUp) {
|
||||||
|
let (mut transform, mut head, direction) = query.into_inner();
|
||||||
|
head.0 = *direction;
|
||||||
|
transform.rotation = direction.orientation();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Регулировка скорости игры
|
||||||
|
pub fn time_speed(input: Res<ButtonInput<KeyCode>>, mut time: ResMut<Time<Virtual>>) {
|
||||||
|
if input.just_pressed(KeyCode::Equal) {
|
||||||
|
let mut speed = time.relative_speed();
|
||||||
|
speed *= 2.0;
|
||||||
|
time.set_relative_speed(speed);
|
||||||
|
trace!("time speed set x2.0: {}", time.relative_speed());
|
||||||
|
} else if input.just_pressed(KeyCode::Minus) {
|
||||||
|
let mut speed = time.relative_speed();
|
||||||
|
speed *= 0.5;
|
||||||
|
time.set_relative_speed(speed);
|
||||||
|
trace!("time speed set x0.5: {}", time.relative_speed());
|
||||||
|
} else if input.just_pressed(KeyCode::Backspace) {
|
||||||
|
time.set_relative_speed(1.0);
|
||||||
|
trace!("time speed reset: {}", time.relative_speed());
|
||||||
|
} else if input.just_pressed(KeyCode::Space) {
|
||||||
|
if time.is_paused() {
|
||||||
|
time.unpause();
|
||||||
|
trace!("unpause game");
|
||||||
|
} else {
|
||||||
|
time.pause();
|
||||||
|
trace!("pause game");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
use std::f32::consts::PI;
|
||||||
|
|
||||||
|
use bevy::transform::components::Transform;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_saturating_sub() {
|
||||||
|
let a: usize = 10;
|
||||||
|
dbg!(a.saturating_sub(5));
|
||||||
|
dbg!(a.saturating_sub(10));
|
||||||
|
dbg!(a.saturating_sub(15));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_remainder() {
|
||||||
|
dbg!(-6 % 5);
|
||||||
|
dbg!(6 % 5);
|
||||||
|
dbg!(6.3 % 5.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ceil() {
|
||||||
|
dbg!(0.1_f32.ceil());
|
||||||
|
dbg!(-0.1_f32.ceil());
|
||||||
|
dbg!(5.9_f32.ceil());
|
||||||
|
dbg!(-5.9_f32.ceil());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_floor() {
|
||||||
|
dbg!(0.1_f32.floor());
|
||||||
|
dbg!((-0.1_f32).floor());
|
||||||
|
dbg!((-0.2_f32).floor());
|
||||||
|
dbg!((-0.3_f32).floor());
|
||||||
|
dbg!((-1.0_f32 / 5.0_f32).floor());
|
||||||
|
dbg!(5.9_f32.floor());
|
||||||
|
dbg!(-5.9_f32.floor());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_zero() {
|
||||||
|
dbg!(-0.0_f32 == 0.0_f32);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ranges() {
|
||||||
|
for x in 0..5 {
|
||||||
|
dbg!(x);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_transform() {
|
||||||
|
let mut transform = Transform::default();
|
||||||
|
dbg!(transform);
|
||||||
|
dbg!({
|
||||||
|
transform.rotate_z(PI / 2.0);
|
||||||
|
transform
|
||||||
|
});
|
||||||
|
dbg!({
|
||||||
|
transform.rotate_z(PI / 2.0);
|
||||||
|
transform
|
||||||
|
});
|
||||||
|
dbg!({
|
||||||
|
transform.rotate_z(PI / 2.0);
|
||||||
|
transform
|
||||||
|
});
|
||||||
|
dbg!({
|
||||||
|
transform.rotate_z(PI / 2.0);
|
||||||
|
transform
|
||||||
|
});
|
||||||
|
dbg!({
|
||||||
|
transform.rotate_z(PI * 2.0);
|
||||||
|
transform
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user