mahjong_core/game/
players.rs

1use crate::macros::derive_game_common;
2use rand::{seq::SliceRandom, thread_rng};
3use ts_rs::TS;
4use uuid::Uuid;
5
6pub type PlayerId = String;
7
8pub type PlayersVec = Vec<PlayerId>;
9
10derive_game_common! {
11#[derive(Default, TS)]
12pub struct Players(pub PlayersVec);
13}
14
15impl Players {
16    pub fn new_player() -> PlayerId {
17        Uuid::new_v4().to_string()
18    }
19}
20
21impl Players {
22    pub fn swap(&mut self, p1: &PlayerId, p2: &PlayerId) {
23        let p1idx = self.0.iter().position(|x| x == p1).unwrap();
24        let p2idx = self.0.iter().position(|x| x == p2).unwrap();
25
26        self.0.swap(p1idx, p2idx);
27    }
28}
29
30// Proxied methods
31impl Players {
32    pub fn len(&self) -> usize {
33        self.0.len()
34    }
35
36    pub fn iter(&self) -> std::slice::Iter<'_, PlayerId> {
37        self.0.iter()
38    }
39
40    pub fn get(&self, index: usize) -> Option<&PlayerId> {
41        self.0.get(index)
42    }
43
44    pub fn is_empty(&self) -> bool {
45        self.0.is_empty()
46    }
47
48    pub fn first(&self) -> &PlayerId {
49        self.0.first().unwrap()
50    }
51}
52
53// Proxied methods
54impl Players {
55    pub fn push(&mut self, player_id: PlayerId) {
56        self.0.push(player_id);
57    }
58
59    pub fn shuffle(&mut self) {
60        self.0.shuffle(&mut thread_rng());
61    }
62}