summaryrefslogtreecommitdiff
path: root/game_server/src/lobby.rs
blob: 6d11a5fcc289c41bafc82513fec66088e2da0c21 (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
56
57
58
59
60
61
62
63
use std::collections::HashMap;

use crate::group::{Group, GroupId};
use crate::scribble_group::ScribbleGroup;

use crate::server::{UserId, GameClient, GameServerError};

pub struct Lobby {
    groups: HashMap<GroupId, Box<Group>>,
}

#[allow(dead_code)]
impl Lobby {
    pub fn new() -> Self {
        Self {
            groups: HashMap::new(),
        }
    }

    fn generate_group(group_type: &str, id: GroupId, name: &str) -> Option<Box<Group>> {
        match group_type {
            "scribble" => {
                Some(Box::new(ScribbleGroup::new(id, name.to_string())))
            },
            _ => None,
        }
    }

    pub fn add_group(&mut self, group: Box<Group>) {
        self.groups.insert(group.id(), group);
    }

    pub fn add_client(&mut self, group_type: &str, group_id: GroupId, group_name: &str,
                   user_id: UserId, client: GameClient) -> Result<(), GameServerError> {
        if !self.groups.contains_key(&group_id) {
            let mut group = match Self::generate_group(group_type, group_id, group_name) {
                    Some(x) => x,
                    _ => return Err(GameServerError::GroupCreationError(format!("failed to generate '{}' group", group_type))),
            };
            group.run();
            self.groups.insert(group_id, group);
        }
        let group = self.groups.get_mut(&group_id).unwrap();
        group.add_client(user_id, client)
    }

    pub fn iter<'b>(&'b self) -> GroupIterator<'b> {
        GroupIterator { groups: self.groups.values() }
    }
}

#[allow(dead_code)]
pub struct GroupIterator<'a> {
    groups: std::collections::hash_map::Values<'a, GroupId, Box<Group>>
}

impl<'a> Iterator for GroupIterator<'a> {
    type Item = &'a Box<Group>;

    fn next(&mut self) -> Option<Self::Item> {
        self.groups.next()
    }
}