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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use super::Responder;
use super::Identity;
use super::LifeStatus;

const NET_ERR: &str = "network error";

pub struct Human {
    username: String,
    role: Identity,
    client: TcpStream,
    id: usize,
    status: LifeStatus,
}

/// 给已连接玩家发送一个 `+` 表示新增一名玩家。
fn reley_prev(clients: &mut Vec<Human>) {
    clients.iter_mut().for_each(|x| x.send("+"));
}

/// 发送已连接玩家数和总玩家数。
fn return_num(client: &mut Human, pos: usize, len: usize) {
    client.send_number(pos);
    client.send_number(len);
}


/// 人类玩家建立连接。需要在每次新连接建立时给已经建立的玩家发送信号以更新进度条。
pub fn build_connect(addr: &String, num: usize) -> Vec<Box<dyn Responder>> {
    let listener = TcpListener::bind(&addr).expect(NET_ERR);
    let mut clients = Vec::new();
    let mut cnt = 0;
    for c in listener.incoming() {
        if let Ok(stream) = c {
            cnt += 1;
            println!("{} connected", stream.peer_addr().unwrap());
            let mut cur = Human::new(stream);
            reley_prev(&mut clients);
            return_num(&mut cur, cnt, num);
            clients.push(cur);
            if cnt == num { break; }
        }
    }
    clients.into_iter().map(|x| Box::new(x) as Box<(dyn Responder)>).collect()
}

impl Human {
    pub fn new(client: TcpStream) -> Self {
        Human { 
            client, 
            role: Identity::Raw,
            username: String::new(),
            id: 0,
            status: LifeStatus::Alive,
        }
    }

    /// `TcpStream` 是流式的,不区分多条信息。这里用蜂鸣器控制字符作为分隔不同信息的方式。
    fn read_line(&mut self) -> Vec<u8> {
        let mut buf: [u8; 1] = [0];
        let mut res = Vec::new();
        loop {
            match self.client.read_exact(&mut buf) {
                Ok(_) => {
                    if buf[0] == 0x7 {
                        break;
                    }
                    res.push(buf[0]);
                }
                Err(_) => {
                    break;
                }
            }
        }
        res
    }
}

impl Responder for Human {
    fn rec(&mut self) -> String {
        let msg = self.read_line();
        let res = String::from_utf8(msg).unwrap();
        #[cfg(debug_assertions)]
        println!("rec {}", res);
        res
    }

    fn send(&mut self, msg: &str) {
        let msg = format!("{}\x07",msg);
        #[cfg(debug_assertions)]
        println!("sended {}", msg);
        self.client.write_all(msg.as_bytes()).unwrap();
    }

    fn set_status(&mut self, s: LifeStatus) {
        self.status = s;
    }

    fn status(&self) -> LifeStatus {
        self.status
    }

    fn set_role(&mut self, r: Identity) {
        self.role = r;
    }

    fn role(&self) -> Identity {
        self.role.clone()
    }

    fn set_name(&mut self) {
        self.username = self.rec_text();
    }

    fn name(&self) -> String {
        format!("{}({} 号)", self.username, self.id)
    }

    fn set_id(&mut self, id: usize) {
        self.id = id;
    }

    fn get_id(&self) -> usize {
        self.id
    }
}