summaryrefslogtreecommitdiff
path: root/server/src/state.rs
blob: e368317c97ce283846b55ad00f47f422595a09bd (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
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
/*
    Hurry Curry! - a game about cooking
    Copyright 2024 metamuffin

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
use crate::{server::Server, ConnectionID};
use anyhow::{bail, Result};
use hurrycurry_protocol::{Message, PacketC, PacketS, PlayerID};
use log::{debug, trace};

impl Server {
    pub async fn tick_outer(&mut self, dt: f32) -> anyhow::Result<()> {
        let r = self.tick(dt);
        if let Some((name, timer)) = r {
            self.scoreboard.save().await?;
            self.load(self.index.generate(&name).await?, timer);
        }
        while let Some(p) = self.packet_out.pop_front() {
            if matches!(p, PacketC::UpdateMap { .. } | PacketC::Movement { .. }) {
                trace!("-> {p:?}");
            } else {
                debug!("-> {p:?}");
            }
            self.tx.send(p).unwrap();
        }
        Ok(())
    }
    pub async fn packet_in_outer(
        &mut self,
        conn: ConnectionID,
        packet: PacketS,
    ) -> Result<Vec<PacketC>> {
        if let Some(p) = get_packet_player(&packet) {
            if !self.connections.entry(conn).or_default().contains(&p) {
                bail!("Packet sent to a player that is not owned by this connection.");
            }
        }
        let mut replies = Vec::new();
        match &packet {
            PacketS::Communicate {
                message: Some(Message::Text(text)),
                timeout: None,
                player,
            } if let Some(command) = text.strip_prefix("/") => {
                match self.handle_command_parse(*player, command).await {
                    Ok(packets) => return Ok(packets),
                    Err(e) => {
                        return Ok(vec![PacketC::ServerMessage {
                            text: format!("{e}"),
                        }]);
                    }
                }
            }
            PacketS::Leave { player } => {
                self.connections.entry(conn).or_default().remove(player);
            }
            PacketS::Join { .. } => {
                if self.connections.entry(conn).or_default().len() > 8 {
                    bail!("Players-per-connection limit exceeded.")
                }
            }
            _ => (),
        }
        self.packet_in(packet, &mut replies)?;

        for p in &replies {
            match p {
                PacketC::Joined { id } => {
                    self.connections.entry(conn).or_default().insert(*id);
                }
                _ => (),
            }
        }

        if self.count_chefs() <= 0 && !self.game.lobby {
            self.tx
                .send(PacketC::ServerMessage {
                    text: "Game was aborted due to a lack of players".to_string(),
                })
                .ok();
            self.load(self.index.generate("lobby").await?, None);
        }
        Ok(replies)
    }

    pub async fn disconnect(&mut self, conn: ConnectionID) {
        if let Some(players) = self.connections.get(&conn) {
            for player in players.to_owned() {
                let _ = self.packet_in_outer(conn, PacketS::Leave { player }).await;
            }
        }
        self.connections.remove(&conn);
    }
}

fn get_packet_player(packet: &PacketS) -> Option<PlayerID> {
    match packet {
        PacketS::Join { .. } => None,
        PacketS::Leave { player } => Some(*player),
        PacketS::Movement { player, .. } => Some(*player),
        PacketS::Interact { player, .. } => Some(*player),
        PacketS::Communicate { player, .. } => Some(*player),
        PacketS::ReplaceHand { player, .. } => Some(*player),
        PacketS::ApplyScore(_) => None,
        PacketS::ReplayTick { .. } => None,
    }
}