aboutsummaryrefslogtreecommitdiff
path: root/src/bot/mod.rs
blob: 3722bf8655a81be5e768bfa8bc1f8f0553a2f64c (plain)
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
use crate::{game::protocol::Direction, State};
use log::debug;
use rand::{rng, seq::IteratorRandom};
use serde::Deserialize;
use std::{ops::DerefMut, sync::Arc};
use tokio::spawn;

#[derive(Deserialize, Clone)]
pub struct Config {
    amount: usize,
}

pub async fn spawn_bots(config: Config, state: Arc<State>) {
    for i in 0..config.amount {
        spawn(bot(config.clone(), state.clone(), format!("bot{i}")));
    }
}

async fn bot(_config: Config, state: Arc<State>, name: String) {
    let mut ticks = state.tick.subscribe();
    let id = {
        let mut g = state.players.write().await;
        let mut id = 0;
        while g.contains_key(&id) {
            id += 1;
        }
        g.insert(id, name.clone());
        id
    };
    let mut possible = Vec::new();
    while let Ok(_) = ticks.recv().await {
        let mut g = state.game.write().await;
        let g = g.deref_mut();
        if let Some((dir, head, _)) = g.heads.get_mut(&id) {
            possible.clear();
            for d in Direction::ALL {
                if g.map[*head + d.vector()].is_none() {
                    possible.push(d)
                }
            }
            *dir = *possible.iter().choose(&mut rng()).unwrap_or(&Direction::Up);
            debug!(name:?, dir:?; "");
        }
    }
}