335 lines
11 KiB
Rust
335 lines
11 KiB
Rust
// Dancing Droids
|
|
// Copyright (C) 2020 Martin HART, Volodymyr PATUTA, Stephane Elias BENABDESLAM
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
// GNU General Public License for more details.
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
extern crate pest;
|
|
#[macro_use]
|
|
extern crate pest_derive;
|
|
|
|
use clap::{App, Arg};
|
|
use pest::Parser;
|
|
use rand::Rng;
|
|
use std::collections::HashMap;
|
|
use std::fs;
|
|
use std::io;
|
|
|
|
mod robot;
|
|
mod world;
|
|
|
|
#[derive(Parser)]
|
|
#[grammar = "../conf.pest"]
|
|
pub struct ConfParser;
|
|
|
|
/// Check if the robot is in the map.
|
|
fn check_map(r: &robot::Robot, w: &world::World) -> Result<(), String> {
|
|
if r.p.x < 0 || r.p.y < 0 || r.p.x > w.x || r.p.y > w.y {
|
|
Err(format!("The robot {} is off map", r.id))
|
|
} else {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// Check if the robot collide with another one at the given position.
|
|
fn check_collisions(r: &robot::Robot, h: &HashMap<robot::Position, u32>) -> Result<(), String> {
|
|
match h.get(&r.p) {
|
|
Some(&x) => Err(format!(
|
|
"The robot id: {} collided with robot id: {} in position: ({};{}) !",
|
|
&r.id, x, &r.p.x, &r.p.y
|
|
)),
|
|
None => Ok(()),
|
|
}
|
|
}
|
|
|
|
/// Creates HashMap of robot position and it's id.
|
|
fn create_hash_map(pool: &Vec<robot::Robot>, hash: &mut HashMap<robot::Position, u32>) {
|
|
for r in pool {
|
|
hash.insert(robot::Position { x: r.p.x, y: r.p.y }, r.id);
|
|
}
|
|
}
|
|
|
|
/// Generate random instructions.
|
|
fn gen_random_instructions() -> String {
|
|
let mut rng = rand::thread_rng();
|
|
let n = rng.gen_range(5, 10);
|
|
let mut instructions = String::with_capacity(n);
|
|
const CHARSET: &[u8] = b"LRF";
|
|
for _ in 0..n {
|
|
let l = rng.gen_range(0, CHARSET.len());
|
|
instructions.push(CHARSET[l] as char);
|
|
}
|
|
|
|
instructions
|
|
}
|
|
|
|
/// Parse the config file, generate the world and robot pool.
|
|
fn parse_config(conf: String, pool: &mut Vec<robot::Robot>) -> Result<world::World, String> {
|
|
let mut lines: Vec<&str> = conf.split('\n').collect();
|
|
let raw_world = match ConfParser::parse(Rule::world, lines.remove(0)) {
|
|
Ok(s) => s.as_str(),
|
|
Err(_) => return Err(String::from("World config is broken.")),
|
|
};
|
|
let mut w: Vec<i32> = Vec::with_capacity(2);
|
|
for n in raw_world.split_whitespace() {
|
|
let v: i32 = n.parse::<i32>().unwrap();
|
|
w.push(v);
|
|
}
|
|
let world = world::World { x: w[0], y: w[1] };
|
|
lines.remove(0);
|
|
let mut r_id: u32 = 0;
|
|
loop {
|
|
r_id += 1;
|
|
if lines.len() == 0 {
|
|
break;
|
|
}
|
|
let raw_setup = match ConfParser::parse(Rule::robot_init, lines.remove(0)) {
|
|
Ok(s) => s.as_str(),
|
|
Err(_) => return Err(String::from("Robot setup is broken.")),
|
|
};
|
|
|
|
let rand_instructions = gen_random_instructions();
|
|
let l = lines.remove(0);
|
|
|
|
let instructions = match ConfParser::parse(Rule::robot_instructions, l) {
|
|
Ok(s) => s.as_str(),
|
|
Err(_) => rand_instructions.as_str(),
|
|
};
|
|
|
|
let mut setup = raw_setup.split_whitespace();
|
|
let pos_x = setup.next().unwrap();
|
|
let pos_y = setup.next().unwrap();
|
|
let orientation = setup.next().unwrap();
|
|
// Convert values of the setup line
|
|
let r_x = pos_x.parse::<i32>().unwrap();
|
|
let r_y = pos_y.parse::<i32>().unwrap();
|
|
let r_o = match orientation {
|
|
"N" => robot::Orientation::N,
|
|
"E" => robot::Orientation::E,
|
|
"S" => robot::Orientation::S,
|
|
"W" => robot::Orientation::W,
|
|
_ => {
|
|
return Err(String::from(
|
|
"The third token of the setup line do not match any orientations !",
|
|
))
|
|
}
|
|
};
|
|
if !robot::is_instructions(instructions) {
|
|
return Err(String::from("Invalid instructions !"));
|
|
}
|
|
|
|
let inst = robot::instructions_from_string(instructions.chars().rev().collect::<String>())?;
|
|
|
|
let r = robot::Robot::new(r_id, r_o, robot::Position { x: r_x, y: r_y }, inst);
|
|
// Load robot inside the pool.
|
|
match check_map(&r, &world) {
|
|
Ok(()) => pool.push(r),
|
|
Err(err) => return Err(err),
|
|
}
|
|
|
|
if lines.len() == 0 {
|
|
break;
|
|
}
|
|
if l.len() == 0 {
|
|
continue;
|
|
}
|
|
lines.remove(0);
|
|
}
|
|
|
|
Ok(world)
|
|
}
|
|
|
|
/// Retrieve the content of a file and return it as a string.
|
|
fn open_file(filename: &str) -> io::Result<String> {
|
|
let content = fs::read_to_string(filename)?;
|
|
Ok(content)
|
|
}
|
|
|
|
/// Here we display the grid by looping in every position checking if it exists in the HashMap.
|
|
fn display_grid(
|
|
w: &world::World,
|
|
robot_pool: &Vec<robot::Robot>,
|
|
h: &HashMap<robot::Position, u32>,
|
|
) -> String {
|
|
let mut grid = String::new();
|
|
for i in (0..w.y + 1).rev() {
|
|
if i < 10 {
|
|
grid = format!("{}{} ", grid, i);
|
|
} else {
|
|
grid = format!("{}{} ", grid, i);
|
|
}
|
|
for j in 0..w.x + 1 {
|
|
match h.get(&robot::Position { x: j, y: i }) {
|
|
Some(id) => match robot_pool[(id - 1) as usize].o {
|
|
robot::Orientation::N => grid = format!("{}↑ ", grid),
|
|
robot::Orientation::E => grid = format!("{}→ ", grid),
|
|
robot::Orientation::S => grid = format!("{}↓ ", grid),
|
|
robot::Orientation::W => grid = format!("{}← ", grid),
|
|
},
|
|
|
|
None => grid = format!("{}. ", grid),
|
|
}
|
|
}
|
|
grid = format!("{}\n", grid);
|
|
}
|
|
grid = format!("{} ", grid);
|
|
for j in 0..w.x + 1 {
|
|
if j < 10 {
|
|
grid = format!("{}{} ", grid, j);
|
|
} else {
|
|
grid = format!("{}{} ", grid, j);
|
|
}
|
|
}
|
|
grid = format!("{}\n", grid);
|
|
grid
|
|
}
|
|
|
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|
// We handle CLI flags here.
|
|
let matches = App::new("DancingDroids")
|
|
.version("0.3.0")
|
|
.about("When droids dance togethers")
|
|
.arg(
|
|
Arg::with_name("file")
|
|
.short("f")
|
|
.long("file")
|
|
.takes_value(true)
|
|
.help("Configuration file"),
|
|
)
|
|
.arg(
|
|
Arg::with_name("random-world")
|
|
.short("w")
|
|
.long("random-world")
|
|
.takes_value(false)
|
|
.help("Generate random world"),
|
|
)
|
|
.get_matches();
|
|
|
|
let raw_conf = open_file(matches.value_of("file").unwrap_or("two_robots.txt"))?;
|
|
|
|
let mut robot_pool: Vec<robot::Robot> = Vec::new();
|
|
let mut world: world::World = parse_config(raw_conf, &mut robot_pool)?;
|
|
world = match matches.is_present("random-world") {
|
|
false => world,
|
|
true => world::random_world(),
|
|
};
|
|
|
|
let mut hash: HashMap<robot::Position, u32> = HashMap::new();
|
|
create_hash_map(&robot_pool, &mut hash);
|
|
let mut print_all = format!("World {{ x_max = {}; y_max = {} }}\n", world.x, world.y);
|
|
print_all = format!("{}{}", print_all, robot::print_robots(&robot_pool));
|
|
if world.x <= 60 && world.y <= 45 {
|
|
print_all = format!("{}Initial state\n", print_all);
|
|
print_all = format!("{}==============\n", print_all);
|
|
print_all = format!("{}{}", print_all, display_grid(&world, &robot_pool, &hash));
|
|
}
|
|
loop {
|
|
let mut piouff: u32 = 0;
|
|
for r in &mut robot_pool {
|
|
if robot::is_piouff(&r) {
|
|
piouff += 1;
|
|
} else {
|
|
hash.remove(&r.p);
|
|
r.execute_instruction();
|
|
check_map(&r, &world)?;
|
|
check_collisions(&r, &hash)?;
|
|
hash.insert(robot::Position { x: r.p.x, y: r.p.y }, r.id);
|
|
}
|
|
}
|
|
if world.x <= 60 && world.y <= 45 {
|
|
std::thread::sleep(std::time::Duration::from_millis(600));
|
|
print!("\x1B[2J\x1B[1;1H");
|
|
print!("{}", display_grid(&world, &robot_pool, &hash));
|
|
}
|
|
if piouff == robot_pool.len() as u32 {
|
|
break;
|
|
}
|
|
}
|
|
print!("\x1B[2J\x1B[1;1H");
|
|
print!("{}", print_all);
|
|
if world.x <= 60 && world.y <= 45 {
|
|
println!("Final state");
|
|
println!("============");
|
|
print!("{}", display_grid(&world, &robot_pool, &hash));
|
|
}
|
|
for r in &robot_pool {
|
|
println!("Robot id: {}: Final position: ({}, {})", r.id, r.p.x, r.p.y);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn test_open_file() {
|
|
assert!(open_file("two_robots.txt").is_ok());
|
|
assert!(open_file("test_unexisting_file.extension").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn test_check_map() {
|
|
let r = robot::Robot::new(
|
|
0,
|
|
robot::Orientation::N,
|
|
robot::Position { x: 2, y: 3 },
|
|
vec![robot::Instruction::F],
|
|
);
|
|
let w = world::World { x: 10, y: 10 };
|
|
|
|
assert!(check_map(&r, &w).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
#[should_panic]
|
|
fn test_check_map_fail() {
|
|
let r = robot::Robot::new(
|
|
0,
|
|
robot::Orientation::N,
|
|
robot::Position { x: 2, y: 4 },
|
|
vec![robot::Instruction::F],
|
|
);
|
|
let w = world::World { x: 3, y: 3 };
|
|
|
|
assert!(check_map(&r, &w).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
#[should_panic]
|
|
fn test_check_collisions() {
|
|
let r = robot::Robot::new(
|
|
0,
|
|
robot::Orientation::N,
|
|
robot::Position { x: 2, y: 3 },
|
|
vec![robot::Instruction::F],
|
|
);
|
|
|
|
let mut h: HashMap<robot::Position, u32> = HashMap::new();
|
|
h.insert(robot::Position { x: 2, y: 3 }, 1);
|
|
assert!(check_collisions(&r, &h).is_ok());
|
|
}
|
|
#[test]
|
|
fn test_parse() {
|
|
let conf: String = String::from("5 5\n\n1 1 N\nFLLFRF\n\n3 2 S\nFFLFRRF\n");
|
|
let mut robot_pool: Vec<robot::Robot> = Vec::new();
|
|
assert!(parse_config(conf, &mut robot_pool).is_ok());
|
|
let conf: String = String::from("5 a\n\n1 1 N\nFLLFRF\n\n3 2 S\nFFLFRRF\n");
|
|
assert!(parse_config(conf, &mut robot_pool).is_err());
|
|
let conf: String = String::from("5 5\n\n1 1 N\nZLLFRF\n\n3 2 S\nFFLFRRF\n");
|
|
assert!(parse_config(conf, &mut robot_pool).is_err());
|
|
let conf: String = String::from("5 5\n\n1 1 R\nFLLFRF\n\n3 2 S\nFFLFRRF\n");
|
|
assert!(parse_config(conf, &mut robot_pool).is_err());
|
|
}
|
|
}
|