// 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 . 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) -> 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, hash: &mut HashMap) { for r in pool { hash.insert(robot::Position { x: r.p.x, y: r.p.y }, r.id); } } 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) -> Result { 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(e) => return Err(format!("{}", e)), }; let mut w: Vec = Vec::with_capacity(2); for n in raw_world.split_whitespace() { let v: i32 = match n.parse::() { Ok(x) => x, Err(_) => return Err(String::from("World config is broken.")), }; 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(e) => return Err(format!("{}", e)), }; 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 = match setup.next() { Some(raw) => raw, None => { return Err(String::from( "Could not read the first token of the setup line !", )) } }; let pos_y = match setup.next() { Some(raw) => raw, None => { return Err(String::from( "Could not read the second token of the setup line !", )) } }; let orientation = match setup.next() { Some(raw) => raw, None => { return Err(String::from( "Could not read the third token of the setup line !", )) } }; // Convert values of the setup line let r_x = match pos_x.parse::() { Ok(raw) => raw, Err(_) => { return Err(String::from( "Could not convert the first token of the setup ligne to i32 !", )) } }; let r_y = match pos_y.parse::() { Ok(raw) => raw, Err(_) => { return Err(String::from( "Could not convert the second token of the setup ligne to i32 !", )) } }; 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 !", )) } }; // Convert instructions line. let inst: Vec = instructions.chars().rev().collect(); if !robot::is_instructions(&inst) { return Err(String::from("Invalid instructions !")); } 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 { 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, h: &HashMap, ) { for i in (0..w.y).rev() { if i < 10 { print!("{} ", i); } else { print!("{} ", i); } for j in 0..w.x { match h.get(&robot::Position { x: j, y: i }) { Some(id) => match robot_pool[(id - 1) as usize].o { robot::Orientation::N => print!("↑ "), robot::Orientation::E => print!("→ "), robot::Orientation::S => print!("↓ "), robot::Orientation::W => print!("← "), }, None => print!(". "), } } println!(); } print!(" "); for j in 0..w.x { if j < 10 { print!("{} ", j); } else { print!("{} ", j); } } println!(); } fn main() -> Result<(), Box> { // We handle CLI flags here. let matches = App::new("DancingDroids") .version("0.1.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") .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 = Vec::new(); let world: world::World = match matches.is_present("random-world") { false => parse_config(raw_conf, &mut robot_pool)?, true => world::random_world(), }; let mut hash: HashMap = HashMap::new(); create_hash_map(&robot_pool, &mut hash); println!("World {{ x_max = {}; y_max = {} }}", world.x, world.y); robot::print_robots(&robot_pool); println!("Initial state"); println!("=============="); 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 piouff == robot_pool.len() as u32 { break; } } println!("Final state"); println!("============"); 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!['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!['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!['F'], ); let mut h: HashMap = HashMap::new(); h.insert(robot::Position { x: 2, y: 3 }, 1); assert!(check_collisions(&r, &h).is_ok()); } }