-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
84 lines (70 loc) · 2.22 KB
/
main.rs
File metadata and controls
84 lines (70 loc) · 2.22 KB
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
use actix_web::{App, HttpResponse, HttpServer, Responder, post};
use serde::{Serialize, Deserialize};
use serde_json::Result;
use rand::seq::SliceRandom;
const ANT_HIVE_URL: &str = "0.0.0.0:7070";
const ACTIONS: [&'static str; 5] = ["stay", "move", "eat", "take", "put"];
const DIRECTIONS: [&'static str; 4] = ["up", "down", "right", "left"];
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(post_async)
})
.bind(ANT_HIVE_URL)?
.run()
.await
}
#[post("/")]
async fn post_async(req_body: String) -> impl Responder {
// Here desiarilze
let request: Request = match deserialize_request(&req_body) {
Err(_) => Request {id: String::from(""), tick: 0, ants: Vec::new()},
Ok(ok_ants) => ok_ants
};
let order_from_ants: Vec<Order> = request.ants.iter()
.map(|ant| Order {
ant_id: ant.id,
act: String::from(*ACTIONS.choose(&mut rand::thread_rng()).unwrap()),
dir: String::from(*DIRECTIONS.choose(&mut rand::thread_rng()).unwrap())})
.collect();
let responce = Responce {orders: order_from_ants};
// Here serialize
let response_body = serde_json::to_string(&responce).unwrap();
HttpResponse::Ok().body(response_body)
}
fn deserialize_request(request: &String ) -> Result<Request> {
let result: Result<Request> = serde_json::from_str(&*request.to_string());
result
}
#[derive(Serialize, Deserialize)]
struct Ant {
pub id: i32,
pub event: String,
pub age: i32,
pub health: i32,
pub cargo: i32,
pub point: Point
}
#[derive(Serialize, Deserialize)]
struct Point {
pub x: i32,
pub y: i32
}
#[derive(Serialize, Deserialize)]
struct Order {
#[serde(rename = "antId")]
pub ant_id: i32,
pub act: String,
pub dir: String
}
#[derive(Serialize, Deserialize)]
struct Request {
pub id: String,
pub tick: i32,
pub ants: Vec<Ant>
}
#[derive(Serialize, Deserialize)]
struct Responce {
pub orders: Vec<Order>
}