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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
|
/*
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::{
data::DataIndex,
entity::bot::BotDriver,
server::{Server, ServerState},
ConnectionID,
};
use anyhow::{anyhow, bail, Result};
use clap::{Parser, ValueEnum};
use hurrycurry_bot::algos::ALGO_CONSTRUCTORS;
use hurrycurry_client_lib::Game;
use hurrycurry_protocol::{Message, PacketC, PacketS, PlayerID};
use log::{debug, trace};
use std::{
collections::{HashMap, HashSet, VecDeque},
time::Duration,
};
use tokio::sync::broadcast::Sender;
pub struct State {
index: DataIndex,
packet_out: VecDeque<PacketC>,
tx: Sender<PacketC>,
connections: HashMap<ConnectionID, HashSet<PlayerID>>,
pub server: ServerState,
pub game: Game,
}
#[derive(Parser)]
#[clap(multicall = true)]
enum Command {
/// Start a new game
Start {
/// Gamedata specification
#[arg(default_value = "junior")]
spec: String,
/// Duration in seconds
#[arg(default_value = "420")]
timer: u64,
},
/// Abort the current game
End,
/// Download recipe/map's source declaration
Download {
/// Resource kind
#[arg(value_enum)]
r#type: DownloadType,
/// Name
name: String,
},
/// List all recipes and maps
List,
/// Send an effect
Effect { name: String },
/// Send an item
Item { name: String },
/// Reload the resource index
ReloadIndex,
#[clap(alias = "summon-bot", alias = "spawn-bot")]
CreateBot { algo: String, name: Option<String> },
/// Reload the current map
#[clap(alias = "r")]
Reload,
}
#[derive(ValueEnum, Clone)]
enum DownloadType {
Map,
Recipes,
}
impl State {
pub async fn new(tx: Sender<PacketC>) -> Result<Self> {
let mut index = DataIndex::default();
index.reload()?;
let mut packet_out = VecDeque::new();
let mut game = Game::default();
let mut server = ServerState::default();
{
Server {
game: &mut game,
state: &mut server,
}
.load(index.generate("lobby").await?, None, &mut packet_out);
}
Ok(Self {
game,
server,
index,
tx,
packet_out,
connections: HashMap::new(),
})
}
pub async fn tick(&mut self, dt: f32) -> anyhow::Result<()> {
let mut server = Server {
game: &mut self.game,
state: &mut self.server,
};
if server.tick(dt, &mut self.packet_out) {
server.load(
self.index.generate("lobby").await?,
None,
&mut self.packet_out,
);
}
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(&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 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(()) => return Ok(vec![]),
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.")
}
}
_ => (),
}
let mut server = Server {
game: &mut self.game,
state: &mut self.server,
};
server.packet_in(packet, &mut replies, &mut self.packet_out)?;
for p in &replies {
match p {
PacketC::Joined { id } => {
self.connections.entry(conn).or_default().insert(*id);
}
_ => (),
}
}
if server.count_chefs() <= 0 && !server.game.lobby {
self.tx
.send(PacketC::ServerMessage {
text: "Game was aborted automatically due to a lack of players".to_string(),
})
.ok();
server.load(
self.index.generate("lobby").await?,
None,
&mut self.packet_out,
);
}
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(conn, PacketS::Leave { player }).await;
}
}
self.connections.remove(&conn);
}
async fn handle_command_parse(&mut self, player: PlayerID, command: &str) -> Result<()> {
for line in command.split("\n") {
self.handle_command(
player,
Command::try_parse_from(
shlex::split(line)
.ok_or(anyhow!("quoting invalid"))?
.into_iter(),
)?,
)
.await?;
}
Ok(())
}
async fn handle_command(&mut self, player: PlayerID, command: Command) -> Result<()> {
let mut server = Server {
game: &mut self.game,
state: &mut self.server,
};
match command {
Command::Start { spec, timer } => {
let data = self.index.generate(&spec).await?;
server.load(data, Some(Duration::from_secs(timer)), &mut self.packet_out);
}
Command::End => {
self.tx
.send(PacketC::ServerMessage {
text: format!(
"Game was aborted by {}.",
server
.game
.players
.get(&player)
.ok_or(anyhow!("player missing"))?
.name
),
})
.ok();
server.load(
self.index.generate("lobby").await?,
None,
&mut self.packet_out,
);
}
Command::Reload => {
if server.count_chefs() > 1 {
bail!("must be at most one player to reload");
}
server.load(
self.index.generate(&server.game.data.current_map).await?,
None,
&mut self.packet_out,
);
}
Command::ReloadIndex => {
self.index.reload()?;
}
Command::Download { r#type, name } => {
let source = match r#type {
DownloadType::Map => self.index.read_map(&name).await,
DownloadType::Recipes => self.index.read_recipes(&name).await,
}?;
bail!("{source}");
}
Command::List => {
bail!(
"Maps: {:?}\nRecipes: {:?}",
self.index.maps.keys().collect::<Vec<_>>(),
self.index.recipes
)
}
Command::Effect { name } => {
self.tx
.send(PacketC::Communicate {
player,
message: Some(Message::Effect(name)),
timeout: None,
})
.ok();
}
Command::Item { name } => {
let item = server
.game
.data
.get_item_by_name(&name)
.ok_or(anyhow!("unknown item"))?;
self.tx
.send(PacketC::Communicate {
player,
message: Some(Message::Item(item)),
timeout: None,
})
.ok();
}
Command::CreateBot { algo, name } => {
let (aname, cons) = ALGO_CONSTRUCTORS
.iter()
.find(|(name, _)| *name == algo.as_str())
.ok_or(anyhow!("algo name unknown"))?;
let algo = cons();
self.server.entities.push(Box::new(BotDriver::new(
format!("{}-bot", name.unwrap_or((*aname).to_owned())),
51,
algo,
)));
}
}
Ok(())
}
}
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,
}
}
|