Initial Commit for snake ten_points_to_slytherin

This commit is contained in:
2017-10-20 21:38:03 +02:00
parent 061da11d43
commit e274bd37e7
8 changed files with 641 additions and 589 deletions

View File

@ -1,7 +1,10 @@
[package] [package]
name = "snakebot_rust" name = "snakebot_rust"
version = "1.1.0" version = "1.1.0"
authors = ["Martin Barksten <martin.barksten@cygni.com>"] authors = [
"Martin Barksten <martin.barksten@cygni.com>",
"Joakim Hulthe <joakim@hulthe.net>",
]
license-file = "LICENSE" license-file = "LICENSE"
[dependencies] [dependencies]

View File

@ -1,5 +1,5 @@
host = "localhost"; host = "localhost";
port = 8080; port = 8080;
snake_name = "rusty-snake"; snake_name = "ten_points_to_slytherin";
venue = "training"; venue = "training";

View File

@ -4,7 +4,7 @@
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json; #[macro_use] extern crate serde_json;
extern crate clap; extern crate clap;
extern crate config; //extern crate config;
extern crate log4rs; extern crate log4rs;
extern crate rustc_version; extern crate rustc_version;
extern crate serde; extern crate serde;
@ -31,9 +31,10 @@ const LOG_TARGET: &'static str = "client";
const HEART_BEAT_S: u64 = 20; const HEART_BEAT_S: u64 = 20;
const CONFIG_FILE: &'static str = "snake.conf"; const CONFIG_FILE: &'static str = "snake.conf";
const DEFAULT_HOST: &'static str = "snake.cygni.se"; //const DEFAULT_HOST: &'static str = "snake.cygni.se";
const DEFAULT_PORT: &'static str = "80"; const DEFAULT_HOST: &'static str = "localhost";
const DEFAULT_SNAKE_NAME: &'static str = "default-rust-snake-name"; const DEFAULT_PORT: &'static str = "8080";
const DEFAULT_SNAKE_NAME: &'static str = "ten_points_to_slytherin";
const DEFAULT_VENUE: &'static str = "training"; const DEFAULT_VENUE: &'static str = "training";
#[derive(Clone, Debug)] #[derive(Clone, Debug)]

View File

@ -1,6 +1,7 @@
use structs::{ Map, SnakeInfo }; use structs::{ Map, SnakeInfo };
use util; use util;
use serde::ser::{ Serialize, Serializer }; use serde::ser::{ Serialize, Serializer };
use util::{ translate_position };
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub enum Tile<'a> { pub enum Tile<'a> {
@ -42,6 +43,18 @@ impl Direction {
Direction::Right => ( 1, 0) Direction::Right => ( 1, 0)
} }
} }
pub fn from_movement_delta(delta: (i32,i32)) -> Direction {
match delta {
(x, y) if y <= -x.abs() => Direction::Up,
(x, y) if y >= x.abs() => Direction::Down,
(x, y) if x <= -y.abs() => Direction::Left,
(x, y) if x >= y.abs() => Direction::Right,
( _, _) => {
panic!(format!("({}, {}) is not a valid movement delta.", delta.0, delta.1))
}
}
}
} }
impl Map { impl Map {
@ -83,6 +96,10 @@ impl Map {
match tile { match tile {
Tile::Empty { coordinate: _ } => true, Tile::Empty { coordinate: _ } => true,
Tile::Food { coordinate: _ } => true, Tile::Food { coordinate: _ } => true,
Tile::SnakeBody { coordinate: _, snake } => {
snake.tailProtectedForGameTicks == 0 &&
coordinate == translate_position(*snake.positions.last().unwrap(), self.width)
},
_ => false _ => false
} }
} }

View File

@ -36,7 +36,7 @@ pub enum Inbound {
pub fn handle_inbound_msg(s: &str) -> Result<Inbound, Error> { pub fn handle_inbound_msg(s: &str) -> Result<Inbound, Error> {
let mut json_value = from_str::<Value>(s) let mut json_value = from_str::<Value>(s)
.expect(&format!("Couldn't parse string into JSON: {:?}", s)); .expect(&format!("Couldn't parse string into JSON: {:?}", s));
let mut map = json_value.as_object_mut() let map = json_value.as_object_mut()
.expect(&format!("Couldn't parse string into JSON object: {:?}", s)); .expect(&format!("Couldn't parse string into JSON object: {:?}", s));
let type_value = map.remove("type").expect(&format!("Couldn't find key `type` in: {:?}", &map)); let type_value = map.remove("type").expect(&format!("Couldn't find key `type` in: {:?}", &map));
let type_str = type_value.as_str().expect(&format!("Couldn't turn JSON Value into string: {:?}", &map)); let type_str = type_value.as_str().expect(&format!("Couldn't turn JSON Value into string: {:?}", &map));
@ -85,4 +85,3 @@ pub fn render_outbound_message(msg: Outbound) -> String {
}), }),
}).to_string() }).to_string()
} }

View File

@ -1,6 +1,6 @@
use structs::{ MapUpdate, GameEnded, TournamentEnded, SnakeDead, GameStarting, PlayerRegistered, InvalidPlayerName }; use structs::{ MapUpdate, GameEnded, TournamentEnded, SnakeDead, GameStarting, PlayerRegistered, InvalidPlayerName };
use maputil::{ Direction }; use maputil::{ Direction };
use util::{ translate_positions }; use util::{ translate_positions, translate_position, vector_diff };
const LOG_TARGET: &'static str = "snake"; const LOG_TARGET: &'static str = "snake";
@ -11,11 +11,36 @@ impl Snake {
debug!(target: LOG_TARGET, "Game map updated, tick: {}", msg.gameTick); debug!(target: LOG_TARGET, "Game map updated, tick: {}", msg.gameTick);
let map = &msg.map; let map = &msg.map;
let snake = map.get_snake_by_id(&msg.receivingPlayerId).unwrap(); let directions = vec![Direction::Down, Direction::Left, Direction::Right, Direction::Up];
debug!(target: LOG_TARGET, "Food can be found at {:?}", translate_positions(&map.foodPositions, map.width)); let snake = map.get_snake_by_id(&msg.receivingPlayerId).unwrap();
debug!(target: LOG_TARGET, "My snake positions are {:?}", translate_positions(&snake.positions, map.width)); let snakes = &map.snakeInfos;
for &d in [Direction::Down, Direction::Left, Direction::Right, Direction::Up].into_iter() {
let snake_positions = translate_positions(&snake.positions, map.width);
let foodPositions = translate_positions(&map.foodPositions, map.width);
let facing = match snake_positions.len() {
0...1 => Direction::Right,
_ => Direction::from_movement_delta(vector_diff(snake_positions[0], snake_positions[1]))
};
debug!(target: LOG_TARGET, "Food can be found at {:?}", foodPositions);
debug!(target: LOG_TARGET, "My snake positions are {:?}", snake_positions);
for s in snakes {
if s.positions.len() == 0 || s.id == snake.id {
continue;
}
let tail_position = translate_position(*s.positions.last().unwrap(), map.width);
let tail_direction = Direction::from_movement_delta(vector_diff(tail_position, snake_positions[0]));
if map.can_snake_move_in_direction(snake, tail_direction) {
debug!(target: LOG_TARGET, "Snake will hunt in direction {:?}", tail_direction);
return tail_direction;
}
}
for &d in directions.iter() {
if map.can_snake_move_in_direction(snake, d) { if map.can_snake_move_in_direction(snake, d) {
debug!(target: LOG_TARGET, "Snake will move in direction {:?}", d); debug!(target: LOG_TARGET, "Snake will move in direction {:?}", d);
return d; return d;
@ -25,6 +50,7 @@ impl Snake {
return Direction::Down; return Direction::Down;
} }
pub fn on_game_ended(&self, msg: &GameEnded) { pub fn on_game_ended(&self, msg: &GameEnded) {
debug!(target: LOG_TARGET, "Game ended, the winner is: {:?}", msg.playerWinnerId); debug!(target: LOG_TARGET, "Game ended, the winner is: {:?}", msg.playerWinnerId);
} }

View File

@ -1,3 +1,9 @@
#[allow(dead_code)]
pub fn vector_diff(a: (i32, i32), b: (i32, i32)) -> (i32,i32) {(
a.0 - b.0,
a.1 - b.1,
)}
#[allow(dead_code)] #[allow(dead_code)]
pub fn translate_position(position: i32, map_width: i32) -> (i32,i32) { pub fn translate_position(position: i32, map_width: i32) -> (i32,i32) {
let pos = position as f64; let pos = position as f64;