#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; #[macro_use] extern crate serde_derive; use rocket::State; use rocket_contrib::json::Json; use pathfinding::grid::Grid; use std::collections::HashMap; use std::sync::{Arc, Mutex}; mod battlesnake; type Cache = Mutex>; #[derive(Debug, Clone)] pub struct GameState { path: Option>, target: battlesnake::Coord, } #[get("/")] fn index() -> &'static str { "Hello, world!" } #[get("/ping")] fn ping() -> &'static str { "OK - Pneuma online" } #[post("/begin", format = "json", data = "")] fn begin(cache: State, msg: Json) -> Json { let head = msg.you.body[0]; let target = find_target(&msg); let path = find_path(&msg, &head, &target); let gs = GameState{ target: *target, path: path, }; if let Some(x) = cache.lock().expect("wanted cache to be unlockable").get_mut(&msg.game.id) { *x = gs; }; Json(battlesnake::StartResponse{ color: "#5ce8c3".to_string(), head_type: "beluga".to_string(), tail_type: "skinny".to_string(), }) } fn find_path( msg: &battlesnake::SnakeRequest, head: &battlesnake::Coord, target: &battlesnake::Coord ) -> Option> { let path = pathfinding::directed::astar::astar( head, |n| msg.board.safe_neighbors(n).into_iter(), |n| (battlesnake::manhattan(n, &target) as usize), |n| n == target, ); match path { None => return None, Some(x) => { return Some(x.0); }, } } #[post("/move", format = "json", data = "")] fn make_move(cache: State, msg: Json) -> Json { let head = msg.you.body[0]; if let Some(mut gs) = cache.lock().expect("wanted cache to be unlockable").get(&msg.game.id) { let gs_path = gs.path.as_ref().or_else(|| { let target = find_target(&msg); let path = find_path(&msg, &head, &target); gs = &GameState{ target: *target, path: path, }; path.as_ref() }); let mut inner = gs_path.expect("what"); let next = inner[0]; inner.pop(); if inner.len() == 0 { gs.path = None; } return Json(battlesnake::MoveResponse{ move_field: battlesnake::Line{ start: &head, end: &next, }.direction().to_string(), }) } let target = find_target(&msg); let path = find_path(&msg, &head, &target); let gs = GameState{ target: *target, path: path, }; println!("{:?}", gs); Json(battlesnake::MoveResponse { move_field: "up".to_string(), }) } fn find_target<'a>(gs: &'a battlesnake::SnakeRequest) -> &'a battlesnake::Coord { let head = &gs.you.body[0]; if gs.you.health > 30 { let mut lowest_score: u32 = 99999; let mut coord: &battlesnake::Coord = &gs.you.body.last().unwrap(); for food in &gs.board.food { let score = battlesnake::manhattan(&head, &food); if score < lowest_score { lowest_score = score; coord = food; } } return coord; } return gs.you.body.last().unwrap(); } fn main() { let map = HashMap::::new(); let mutex_map = Mutex::from(map); rocket::ignite().mount("/", routes![ index, begin, ping, make_move, ]) .manage(mutex_map) .launch(); }