summaryrefslogtreecommitdiff
path: root/src/server/navigation.rs
blob: eb9095de2dbe4a2024b4370b81ea21d5f6fae115 (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
extern crate serde_json;

use std::collections::HashMap;
use std::io::BufRead;
use std::io::Write;

use crate::mass::{Mass, MassType};
use crate::math::distance;
use crate::server::connection::ServerConnection;

impl ServerConnection {
    pub fn server_navigation(&mut self, masses: &mut HashMap<String, Mass>) {
        let mut ship = masses.remove(&self.name).unwrap();
        let ship_clone = ship.clone();

        if let MassType::Ship {
            ref mut navigation, ..
        } = ship.mass_type
        {
            let navigation = navigation.as_mut().unwrap();
            navigation.verify_target(ship_clone.position, &masses);
            let mut within_range: HashMap<&String, &Mass> = masses
                .iter()
                .filter(|&(_, mass)| {
                    distance(ship_clone.position, mass.position) < navigation.range
                })
                .collect();
            within_range.insert(&self.name, &ship_clone);

            if self.open {
                let send = serde_json::to_string(&within_range).unwrap() + "\n";

                if let Err(_err) = self.stream.write(send.as_bytes()) {
                    self.open = false;
                };

                let mut recv = String::new();
                if let Ok(result) = self.buff_r.read_line(&mut recv) {
                    if result == 0 {
                        self.open = false;
                    }
                    if !recv.is_empty() {
                        navigation.give_target(recv.replace("\n", ""));
                    }
                }
            }
        }

        masses.insert(self.name.clone(), ship);
    }
}