Implement Map tick method

This commit is contained in:
2017-10-31 19:57:45 +01:00
parent 2137fbd565
commit 6b81b6bc40
2 changed files with 57 additions and 1 deletions

View File

@ -1,7 +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 }; use util::{ translate_position, step_in_direction };
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub enum Tile<'a> { pub enum Tile<'a> {
@ -126,6 +126,47 @@ impl Map {
let (x,y) = coordinate; let (x,y) = coordinate;
x < 0 || x >= self.width || y < 0 || y >= self.height x < 0 || x >= self.width || y < 0 || y >= self.height
} }
pub fn tick(&self, decisions: Vec<Direction>) -> Map {
if decisions.len() < self.snakeInfos.len() {
panic!("All snakes have to make a decision");
}
let worldTick = self.worldTick + 1;
let mut newSnakeInfos: Vec<SnakeInfo> = vec![];
let grow_snakes: bool = worldTick % 3 == 1;
if !grow_snakes {
for i in 0..newSnakeInfos.len() {
newSnakeInfos[i].positions.pop();
}
}
for i in 0..self.snakeInfos.len() {
let snake: &mut SnakeInfo = &mut newSnakeInfos[i];
if(self.can_snake_move_in_direction(snake, decisions[i])) {
let head_position = snake.positions[0].clone();
snake.positions.insert(0,
step_in_direction(
head_position,
decisions[i],
self.width
),
);
}
}
Map {
width: self.width.clone(),
height: self.height.clone(),
worldTick: worldTick,
snakeInfos: newSnakeInfos,
foodPositions: self.foodPositions.clone(),
obstaclePositions: self.obstaclePositions.clone(),
}
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1,3 +1,5 @@
use maputil::{ Direction };
#[allow(dead_code)] #[allow(dead_code)]
pub fn vector_diff(a: (i32, i32), b: (i32, i32)) -> (i32,i32) {( pub fn vector_diff(a: (i32, i32), b: (i32, i32)) -> (i32,i32) {(
a.0 - b.0, a.0 - b.0,
@ -15,6 +17,19 @@ pub fn translate_position(position: i32, map_width: i32) -> (i32,i32) {
(x as i32, y as i32) (x as i32, y as i32)
} }
#[allow(dead_code)]
pub fn step_in_direction(position: i32, direction: Direction, map_width: i32) -> i32 {
let xy = translate_position(position, map_width);
let dxy = match direction {
Direction::Down => (xy.0, xy.1 + 1),
Direction::Up => (xy.0, xy.1 - 1),
Direction::Left => (xy.0 - 1, xy.1),
Direction::Right => (xy.0 + 1, xy.1),
};
translate_coordinate(dxy, map_width)
}
#[allow(dead_code)] #[allow(dead_code)]
pub fn translate_positions(positions: &Vec<i32>, map_width: i32) -> Vec<(i32,i32)> { pub fn translate_positions(positions: &Vec<i32>, map_width: i32) -> Vec<(i32,i32)> {
positions.into_iter().map(|pos| translate_position(*pos, map_width)).collect() positions.into_iter().map(|pos| translate_position(*pos, map_width)).collect()