dancing_droids/src/main.rs

275 lines
8.4 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/>.
use clap::{App, Arg};
use std::collections::HashMap;
use std::fs;
use std::io;
mod robot;
mod world;
/// 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(()),
}
}
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);
}
}
/// 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 = conf.lines();
// The first line of the config file should be the World.
let raw_line: &str = match lines.next() {
Some(raw) => raw,
None => {
return Err(String::from(
"Could not read the first line of the config file !",
))
}
};
let mut tokens = raw_line.split_whitespace();
let token1 = match tokens.next() {
Some(raw) => raw,
None => {
return Err(String::from(
"Could not read the first token of the first line !",
))
}
};
let token2 = match tokens.next() {
Some(raw) => raw,
None => {
return Err(String::from(
"Could not read the second token of the first line !",
))
}
};
let x: i32 = match token1.parse::<i32>() {
Ok(x) => x,
Err(_) => {
return Err(String::from(
"Could not convert token one from the first string to i32",
))
}
};
let y: i32 = match token2.parse::<i32>() {
Ok(x) => x,
Err(_) => {
return Err(String::from(
"Could not convert token two from the first string to i32",
))
}
};
let w = world::World { x, y };
let mut r_id: u32 = 0;
loop {
r_id += 1;
// This line should be empty.
let empty_line = match lines.next() {
None => break,
Some(x) => x,
};
if !empty_line.is_empty() {
return Err(String::from("This line should be empty !"));
}
let raw_setup = match lines.next() {
None => return Err(String::from("This line should be the config !")),
Some(raw) => raw,
};
if raw_setup.is_empty() {
return Err(String::from("This line should not be empty !"));
}
let raw_inst = match lines.next() {
None => return Err(String::from("This line should be the instruction !")),
Some(raw) => raw,
};
if raw_inst.is_empty() {
return Err(String::from("This line should not be empty !"));
}
// Parse the setup line of the robot.
let mut setup = raw_setup.split_whitespace();
let pos_x = match setup.next() {
None => {
return Err(String::from(
"Could not read the first token of the setup line !",
))
}
Some(raw) => raw,
};
let pos_y = match setup.next() {
None => {
return Err(String::from(
"Could not read the second token of the setup line !",
))
}
Some(raw) => raw,
};
let orientation = match setup.next() {
None => {
return Err(String::from(
"Could not read the third token of the setup line !",
))
}
Some(raw) => raw,
};
// Convert values of the setup line
let r_x = match pos_x.parse::<i32>() {
Err(_) => {
return Err(String::from(
"Could not convert the first token of the setup ligne to i32 !",
))
}
Ok(raw) => raw,
};
let r_y = match pos_y.parse::<i32>() {
Err(_) => {
return Err(String::from(
"Could not convert the second token of the setup ligne to i32 !",
))
}
Ok(raw) => raw,
};
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<char> = raw_inst.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, &w) {
Ok(()) => pool.push(r),
Err(err) => return Err(err),
}
}
Ok(w)
}
/// 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)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 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"),
)
.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 world: world::World = parse_config(raw_conf, &mut robot_pool)?;
let mut hash: HashMap<robot::Position, u32> = HashMap::new();
create_hash_map(&robot_pool, &mut hash);
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<robot::Position, u32> = HashMap::new();
h.insert(robot::Position { x: 2, y: 3 }, 1);
assert!(check_collisions(&r, &h).is_ok());
}
}