flatland-client-lib 0.2.22

Flatland3 remote game client library (TCP session, bots, game state)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use std::time::Duration;
use std::time::Instant;

use flatland_protocol::{Intent, LifeState, NpcView, ResourceNodeView, Seq, Snapshot};
use rand::rngs::StdRng;
use rand::Rng;
use rand::SeedableRng;
use tracing::debug;

use crate::session::{PlayConnection, SessionEvent};

#[derive(Debug, Clone)]
pub struct BotConfig {
    pub name: String,
    pub think_interval: Duration,
    pub harvest_once: bool,
    pub hunt_once: bool,
    pub say_once: Option<String>,
}

impl BotConfig {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            think_interval: Duration::from_millis(100),
            harvest_once: false,
            hunt_once: false,
            say_once: None,
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct BotStats {
    pub ticks_received: u64,
    pub intents_sent: u64,
    pub intent_acks: u64,
    pub last_tick: u64,
    pub last_entity_count: usize,
    pub intent_latency_p99_ms: f64,
}

struct PendingIntent {
    sent_at: Instant,
    seq: Seq,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HuntPhase {
    Seek,
    Fight,
    Butcher,
    Done,
}

pub struct BotClient<S: PlayConnection> {
    config: BotConfig,
    session: S,
    seq: Seq,
    stats: BotStats,
    pending: Vec<PendingIntent>,
    rng: StdRng,
    did_special: bool,
    hunt_phase: Option<HuntPhase>,
    last_pos: (f32, f32),
    last_npcs: Vec<NpcView>,
    last_resource_nodes: Vec<ResourceNodeView>,
    hunt_target: Option<u64>,
    attack_cooldown: u8,
}

impl<S: PlayConnection> BotClient<S> {
    pub fn new(config: BotConfig, session: S) -> Self {
        let seed = session.entity_id() ^ session.session_id().rotate_left(17);
        let hunt_once = config.hunt_once;
        Self {
            config,
            session,
            seq: 0,
            stats: BotStats::default(),
            pending: Vec::new(),
            rng: StdRng::seed_from_u64(seed),
            did_special: false,
            hunt_phase: if hunt_once {
                Some(HuntPhase::Seek)
            } else {
                None
            },
            last_pos: (0.0, 0.0),
            last_npcs: Vec::new(),
            last_resource_nodes: Vec::new(),
            hunt_target: None,
            attack_cooldown: 0,
        }
    }

    pub fn entity_id(&self) -> u64 {
        self.session.entity_id()
    }

    pub fn stats(&self) -> &BotStats {
        &self.stats
    }

    pub async fn run_until(&mut self, deadline: Instant) -> anyhow::Result<()> {
        let mut next_think = tokio::time::Instant::now();

        while Instant::now() < deadline {
            tokio::select! {
                _ = tokio::time::sleep_until(next_think) => {
                    self.send_random_intent().await?;
                    next_think = tokio::time::Instant::now() + self.config.think_interval;
                }
                event = self.session.next_event() => {
                    match event {
                        Some(ev) => self.handle_event(ev).await?,
                        None => break,
                    }
                }
            }
        }

        self.disconnect();
        Ok(())
    }

    pub fn disconnect(&self) {
        self.session.disconnect();
    }

    async fn send_random_intent(&mut self) -> anyhow::Result<()> {
        if self.config.hunt_once {
            if let Some(phase) = self.hunt_phase {
                if phase != HuntPhase::Done {
                    return self.send_hunt_intent().await;
                }
            }
        }

        self.seq += 1;
        let forward = self.rng.gen_range(-1.0..=1.0);
        let strafe = self.rng.gen_range(-1.0..=1.0);
        let seq = self.seq;

        self.session
            .submit_intent(Intent::Move {
                entity_id: self.session.entity_id(),
                forward,
                strafe,
                vertical: 0.0,
                sprint: false,
                seq,
            })
            .await?;

        self.pending.push(PendingIntent {
            sent_at: Instant::now(),
            seq,
        });
        self.stats.intents_sent += 1;
        Ok(())
    }

    async fn handle_event(&mut self, event: SessionEvent) -> anyhow::Result<()> {
        match event {
            SessionEvent::Welcome {
                entity_id,
                snapshot,
                ..
            } => {
                debug!(bot = %self.config.name, entity_id, "welcome");
                self.ingest_snapshot(&snapshot);
                if !self.did_special {
                    self.did_special = true;
                    if self.config.harvest_once {
                        if let Some(node) = snapshot
                            .resource_nodes
                            .iter()
                            .find(|n| n.state == flatland_protocol::ResourceNodeState::Available)
                        {
                            self.seq += 1;
                            self.session
                                .submit_intent(Intent::Harvest {
                                    entity_id: self.session.entity_id(),
                                    node_id: node.id.clone(),
                                    seq: self.seq,
                                })
                                .await?;
                            self.stats.intents_sent += 1;
                        }
                    }
                    if let Some(text) = &self.config.say_once {
                        self.seq += 1;
                        self.session
                            .submit_intent(Intent::Say {
                                entity_id: self.session.entity_id(),
                                channel: flatland_protocol::ChatChannel::Nearby,
                                text: text.clone(),
                                to_entity: None,
                                seq: self.seq,
                            })
                            .await?;
                        self.stats.intents_sent += 1;
                    }
                }
            }
            SessionEvent::Tick(delta) => {
                self.stats.ticks_received += 1;
                self.stats.last_tick = delta.tick;
                self.stats.last_entity_count = delta.entities.len();
                if let Some(entity) = delta
                    .entities
                    .iter()
                    .find(|e| e.id == self.session.entity_id())
                {
                    self.last_pos = (entity.transform.position.x, entity.transform.position.y);
                }
                if !delta.npcs.is_empty() {
                    self.last_npcs = delta.npcs;
                }
                if !delta.resource_nodes.is_empty() {
                    self.last_resource_nodes = delta.resource_nodes;
                }
            }
            SessionEvent::IntentAck { seq, .. } => {
                self.stats.intent_acks += 1;
                if let Some(idx) = self.pending.iter().position(|p| p.seq == seq) {
                    let pending = self.pending.remove(idx);
                    let ms = pending.sent_at.elapsed().as_secs_f64() * 1000.0;
                    self.stats.intent_latency_p99_ms = self.stats.intent_latency_p99_ms.max(ms);
                }
            }
            SessionEvent::Chat(_) | SessionEvent::HarvestResult(_) => {}
            SessionEvent::CraftResult(_)
            | SessionEvent::Death(_)
            | SessionEvent::Interaction(_)
            | SessionEvent::ShopOpened(_)
            | SessionEvent::BankOpened(_)
            | SessionEvent::StorageOpened(_)
            | SessionEvent::TradeOpened(_)
            | SessionEvent::TradeClosed { .. }
            | SessionEvent::UseResult(_)
            | SessionEvent::NpcTalkOpened(_)
            | SessionEvent::NpcTalkPending(_)
            | SessionEvent::NpcTalkReply(_)
            | SessionEvent::NpcTalkClosed(_)
            | SessionEvent::NpcTalkError(_)
            | SessionEvent::QuestOffer(_)
            | SessionEvent::QuestAccepted(_)
            | SessionEvent::QuestWithdrawn(_)
            | SessionEvent::QuestStepCompleted(_)
            | SessionEvent::QuestCompleted(_)
            | SessionEvent::ContentUpdated { .. } => {}
            SessionEvent::Disconnected { .. } => {
                anyhow::bail!("disconnected");
            }
        }
        Ok(())
    }

    fn ingest_snapshot(&mut self, snapshot: &Snapshot) {
        self.last_npcs = snapshot.npcs.clone();
        self.last_resource_nodes = snapshot.resource_nodes.clone();
        if let Some(entity) = snapshot
            .entities
            .iter()
            .find(|e| e.id == self.session.entity_id())
        {
            self.last_pos = (entity.transform.position.x, entity.transform.position.y);
        }
    }

    fn nearest_wildlife(&self) -> Option<&NpcView> {
        let (px, py) = self.last_pos;
        self.last_npcs
            .iter()
            .filter(|n| n.entity_id.is_some())
            .filter(|n| n.building_id.is_none())
            .filter(|n| n.life_state != Some(LifeState::Dead))
            .min_by(|a, b| {
                let da = (a.x - px).hypot(a.y - py);
                let db = (b.x - px).hypot(b.y - py);
                da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
            })
    }

    fn nearest_carcass(&self) -> Option<&ResourceNodeView> {
        let (px, py) = self.last_pos;
        self.last_resource_nodes
            .iter()
            .filter(|n| n.id.starts_with("carcass-"))
            .filter(|n| n.state == flatland_protocol::ResourceNodeState::Available)
            .min_by(|a, b| {
                let da = (a.x - px).hypot(a.y - py);
                let db = (b.x - px).hypot(b.y - py);
                da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
            })
    }

    async fn send_hunt_intent(&mut self) -> anyhow::Result<()> {
        let phase = self.hunt_phase.unwrap_or(HuntPhase::Done);
        let entity_id = self.session.entity_id();
        let (px, py) = self.last_pos;

        if let Some(carcass) = self.nearest_carcass().cloned() {
            let dist = (carcass.x - px).hypot(carcass.y - py);
            if dist <= 2.0 {
                self.hunt_phase = Some(HuntPhase::Butcher);
                self.seq += 1;
                self.session
                    .submit_intent(Intent::Harvest {
                        entity_id,
                        node_id: carcass.id,
                        seq: self.seq,
                    })
                    .await?;
                self.stats.intents_sent += 1;
                self.hunt_phase = Some(HuntPhase::Done);
                return Ok(());
            }
        }

        match phase {
            HuntPhase::Seek | HuntPhase::Fight => {
                if let Some(prey) = self.nearest_wildlife().cloned() {
                    let tx = prey.x;
                    let ty = prey.y;
                    let prey_entity = prey.entity_id;
                    let dist = (tx - px).hypot(ty - py);
                    if dist <= 2.0 {
                        self.hunt_phase = Some(HuntPhase::Fight);
                        if self.hunt_target != prey_entity {
                            self.hunt_target = prey_entity;
                            self.seq += 1;
                            if let Some(target_id) = prey_entity {
                                self.session
                                    .submit_intent(Intent::SetTarget {
                                        entity_id,
                                        target_id,
                                        seq: self.seq,
                                    })
                                    .await?;
                                self.stats.intents_sent += 1;
                            }
                        }
                        if self.attack_cooldown == 0 {
                            self.seq += 1;
                            self.session
                                .submit_intent(Intent::Attack {
                                    entity_id,
                                    target_id: prey_entity,
                                    weapon_slot: None,
                                    seq: self.seq,
                                })
                                .await?;
                            self.stats.intents_sent += 1;
                            self.attack_cooldown = 6;
                        } else {
                            self.attack_cooldown = self.attack_cooldown.saturating_sub(1);
                        }
                        return Ok(());
                    }

                    let dx = tx - px;
                    let dy = ty - py;
                    let len = (dx * dx + dy * dy).sqrt().max(0.001);
                    let forward = dy / len;
                    let strafe = dx / len;
                    self.seq += 1;
                    self.session
                        .submit_intent(Intent::Move {
                            entity_id,
                            forward,
                            strafe,
                            vertical: 0.0,
                            sprint: true,
                            seq: self.seq,
                        })
                        .await?;
                    self.stats.intents_sent += 1;
                    return Ok(());
                }
            }
            HuntPhase::Butcher | HuntPhase::Done => {}
        }

        self.send_random_move().await
    }

    async fn send_random_move(&mut self) -> anyhow::Result<()> {
        self.seq += 1;
        let forward = self.rng.gen_range(-1.0..=1.0);
        let strafe = self.rng.gen_range(-1.0..=1.0);
        let seq = self.seq;

        self.session
            .submit_intent(Intent::Move {
                entity_id: self.session.entity_id(),
                forward,
                strafe,
                vertical: 0.0,
                sprint: false,
                seq,
            })
            .await?;

        self.pending.push(PendingIntent {
            sent_at: Instant::now(),
            seq,
        });
        self.stats.intents_sent += 1;
        Ok(())
    }
}