summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 5ea9eccb8a6f9796c0e3b81af05f8f47a90eda89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
extern crate json;
extern crate rand;

mod actions;
mod math;
mod files;
mod ships;

use actions::*;
use math::*;
use files::*;
use ships::*;

use std::path::PathBuf;

pub fn write_move(working_dir: PathBuf) -> Result<(), String> {
    let state = read_file(&working_dir)?;

    let is_place_phase = state["Phase"] == 1;
    let map_dimension = state["MapDimension"]
        .as_u16()
        .ok_or("Did not find the map dimension in the state json file")?;

    let action = if is_place_phase {
        place_ships()
    }
    else {
        shoot_randomly(map_dimension)
    };

    write_action(&working_dir, is_place_phase, action)
        .map_err(|e| format!("Failed to write action to file. Error: {}", e))?;
    
    Ok(())
}


fn place_ships() -> Action {
    let ships = vec!(
        (Ship::Battleship, Point::new(1, 0), Orientation::North),
        (Ship::Carrier, Point::new(3, 1), Orientation::East),
        (Ship::Cruiser, Point::new(4, 2), Orientation::North),
        (Ship::Destroyer, Point::new(7, 3), Orientation::North),
        (Ship::Submarine, Point::new(1, 8), Orientation::East)
    );
    
    Action::PlaceShips(ships)
}

fn shoot_randomly(map_dimension: u16) -> Action {
    Action::Shoot(random_point(map_dimension))
}