aboutsummaryrefslogtreecommitdiff
path: root/planetwars-client/src/main.rs
blob: 25a6725ac8937370e27ab0d863b8d42c6da7b2f3 (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
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
pub mod pb {
    tonic::include_proto!("grpc.planetwars.bot_api");
}

use pb::bot_api_service_client::BotApiServiceClient;
use planetwars_matchrunner::bot_runner::Bot;
use serde::Deserialize;
use std::{path::PathBuf, time::Duration};
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;
use tonic::{metadata::MetadataValue, transport::Channel, Request, Status};

#[derive(Deserialize)]
struct BotConfig {
    #[allow(dead_code)]
    name: String,
    command: Vec<String>,
}

#[tokio::main]
async fn main() {
    let content = std::fs::read_to_string("simplebot.toml").unwrap();
    let bot_config: BotConfig = toml::from_str(&content).unwrap();

    let channel = Channel::from_static("http://localhost:50051")
        .connect()
        .await
        .unwrap();

    let created_match = create_match(channel.clone()).await.unwrap();
    run_player(bot_config, created_match.player_key, channel).await;
    tokio::time::sleep(Duration::from_secs(1)).await;
}

async fn create_match(channel: Channel) -> Result<pb::CreatedMatch, Status> {
    let mut client = BotApiServiceClient::new(channel);
    let res = client
        .create_match(Request::new(pb::MatchRequest {
            opponent_name: "simplebot".to_string(),
        }))
        .await;
    res.map(|response| response.into_inner())
}

async fn run_player(bot_config: BotConfig, player_key: String, channel: Channel) {
    let mut client = BotApiServiceClient::with_interceptor(channel, |mut req: Request<()>| {
        let player_key: MetadataValue<_> = player_key.parse().unwrap();
        req.metadata_mut().insert("player_key", player_key);
        Ok(req)
    });

    let mut bot_process = Bot {
        working_dir: PathBuf::from("."),
        argv: bot_config.command,
    }
    .spawn_process();

    let (tx, rx) = mpsc::unbounded_channel();
    let mut stream = client
        .connect_player(UnboundedReceiverStream::new(rx))
        .await
        .unwrap()
        .into_inner();
    while let Some(message) = stream.message().await.unwrap() {
        use pb::client_message::ClientMessage;
        use pb::server_message::ServerMessage;

        match message.server_message {
            Some(ServerMessage::PlayerRequest(req)) => {
                let moves = bot_process.communicate(&req.content).await.unwrap();
                let resp = pb::PlayerRequestResponse {
                    request_id: req.request_id,
                    content: moves.as_bytes().to_vec(),
                };
                let msg = pb::ClientMessage {
                    client_message: Some(ClientMessage::RequestResponse(resp)),
                };
                tx.send(msg).unwrap();
            }
            _ => {} // pass
        }
    }
}