Skip to main content

flatland_client_lib/
bot.rs

1use std::time::Duration;
2use std::time::Instant;
3
4use flatland_protocol::{Intent, LifeState, NpcView, ResourceNodeView, Seq, Snapshot};
5use rand::Rng;
6use rand::SeedableRng;
7use rand::rngs::StdRng;
8use tracing::debug;
9
10use crate::session::{PlayConnection, SessionEvent};
11
12#[derive(Debug, Clone)]
13pub struct BotConfig {
14    pub name: String,
15    pub think_interval: Duration,
16    pub harvest_once: bool,
17    pub hunt_once: bool,
18    pub say_once: Option<String>,
19}
20
21impl BotConfig {
22    pub fn new(name: impl Into<String>) -> Self {
23        Self {
24            name: name.into(),
25            think_interval: Duration::from_millis(100),
26            harvest_once: false,
27            hunt_once: false,
28            say_once: None,
29        }
30    }
31}
32
33#[derive(Debug, Default, Clone)]
34pub struct BotStats {
35    pub ticks_received: u64,
36    pub intents_sent: u64,
37    pub intent_acks: u64,
38    pub last_tick: u64,
39    pub last_entity_count: usize,
40    pub intent_latency_p99_ms: f64,
41}
42
43struct PendingIntent {
44    sent_at: Instant,
45    seq: Seq,
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49enum HuntPhase {
50    Seek,
51    Fight,
52    Butcher,
53    Done,
54}
55
56pub struct BotClient<S: PlayConnection> {
57    config: BotConfig,
58    session: S,
59    seq: Seq,
60    stats: BotStats,
61    pending: Vec<PendingIntent>,
62    rng: StdRng,
63    did_special: bool,
64    hunt_phase: Option<HuntPhase>,
65    last_pos: (f32, f32),
66    last_npcs: Vec<NpcView>,
67    last_resource_nodes: Vec<ResourceNodeView>,
68    hunt_target: Option<u64>,
69    attack_cooldown: u8,
70}
71
72impl<S: PlayConnection> BotClient<S> {
73    pub fn new(config: BotConfig, session: S) -> Self {
74        let seed = session.entity_id() ^ session.session_id().rotate_left(17);
75        let hunt_once = config.hunt_once;
76        Self {
77            config,
78            session,
79            seq: 0,
80            stats: BotStats::default(),
81            pending: Vec::new(),
82            rng: StdRng::seed_from_u64(seed),
83            did_special: false,
84            hunt_phase: if hunt_once {
85                Some(HuntPhase::Seek)
86            } else {
87                None
88            },
89            last_pos: (0.0, 0.0),
90            last_npcs: Vec::new(),
91            last_resource_nodes: Vec::new(),
92            hunt_target: None,
93            attack_cooldown: 0,
94        }
95    }
96
97    pub fn entity_id(&self) -> u64 {
98        self.session.entity_id()
99    }
100
101    pub fn stats(&self) -> &BotStats {
102        &self.stats
103    }
104
105    pub async fn run_until(&mut self, deadline: Instant) -> anyhow::Result<()> {
106        let mut next_think = tokio::time::Instant::now();
107
108        while Instant::now() < deadline {
109            tokio::select! {
110                _ = tokio::time::sleep_until(next_think) => {
111                    self.send_random_intent().await?;
112                    next_think = tokio::time::Instant::now() + self.config.think_interval;
113                }
114                event = self.session.next_event() => {
115                    match event {
116                        Some(ev) => self.handle_event(ev).await?,
117                        None => break,
118                    }
119                }
120            }
121        }
122
123        self.disconnect();
124        Ok(())
125    }
126
127    pub fn disconnect(&self) {
128        self.session.disconnect();
129    }
130
131    async fn send_random_intent(&mut self) -> anyhow::Result<()> {
132        if self.config.hunt_once {
133            if let Some(phase) = self.hunt_phase {
134                if phase != HuntPhase::Done {
135                    return self.send_hunt_intent().await;
136                }
137            }
138        }
139
140        self.seq += 1;
141        let forward = self.rng.gen_range(-1.0..=1.0);
142        let strafe = self.rng.gen_range(-1.0..=1.0);
143        let seq = self.seq;
144
145        self.session
146            .submit_intent(Intent::Move {
147                entity_id: self.session.entity_id(),
148                forward,
149                strafe,
150                vertical: 0.0,
151                sprint: false,
152                seq,
153            })
154            .await?;
155
156        self.pending.push(PendingIntent {
157            sent_at: Instant::now(),
158            seq,
159        });
160        self.stats.intents_sent += 1;
161        Ok(())
162    }
163
164    async fn handle_event(&mut self, event: SessionEvent) -> anyhow::Result<()> {
165        match event {
166            SessionEvent::Welcome { entity_id, snapshot, .. } => {
167                debug!(bot = %self.config.name, entity_id, "welcome");
168                self.ingest_snapshot(&snapshot);
169                if !self.did_special {
170                    self.did_special = true;
171                    if self.config.harvest_once {
172                        if let Some(node) = snapshot
173                            .resource_nodes
174                            .iter()
175                            .find(|n| n.state == flatland_protocol::ResourceNodeState::Available)
176                        {
177                            self.seq += 1;
178                            self.session
179                                .submit_intent(Intent::Harvest {
180                                    entity_id: self.session.entity_id(),
181                                    node_id: node.id.clone(),
182                                    seq: self.seq,
183                                })
184                                .await?;
185                            self.stats.intents_sent += 1;
186                        }
187                    }
188                    if let Some(text) = &self.config.say_once {
189                        self.seq += 1;
190                        self.session
191                            .submit_intent(Intent::Say {
192                                entity_id: self.session.entity_id(),
193                                channel: flatland_protocol::ChatChannel::Nearby,
194                                text: text.clone(),
195                                seq: self.seq,
196                            })
197                            .await?;
198                        self.stats.intents_sent += 1;
199                    }
200                }
201            }
202            SessionEvent::Tick(delta) => {
203                self.stats.ticks_received += 1;
204                self.stats.last_tick = delta.tick;
205                self.stats.last_entity_count = delta.entities.len();
206                if let Some(entity) = delta
207                    .entities
208                    .iter()
209                    .find(|e| e.id == self.session.entity_id())
210                {
211                    self.last_pos = (
212                        entity.transform.position.x,
213                        entity.transform.position.y,
214                    );
215                }
216                if !delta.npcs.is_empty() {
217                    self.last_npcs = delta.npcs;
218                }
219                if !delta.resource_nodes.is_empty() {
220                    self.last_resource_nodes = delta.resource_nodes;
221                }
222            }
223            SessionEvent::IntentAck { seq, .. } => {
224                self.stats.intent_acks += 1;
225                if let Some(idx) = self.pending.iter().position(|p| p.seq == seq) {
226                    let pending = self.pending.remove(idx);
227                    let ms = pending.sent_at.elapsed().as_secs_f64() * 1000.0;
228                    self.stats.intent_latency_p99_ms =
229                        self.stats.intent_latency_p99_ms.max(ms);
230                }
231            }
232            SessionEvent::Chat(_) | SessionEvent::HarvestResult(_) => {}
233            SessionEvent::CraftResult(_)
234            | SessionEvent::Death(_)
235            | SessionEvent::Interaction(_)
236            | SessionEvent::ShopOpened(_)
237            | SessionEvent::UseResult(_)
238            | SessionEvent::ContentUpdated { .. } => {}
239            SessionEvent::Disconnected { .. } => {
240                anyhow::bail!("disconnected");
241            }
242        }
243        Ok(())
244    }
245
246    fn ingest_snapshot(&mut self, snapshot: &Snapshot) {
247        self.last_npcs = snapshot.npcs.clone();
248        self.last_resource_nodes = snapshot.resource_nodes.clone();
249        if let Some(entity) = snapshot
250            .entities
251            .iter()
252            .find(|e| e.id == self.session.entity_id())
253        {
254            self.last_pos = (
255                entity.transform.position.x,
256                entity.transform.position.y,
257            );
258        }
259    }
260
261    fn nearest_wildlife(&self) -> Option<&NpcView> {
262        let (px, py) = self.last_pos;
263        self.last_npcs
264            .iter()
265            .filter(|n| n.entity_id.is_some())
266            .filter(|n| n.building_id.is_none())
267            .filter(|n| n.life_state != Some(LifeState::Dead))
268            .min_by(|a, b| {
269                let da = (a.x - px).hypot(a.y - py);
270                let db = (b.x - px).hypot(b.y - py);
271                da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
272            })
273    }
274
275    fn nearest_carcass(&self) -> Option<&ResourceNodeView> {
276        let (px, py) = self.last_pos;
277        self.last_resource_nodes
278            .iter()
279            .filter(|n| n.id.starts_with("carcass-"))
280            .filter(|n| n.state == flatland_protocol::ResourceNodeState::Available)
281            .min_by(|a, b| {
282                let da = (a.x - px).hypot(a.y - py);
283                let db = (b.x - px).hypot(b.y - py);
284                da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
285            })
286    }
287
288    async fn send_hunt_intent(&mut self) -> anyhow::Result<()> {
289        let phase = self.hunt_phase.unwrap_or(HuntPhase::Done);
290        let entity_id = self.session.entity_id();
291        let (px, py) = self.last_pos;
292
293        if let Some(carcass) = self.nearest_carcass().cloned() {
294            let dist = (carcass.x - px).hypot(carcass.y - py);
295            if dist <= 2.0 {
296                self.hunt_phase = Some(HuntPhase::Butcher);
297                self.seq += 1;
298                self.session
299                    .submit_intent(Intent::Harvest {
300                        entity_id,
301                        node_id: carcass.id,
302                        seq: self.seq,
303                    })
304                    .await?;
305                self.stats.intents_sent += 1;
306                self.hunt_phase = Some(HuntPhase::Done);
307                return Ok(());
308            }
309        }
310
311        match phase {
312            HuntPhase::Seek | HuntPhase::Fight => {
313                if let Some(prey) = self.nearest_wildlife().cloned() {
314                    let tx = prey.x;
315                    let ty = prey.y;
316                    let prey_entity = prey.entity_id;
317                    let dist = (tx - px).hypot(ty - py);
318                    if dist <= 2.0 {
319                        self.hunt_phase = Some(HuntPhase::Fight);
320                        if self.hunt_target != prey_entity {
321                            self.hunt_target = prey_entity;
322                            self.seq += 1;
323                            if let Some(target_id) = prey_entity {
324                                self.session
325                                    .submit_intent(Intent::SetTarget {
326                                        entity_id,
327                                        target_id,
328                                        seq: self.seq,
329                                    })
330                                    .await?;
331                                self.stats.intents_sent += 1;
332                            }
333                        }
334                        if self.attack_cooldown == 0 {
335                            self.seq += 1;
336                            self.session
337                                .submit_intent(Intent::Attack {
338                                    entity_id,
339                                    target_id: prey_entity,
340                                    weapon_slot: None,
341                                    seq: self.seq,
342                                })
343                                .await?;
344                            self.stats.intents_sent += 1;
345                            self.attack_cooldown = 6;
346                        } else {
347                            self.attack_cooldown = self.attack_cooldown.saturating_sub(1);
348                        }
349                        return Ok(());
350                    }
351
352                    let dx = tx - px;
353                    let dy = ty - py;
354                    let len = (dx * dx + dy * dy).sqrt().max(0.001);
355                    let forward = dy / len;
356                    let strafe = dx / len;
357                    self.seq += 1;
358                    self.session
359                        .submit_intent(Intent::Move {
360                            entity_id,
361                            forward,
362                            strafe,
363                            vertical: 0.0,
364                            sprint: true,
365                            seq: self.seq,
366                        })
367                        .await?;
368                    self.stats.intents_sent += 1;
369                    return Ok(());
370                }
371            }
372            HuntPhase::Butcher | HuntPhase::Done => {}
373        }
374
375        self.send_random_move().await
376    }
377
378    async fn send_random_move(&mut self) -> anyhow::Result<()> {
379        self.seq += 1;
380        let forward = self.rng.gen_range(-1.0..=1.0);
381        let strafe = self.rng.gen_range(-1.0..=1.0);
382        let seq = self.seq;
383
384        self.session
385            .submit_intent(Intent::Move {
386                entity_id: self.session.entity_id(),
387                forward,
388                strafe,
389                vertical: 0.0,
390                sprint: false,
391                seq,
392            })
393            .await?;
394
395        self.pending.push(PendingIntent {
396            sent_at: Instant::now(),
397            seq,
398        });
399        self.stats.intents_sent += 1;
400        Ok(())
401    }
402}