aboutsummaryrefslogtreecommitdiff
path: root/server/src/game.rs
blob: fbbab0a4f06d51b1ac59f3952a345c141c058f0c (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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use crate::protocol::{Item, PacketC, PacketS, Tile, ID};
use anyhow::{anyhow, Result};
use glam::IVec2;
use std::collections::{HashMap, VecDeque};

struct TileData {
    kind: Tile,
    items: Vec<ID>,
    active: bool,
}

struct Player {
    name: String,
    hand: Option<ID>,
}

#[derive(Default)]
pub struct Game {
    item_id_counter: ID,
    tiles: HashMap<IVec2, TileData>,
    items: HashMap<ID, Item>,
    players: HashMap<ID, Player>,
    packet_out: VecDeque<PacketC>,
}

impl Game {
    pub fn new() -> Self {
        let mut g = Self::default();
        for x in -5..5 {
            for y in -5..5 {
                g.tiles.insert(IVec2 { x, y }, Tile::Floor.into());
            }
        }
        for x in -5..5 {
            g.tiles.insert(IVec2 { x, y: -5 }, Tile::Table.into());
            g.tiles.insert(IVec2 { x, y: 4 }, Tile::Table.into());
        }
        for y in -5..5 {
            g.tiles.insert(IVec2 { x: -5, y }, Tile::Table.into());
            g.tiles.insert(IVec2 { x: 4, y }, Tile::Table.into());
        }

        g.tiles.extend(
            [
                ([-5, 1], Tile::Pan),
                ([-5, 2], Tile::Pan),
                ([4, 3], Tile::Pan),
            ]
            .map(|(k, v)| {
                (
                    IVec2::from_array(k),
                    TileData {
                        active: false,
                        items: vec![],
                        kind: v,
                    },
                )
            }),
        );

        g
    }

    pub fn packet_out(&mut self) -> Option<PacketC> {
        self.packet_out.pop_front()
    }

    pub fn prime_client(&self, id: ID) -> Vec<PacketC> {
        let mut out = Vec::new();
        for (&id, player) in &self.players {
            out.push(PacketC::AddPlayer {
                id,
                name: player.name.clone(),
                hand: player.hand.map(|i| (i, self.items[&i])),
            })
        }
        for (&pos, tdata) in &self.tiles {
            out.push(PacketC::UpdateMap {
                pos,
                tile: tdata.kind,
            });
            for &id in &tdata.items {
                out.push(PacketC::ProduceItem {
                    id,
                    pos,
                    kind: self.items[&id],
                })
            }
        }
        out.push(PacketC::Joined { id });
        out
    }

    pub fn packet_in(&mut self, player: ID, packet: PacketS) -> Result<()> {
        match packet {
            PacketS::Join { name } => {
                self.players.insert(
                    player,
                    Player {
                        hand: None,
                        name: name.clone(),
                    },
                );
                self.packet_out.push_back(PacketC::AddPlayer {
                    id: player,
                    name,
                    hand: None,
                });
            }
            PacketS::Leave => {
                let p = self
                    .players
                    .remove(&player)
                    .ok_or(anyhow!("player does not exist"))?;
                if let Some(id) = p.hand {
                    self.items.remove(&id).expect("hand item lost");
                }
                self.packet_out
                    .push_back(PacketC::RemovePlayer { id: player })
            }
            PacketS::Position { pos, rot } => {
                self.packet_out
                    .push_back(PacketC::Position { player, pos, rot });
            }
            PacketS::Interact { pos } => {
                let tile = self
                    .tiles
                    .get_mut(&pos)
                    .ok_or(anyhow!("interacting with empty tile"))?;
                let player_data = self
                    .players
                    .get_mut(&player)
                    .ok_or(anyhow!("player does not exist"))?;

                if let Some(item) = player_data.hand.take() {
                    tile.items.push(item);
                    self.packet_out.push_back(PacketC::PutItem { item, pos })
                } else {
                    if let Some(item) = tile.items.pop() {
                        player_data.hand = Some(item);
                        self.packet_out
                            .push_back(PacketC::TakeItem { item, player })
                    }
                }
            }
        }
        Ok(())
    }
}

impl From<Tile> for TileData {
    fn from(kind: Tile) -> Self {
        Self {
            kind,
            active: false,
            items: vec![],
        }
    }
}