Add networking as player constructor
+2
src/main.rs
+2
src/main.rs
+38
src/network.rs
+38
src/network.rs
···
···
1
+
use std::net::{SocketAddr, TcpListener, TcpStream};
2
+
3
+
pub enum NetworkError {
4
+
IO(std::io::Error),
5
+
NoIncomingConnexionError,
6
+
}
7
+
8
+
impl From<std::io::Error> for NetworkError {
9
+
fn from(value: std::io::Error) -> Self {
10
+
NetworkError::IO(value)
11
+
}
12
+
}
13
+
14
+
struct TcpPlayer {
15
+
connexion_stream: TcpStream,
16
+
}
17
+
18
+
impl TcpPlayer {
19
+
pub fn host(addr: SocketAddr) -> Result<TcpPlayer, NetworkError> {
20
+
let listener = TcpListener::bind(addr)?;
21
+
let mut streams = listener.incoming();
22
+
let stream = streams
23
+
.next()
24
+
.ok_or(NetworkError::NoIncomingConnexionError)??;
25
+
26
+
Ok(TcpPlayer {
27
+
connexion_stream: stream,
28
+
})
29
+
}
30
+
31
+
pub fn join(addr: SocketAddr) -> Result<TcpPlayer, NetworkError> {
32
+
let stream = TcpStream::connect(addr)?;
33
+
34
+
Ok(TcpPlayer {
35
+
connexion_stream: stream,
36
+
})
37
+
}
38
+
}
+4
-4
src/parser.rs
+4
-4
src/parser.rs
···
22
23
impl Vector2u16 {
24
pub fn new(x: u16, y: u16) -> Self {
25
-
Vector2u16 { x: x, y: y }
26
}
27
}
28
···
35
impl Boat {
36
pub fn new(first_pos: Vector2u16, last_pos: Vector2u16) -> Self {
37
Boat {
38
-
first_pos: first_pos,
39
-
last_pos: last_pos,
40
}
41
}
42
}
43
44
pub fn parse_file(file_path: &Path) -> Result<[Boat; 4], ParserError> {
45
let mut file = File::open(file_path)?;
46
-
Ok(parse_ships(&mut file)?)
47
}
48
49
pub fn parse_ships<T: Read>(file: &mut T) -> Result<[Boat; 4], ParserError> {
···
22
23
impl Vector2u16 {
24
pub fn new(x: u16, y: u16) -> Self {
25
+
Vector2u16 { x, y }
26
}
27
}
28
···
35
impl Boat {
36
pub fn new(first_pos: Vector2u16, last_pos: Vector2u16) -> Self {
37
Boat {
38
+
first_pos,
39
+
last_pos,
40
}
41
}
42
}
43
44
pub fn parse_file(file_path: &Path) -> Result<[Boat; 4], ParserError> {
45
let mut file = File::open(file_path)?;
46
+
parse_ships(&mut file)
47
}
48
49
pub fn parse_ships<T: Read>(file: &mut T) -> Result<[Boat; 4], ParserError> {