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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
use math::*;
use ships::*;
use std::fmt;
use std::collections::HashSet;
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Action {
PlaceShips(Vec<ShipPlacement>),
Shoot(Weapon, Point)
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Action::Shoot(w, p) => writeln!(f, "{},{},{}", w, p.x, p.y),
&Action::PlaceShips(ref ships) => ships.iter().map(|ref ship| {
writeln!(f, "{} {} {} {}", ship.ship_type, ship.point.x, ship.point.y, ship.direction)
}).fold(Ok(()), |acc, next| acc.and(next))
}
}
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct ShipPlacement {
ship_type: Ship,
point: Point,
direction: Direction
}
impl ShipPlacement {
pub fn new(ship_type: Ship, point: Point, direction: Direction) -> ShipPlacement {
ShipPlacement {
ship_type: ship_type,
point: point,
direction: direction
}
}
pub fn valid(&self, map_size: u16) -> bool {
let start = self.point;
let end = start.move_point(self.direction, self.ship_type.length() as i32, map_size);
start.x < map_size && start.y < map_size && end.is_some()
}
pub fn valid_placements(placements: &Vec<ShipPlacement>, map_size: u16) -> bool {
let mut occupied = HashSet::new();
let individuals_valid = placements.iter().all(|p| p.valid(map_size));
let mut no_overlaps = true;
for placement in placements {
for i in 0..placement.ship_type.length() as i32 {
match placement.point.move_point(placement.direction, i, map_size) {
Some(block) => {
no_overlaps = no_overlaps && !occupied.contains(&block);
occupied.insert(block);
},
None => {
//invalid case here is handled above
}
}
}
//block out the area around the current ship to prevent adjacent ships
for i in 0..placement.ship_type.length() as i32 {
match placement.point.move_point(placement.direction, i, map_size) {
Some(current_block) => {
if let Some(p) = current_block.move_point(Direction::North, 1, map_size) {
occupied.insert(p);
}
if let Some(p) = current_block.move_point(Direction::South, 1, map_size) {
occupied.insert(p);
}
if let Some(p) = current_block.move_point(Direction::East, 1, map_size) {
occupied.insert(p);
}
if let Some(p) = current_block.move_point(Direction::West, 1, map_size) {
occupied.insert(p);
}
},
None => {
//invalid case here is handled above
}
}
}
}
individuals_valid && no_overlaps
}
}
|