1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 06:16:04 +00:00

fix some swarm examples/docs

This commit is contained in:
Ubuntu 2023-02-06 19:15:41 +00:00
parent cbcf1d5e54
commit d51b2a29b2
7 changed files with 57 additions and 108 deletions

View file

@ -3,7 +3,7 @@ use azalea::prelude::*;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::Arc; use std::sync::Arc;
#[derive(Default, Clone)] #[derive(Default, Clone, Component)]
struct State { struct State {
pub started: Arc<Mutex<bool>>, pub started: Arc<Mutex<bool>>,
} }
@ -13,15 +13,11 @@ async fn main() {
let account = Account::offline("bot"); let account = Account::offline("bot");
// or let bot = Account::microsoft("email").await; // or let bot = Account::microsoft("email").await;
azalea::start(azalea::Options { azalea::ClientBuilder::new()
account, .set_handler(handle)
address: "localhost", .start(account, "localhost")
state: State::default(), .await
plugins: plugins![], .unwrap();
handle,
})
.await
.unwrap();
} }
async fn handle(bot: Client, event: Event, state: State) -> anyhow::Result<()> { async fn handle(bot: Client, event: Event, state: State) -> anyhow::Result<()> {

View file

@ -7,15 +7,11 @@ async fn main() {
let account = Account::offline("bot"); let account = Account::offline("bot");
// or let account = Account::microsoft("email").await; // or let account = Account::microsoft("email").await;
azalea::start(azalea::Options { ClientBuilder::new()
account, .set_handler(handle)
address: "localhost", .start(account, "localhost")
state: State::default(), .await
plugins: plugins![], .unwrap();
handle,
})
.await
.unwrap();
} }
#[derive(Default, Clone, Component)] #[derive(Default, Clone, Component)]
@ -28,7 +24,7 @@ async fn handle(bot: Client, event: Event, _state: State) -> anyhow::Result<()>
if sender == bot.profile.name { if sender == bot.profile.name {
return Ok(()); // ignore our own messages return Ok(()); // ignore our own messages
} }
bot.chat(&content).await?; bot.chat(&content);
}; };
} }
_ => {} _ => {}

View file

@ -14,7 +14,7 @@ use std::time::Duration;
#[derive(Default, Clone, Component)] #[derive(Default, Clone, Component)]
struct State {} struct State {}
#[derive(Default, Clone, Component)] #[derive(Default, Clone, Resource)]
struct SwarmState {} struct SwarmState {}
#[tokio::main] #[tokio::main]
@ -54,7 +54,7 @@ async fn main() -> anyhow::Result<()> {
} }
loop { loop {
let e = azalea::SwarmBuilder::new() let e = SwarmBuilder::new()
.add_accounts(accounts.clone()) .add_accounts(accounts.clone())
.set_handler(handle) .set_handler(handle)
.set_swarm_handler(swarm_handle) .set_swarm_handler(swarm_handle)

View file

@ -1,5 +1,4 @@
use azalea::{prelude::*, SwarmEvent}; use azalea::prelude::*;
use azalea::{Account, Client, Event, Swarm};
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@ -7,44 +6,29 @@ async fn main() {
let mut states = Vec::new(); let mut states = Vec::new();
for i in 0..10 { for i in 0..10 {
accounts.push(Account::offline(&format!("bot{o}"))); accounts.push(Account::offline(&format!("bot{i}")));
states.push(State::default()); states.push(State::default());
} }
azalea::start_swarm(azalea::SwarmOptions { let e = azalea::SwarmBuilder::new()
accounts, .add_accounts(accounts.clone())
address: "localhost", .set_handler(handle)
.set_swarm_handler(swarm_handle)
swarm_state: SwarmState::default(), .start("localhost")
states, .await;
swarm_plugins: plugins![],
plugins: plugins![],
handle,
swarm_handle,
join_delay: None,
})
.await
.unwrap();
} }
#[derive(Default, Clone)] #[derive(Default, Clone, Component)]
struct State {} struct State {}
#[derive(Default, Clone)] #[derive(Default, Clone, Resource)]
struct SwarmState {} struct SwarmState {}
async fn handle(bot: Client, event: Event, state: State) -> anyhow::Result<()> { async fn handle(bot: Client, event: Event, state: State) -> anyhow::Result<()> {
Ok(()) Ok(())
} }
async fn swarm_handle( async fn swarm_handle(swarm: Swarm, event: SwarmEvent, state: SwarmState) -> anyhow::Result<()> {
swarm: Swarm<State>,
event: SwarmEvent,
state: SwarmState,
) -> anyhow::Result<()> {
match &event { match &event {
SwarmEvent::Login => { SwarmEvent::Login => {
swarm.goto(azalea::BlockPos::new(0, 70, 0)).await; swarm.goto(azalea::BlockPos::new(0, 70, 0)).await;

View file

@ -1,5 +1,9 @@
use azalea::{pathfinder, Account, Client, Event, SwarmEvent}; use std::time::Duration;
use azalea::entity::metadata::Player;
use azalea::{pathfinder, Account, Client, Event, GameProfileComponent, SwarmEvent};
use azalea::{prelude::*, Swarm}; use azalea::{prelude::*, Swarm};
use azalea_ecs::query::With;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@ -11,23 +15,14 @@ async fn main() {
states.push(State::default()); states.push(State::default());
} }
azalea::start_swarm(azalea::SwarmOptions { SwarmBuilder::new()
accounts, .add_accounts(accounts.clone())
address: "localhost", .set_handler(handle)
.set_swarm_handler(swarm_handle)
swarm_state: SwarmState::default(), .join_delay(Duration::from_millis(1000))
states, .start("localhost")
.await
swarm_plugins: swarm_plugins![pathfinder::Plugin], .unwrap();
plugins: plugins![],
handle,
swarm_handle,
join_delay: None,
})
.await
.unwrap();
} }
#[derive(Default, Clone)] #[derive(Default, Clone)]
@ -39,15 +34,13 @@ struct SwarmState {}
async fn handle(bot: Client, event: Event, state: State) -> anyhow::Result<()> { async fn handle(bot: Client, event: Event, state: State) -> anyhow::Result<()> {
Ok(()) Ok(())
} }
async fn swarm_handle( async fn swarm_handle(swarm: Swarm, event: SwarmEvent, state: SwarmState) -> anyhow::Result<()> {
swarm: Swarm<State>,
event: SwarmEvent,
state: SwarmState,
) -> anyhow::Result<()> {
match event { match event {
SwarmEvent::Tick => { SwarmEvent::Tick => {
if let Some(target_entity) = if let Some(target_entity) =
swarm.entity_by::<Player>(|name: &Name| name == "Herobrine") swarm.entity_by::<With<Player>>(|profile: &&GameProfileComponent| {
profile.name == "Herobrine"
})
{ {
let target_bounding_box = let target_bounding_box =
swarm.map_entity(target_entity, |bb: &BoundingBox| bb.clone()); swarm.map_entity(target_entity, |bb: &BoundingBox| bb.clone());

View file

@ -3,5 +3,7 @@
pub use crate::bot::BotClientExt; pub use crate::bot::BotClientExt;
pub use crate::pathfinder::PathfinderClientExt; pub use crate::pathfinder::PathfinderClientExt;
pub use crate::{ClientBuilder, SwarmBuilder};
pub use azalea_client::{Account, Client, Event}; pub use azalea_client::{Account, Client, Event};
pub use azalea_ecs::component::Component; pub use azalea_ecs::component::Component;
pub use azalea_ecs::system::Resource;

View file

@ -28,12 +28,10 @@ use tokio::sync::mpsc;
/// A swarm is a way to conveniently control many bots at once, while also /// A swarm is a way to conveniently control many bots at once, while also
/// being able to control bots at an individual level when desired. /// being able to control bots at an individual level when desired.
/// ///
/// Swarms are created from the [`azalea::start_swarm`] function. /// Swarms are created from [`azalea::SwarmBuilder`].
/// ///
/// The `S` type parameter is the type of the state for individual bots. /// The `S` type parameter is the type of the state for individual bots.
/// It's used to make the [`Swarm::add`] function work. /// It's used to make the [`Swarm::add`] function work.
///
/// [`azalea::start_swarm`]: fn.start_swarm.html
#[derive(Clone, Resource)] #[derive(Clone, Resource)]
pub struct Swarm { pub struct Swarm {
pub ecs_lock: Arc<Mutex<Ecs>>, pub ecs_lock: Arc<Mutex<Ecs>>,
@ -84,7 +82,7 @@ where
Fut: Future<Output = Result<(), anyhow::Error>> + Send + 'static, Fut: Future<Output = Result<(), anyhow::Error>> + Send + 'static,
SwarmFut: Future<Output = Result<(), anyhow::Error>> + Send + 'static, SwarmFut: Future<Output = Result<(), anyhow::Error>> + Send + 'static,
S: Default + Send + Sync + Clone + Component + 'static, S: Default + Send + Sync + Clone + Component + 'static,
SS: Default + Send + Sync + Clone + Component + 'static, SS: Default + Send + Sync + Clone + Resource + 'static,
{ {
/// Start creating the swarm. /// Start creating the swarm.
#[must_use] #[must_use]
@ -297,7 +295,7 @@ where
Fut: Future<Output = Result<(), anyhow::Error>> + Send + 'static, Fut: Future<Output = Result<(), anyhow::Error>> + Send + 'static,
SwarmFut: Future<Output = Result<(), anyhow::Error>> + Send + 'static, SwarmFut: Future<Output = Result<(), anyhow::Error>> + Send + 'static,
S: Default + Send + Sync + Clone + Component + 'static, S: Default + Send + Sync + Clone + Component + 'static,
SS: Default + Send + Sync + Clone + Component + 'static, SS: Default + Send + Sync + Clone + Resource + 'static,
{ {
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
@ -340,13 +338,12 @@ pub enum SwarmStartError {
/// # Examples /// # Examples
/// ```rust,no_run /// ```rust,no_run
/// use azalea::{prelude::*, Swarm, SwarmEvent}; /// use azalea::{prelude::*, Swarm, SwarmEvent};
/// use azalea::{Account, Client, Event};
/// use std::time::Duration; /// use std::time::Duration;
/// ///
/// #[derive(Default, Clone)] /// #[derive(Default, Clone, Component)]
/// struct State {} /// struct State {}
/// ///
/// #[derive(Default, Clone)] /// #[derive(Default, Clone, Resource)]
/// struct SwarmState {} /// struct SwarmState {}
/// ///
/// #[tokio::main] /// #[tokio::main]
@ -360,22 +357,13 @@ pub enum SwarmStartError {
/// } /// }
/// ///
/// loop { /// loop {
/// let e = azalea::start_swarm(azalea::SwarmOptions { /// let e = SwarmBuilder::new()
/// accounts: accounts.clone(), /// .add_accounts(accounts.clone())
/// address: "localhost", /// .set_handler(handle)
/// /// .set_swarm_handler(swarm_handle)
/// states: states.clone(), /// .join_delay(Duration::from_millis(1000))
/// swarm_state: SwarmState::default(), /// .start("localhost")
/// /// .await;
/// plugins: plugins![],
/// swarm_plugins: swarm_plugins![],
///
/// handle,
/// swarm_handle,
///
/// join_delay: Some(Duration::from_millis(1000)),
/// })
/// .await;
/// println!("{e:?}"); /// println!("{e:?}");
/// } /// }
/// } /// }
@ -405,16 +393,6 @@ pub enum SwarmStartError {
/// } /// }
/// Ok(()) /// Ok(())
/// } /// }
// pub async fn start_swarm<
// S: Send + Sync + Clone + 'static,
// SS: Send + Sync + Clone + 'static,
// A: Send + TryInto<ServerAddress>,
// Fut: Future<Output = Result<(), anyhow::Error>> + Send + 'static,
// SwarmFut: Future<Output = Result<(), anyhow::Error>> + Send + 'static,
// >(
// options: SwarmOptions<S, SS, A, Fut, SwarmFut>,
// ) -> Result<(), SwarmStartError> {
// }
impl Swarm { impl Swarm {
/// Add a new account to the swarm. You can remove it later by calling /// Add a new account to the swarm. You can remove it later by calling
@ -457,7 +435,7 @@ impl Swarm {
tokio::spawn(async move { tokio::spawn(async move {
while let Some(event) = rx.recv().await { while let Some(event) = rx.recv().await {
// we can't handle events here (since we can't copy the handler), // we can't handle events here (since we can't copy the handler),
// they're handled above in start_swarm // they're handled above in SwarmBuilder::start
if let Err(e) = cloned_bots_tx.send((Some(event), cloned_bot.clone())) { if let Err(e) = cloned_bots_tx.send((Some(event), cloned_bot.clone())) {
error!("Error sending event to swarm: {e}"); error!("Error sending event to swarm: {e}");
} }