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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
|
use crate::protocol::*;
use crate::server::entity_map::*;
use crate::server::network::*;
use crate::shared::ability::*;
use crate::shared::activation::*;
use crate::shared::buffs::*;
use crate::shared::champion::*;
use crate::shared::cooldown::*;
use crate::shared::health::*;
use crate::shared::health_event::*;
use crate::shared::imperative::*;
use crate::shared::player::*;
use crate::shared::projectile::*;
use crate::shared::stats::*;
use crate::shared::*;
use bevy::prelude::*;
use bevy::utils::*;
use lightyear::prelude::*;
use lightyear::server::events::MessageEvent;
use rand::Rng;
pub mod entity_map;
mod network;
pub fn main(transport: TransportConfig) {
App::new()
.add_plugins(MinimalPlugins)
.add_plugins(ServerPlugin { transport })
.run();
}
struct ServerPlugin {
pub transport: TransportConfig,
}
const HEALTH_REGEN_RATE: f32 = 5.;
#[derive(Resource)]
struct HealthRegenTimer(pub Timer);
impl Default for HealthRegenTimer {
fn default() -> Self {
HealthRegenTimer(Timer::from_seconds(HEALTH_REGEN_RATE, TimerMode::Repeating))
}
}
impl Plugin for ServerPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(EntityMap::default())
.insert_resource(HealthRegenTimer::default())
.add_plugins(NetworkPlugin {
transport: self.transport.clone(),
})
.add_systems(Startup, setup)
.add_systems(Update, (connects, disconnects))
.add_systems(Update, receive_message)
.add_systems(FixedUpdate, timers_tick)
.add_systems(FixedUpdate, effective_stats)
.add_systems(FixedUpdate, health_regen.after(timers_tick))
.add_systems(
FixedUpdate,
(
(imperative_attack_approach, imperative_attack_attack)
.chain()
.after(activation),
activation.after(cooldown_decrement),
imperative_walk_to,
)
.after(player_input),
)
.add_systems(
FixedUpdate,
(
projectile_move.after(imperative_walk_to),
projectile_despawn,
)
.chain(),
)
.add_systems(FixedUpdate, cooldown_decrement)
.add_systems(FixedUpdate, (buffs_despawn, buffs_tick).chain())
.add_systems(FixedUpdate, player_input);
}
}
fn setup(mut commands: Commands, mut entity_map: ResMut<EntityMap>) {
let client_id = 1;
let entity = commands.spawn(PlayerBundle::new(1, Vec2::ZERO, Color::GRAY));
entity_map.0.insert(client_id, entity.id());
}
fn connects(
mut commands: Commands,
mut connects: EventReader<server::ConnectEvent>,
mut entity_map: ResMut<EntityMap>,
) {
let mut rng = rand::thread_rng();
for connection in connects.read() {
let client_id = connection.context();
let position = Vec2::new(
50. * rng.gen_range(-2..=2) as f32,
50. * rng.gen_range(-2..=2) as f32,
);
let color = Color::hsl(360. * rng.gen_range(0..=15) as f32 / 16., 0.95, 0.7);
let entity = commands.spawn(PlayerBundle::new(*client_id, position, color));
entity_map.0.insert(*client_id, entity.id());
}
}
fn receive_message(
entity_map: Res<EntityMap>,
mut commands: Commands,
mut reader: EventReader<MessageEvent<SelectChampion>>,
) {
for event in reader.read() {
let client_id = event.context();
let SelectChampion(champion) = event.message();
let Some(entity) = entity_map.0.get(client_id) else {
continue;
};
commands.entity(*entity).insert(*champion);
}
}
fn disconnects(
mut commands: Commands,
mut disconnects: EventReader<server::DisconnectEvent>,
mut entity_map: ResMut<EntityMap>,
) {
for connection in disconnects.read() {
let client_id = connection.context();
if let Some(entity_id) = entity_map.0.remove(client_id) {
commands.entity(entity_id).despawn();
}
}
}
fn player_input(
entity_map: Res<EntityMap>,
mut input_reader: EventReader<server::InputEvent<Inputs>>,
mut imperatives: Query<&mut Imperative>,
mut activations: Query<&mut Activation>,
) {
for input in input_reader.read() {
let client_id = input.context();
if let Some(input) = input.input() {
if let Some(entity_id) = entity_map.0.get(client_id) {
match input {
Inputs::Imperative(new_imperative) => {
if let Ok(mut imperative) = imperatives.get_mut(*entity_id) {
*imperative = *new_imperative;
}
}
Inputs::Activation(new_activation) => {
if let Ok(mut activation) = activations.get_mut(*entity_id) {
*activation = *new_activation;
}
}
Inputs::None => {}
}
}
}
}
}
fn imperative_walk_to(
mut players: Query<(Entity, &mut Imperative, &EffectiveStats)>,
mut positions: Query<&mut PlayerPosition>,
time: Res<Time>,
) {
for (entity, mut imperative, effective_stats) in players.iter_mut() {
match *imperative {
Imperative::WalkTo(target_position) => {
if let Ok(mut position) = positions.get_mut(entity) {
let (new_position, target_reached) = move_to_target(
position.0,
target_position,
effective_stats.0.movement_speed * time.delta().as_secs_f32(),
);
position.0 = new_position;
if target_reached {
*imperative = Imperative::Idle;
}
} else {
*imperative = Imperative::Idle;
}
}
_ => {}
}
}
}
fn move_to_target(position: Vec2, target_position: Vec2, max_distance: f32) -> (Vec2, bool) {
let distance = (target_position - position).length();
let direction = (target_position - position).normalize_or_zero();
let new_position = position + f32::min(max_distance, distance) * direction;
if position.distance(new_position) <= f32::EPSILON {
(target_position, true)
} else {
(new_position, false)
}
}
fn move_along_direction(position: Vec2, direction: Vec2, distance: f32) -> Vec2 {
position + distance * direction
}
fn imperative_attack_approach(
entity_map: Res<EntityMap>,
mut players: Query<(&PlayerId, &mut Imperative, &EffectiveStats)>,
mut positions: Query<&mut PlayerPosition>,
time: Res<Time>,
) {
for (id, mut imperative, effective_stats) in players.iter_mut() {
match *imperative {
Imperative::AttackTarget(_, target_player) => {
let Some(entity) = entity_map.0.get(&id.0) else {
*imperative = Imperative::Idle;
continue;
};
let Some(target_entity) = entity_map.0.get(&target_player.0) else {
*imperative = Imperative::Idle;
continue;
};
let Ok([mut position, target_position]) =
positions.get_many_mut([*entity, *target_entity])
else {
*imperative = Imperative::Idle;
continue;
};
let distance = target_position.0.distance(position.0);
if distance > effective_stats.0.attack_range {
let (new_position, _) = move_to_target(
position.0,
target_position.0,
effective_stats.0.movement_speed * time.delta().as_secs_f32(),
);
position.0 = new_position;
}
}
_ => {}
}
}
}
fn imperative_attack_attack(
entity_map: Res<EntityMap>,
mut commands: Commands,
mut cooldowns: Query<&mut Cooldown>,
mut players: Query<(&PlayerId, &mut Imperative, &EffectiveStats)>,
mut positions: Query<&mut PlayerPosition>,
champions: Query<&Champion>,
) {
for (id, mut imperative, effective_stats) in players.iter_mut() {
let Some(entity) = entity_map.0.get(&id.0) else {
*imperative = Imperative::Idle;
continue;
};
let Ok(champion) = champions.get(*entity) else {
*imperative = Imperative::Idle;
continue;
};
match *imperative {
Imperative::AttackTarget(ability_slot, target_player) => {
let Ability::Targeted(ability) = champion.ability(ability_slot) else {
*imperative = Imperative::Idle;
continue;
};
let Some(target_entity) = entity_map.0.get(&target_player.0) else {
*imperative = Imperative::Idle;
continue;
};
let Ok([position, target_position]) =
positions.get_many_mut([*entity, *target_entity])
else {
*imperative = Imperative::Idle;
continue;
};
let distance = target_position.0.distance(position.0);
if distance <= effective_stats.0.attack_range {
let Ok(mut cooldown) = cooldowns.get_mut(*entity) else {
*imperative = Imperative::Idle;
continue;
};
let base_cooldown = champion.base_cooldown();
if cooldown.0[ability_slot].is_zero() {
cooldown.0[ability_slot] = if ability_slot == AbilitySlot::A {
Duration::from_secs_f32(effective_stats.0.attack_speed)
} else {
base_cooldown.0[ability_slot]
};
commands.spawn(ProjectileBundle::new(ability.to_projectile(
*id,
position.0,
target_player,
)));
if ability_slot != AbilitySlot::A {
*imperative = Imperative::Idle;
}
}
}
}
Imperative::AttackDirection(ability_slot, direction) => {
let Ability::Directional(ability) = champion.ability(ability_slot) else {
*imperative = Imperative::Idle;
continue;
};
let Ok(mut cooldown) = cooldowns.get_mut(*entity) else {
*imperative = Imperative::Idle;
continue;
};
let base_cooldown = champion.base_cooldown();
if cooldown.0[ability_slot].is_zero() {
cooldown.0[ability_slot] = base_cooldown.0[ability_slot];
ability.activate()(&mut commands, *id, direction);
}
*imperative = Imperative::Idle;
}
_ => {}
}
}
}
fn activation(
champions: Query<&Champion>,
mut commands: Commands,
entity_map: Res<EntityMap>,
mut cooldowns: Query<&mut Cooldown>,
mut players: Query<(&PlayerId, &mut Activation)>,
) {
for (id, mut activation) in players.iter_mut() {
let Some(entity) = entity_map.0.get(&id.0) else {
*activation = Activation::None;
continue;
};
let Ok(champion) = champions.get(*entity) else {
*activation = Activation::None;
continue;
};
let Activation::Activate(ability_slot) = *activation else {
*activation = Activation::None;
continue;
};
let Ability::Activated(ability) = champion.ability(ability_slot) else {
*activation = Activation::None;
continue;
};
let Ok(mut cooldown) = cooldowns.get_mut(*entity) else {
*activation = Activation::None;
continue;
};
let base_cooldown = champion.base_cooldown();
if cooldown.0[ability_slot].is_zero() {
cooldown.0[ability_slot] = base_cooldown.0[ability_slot];
ability.activate()(&mut commands, *id);
*activation = Activation::None;
}
}
}
const PROJECTILE_SPEED: f32 = 150.;
fn projectile_move(
entity_map: Res<EntityMap>,
player_positions: Query<&PlayerPosition>,
mut projectiles: Query<&mut Projectile>,
time: Res<Time>,
) {
for mut projectile in projectiles.iter_mut() {
let new_type = match projectile.type_.clone() {
ProjectileType::Free(mut free_projectile) => {
let new_position = move_along_direction(
free_projectile.position,
free_projectile.direction,
PROJECTILE_SPEED * time.delta().as_secs_f32(),
);
free_projectile.position = new_position;
ProjectileType::Free(free_projectile)
}
ProjectileType::Instant(instant_projectile) => {
ProjectileType::Instant(instant_projectile)
}
ProjectileType::Targeted(mut targeted_projectile) => {
if let Some(target_entity) = entity_map.0.get(&targeted_projectile.target_player.0)
{
if let Ok(target_position) = player_positions.get(*target_entity) {
let (new_position, _) = move_to_target(
targeted_projectile.position.clone(),
target_position.0,
PROJECTILE_SPEED * time.delta().as_secs_f32(),
);
targeted_projectile.position = new_position;
}
}
ProjectileType::Targeted(targeted_projectile)
}
};
projectile.type_ = new_type;
}
}
fn projectile_despawn(
entity_map: Res<EntityMap>,
mut commands: Commands,
mut connection_manager: ResMut<ServerConnectionManager>,
mut healths: Query<&mut Health>,
player_positions: Query<&PlayerPosition>,
projectiles: Query<(Entity, &mut Projectile)>,
projectile_targets: Query<(&PlayerId, &PlayerPosition)>,
) {
for (entity, projectile) in projectiles.iter() {
let (despawn, maybe_target_player): (bool, Option<PlayerId>) = (|| match &projectile.type_ {
ProjectileType::Free(free_projectile) => {
let mut maybe_target_player = None;
let mut maybe_target_distance = None;
for (player, position) in projectile_targets.iter() {
if *player == projectile.source_player {
continue;
}
let distance = free_projectile.position.distance(position.0);
if distance > PLAYER_RADIUS {
continue;
}
match maybe_target_distance {
Some(old_distance) => {
if distance < old_distance {
maybe_target_player = Some(player);
maybe_target_distance = Some(distance);
}
}
None => {
maybe_target_player = Some(player);
maybe_target_distance = Some(distance);
}
}
}
if let Some(target_player) = maybe_target_player {
(true, Some(*target_player))
} else {
(
free_projectile
.position
.distance(free_projectile.starting_position)
>= free_projectile.max_distance,
None,
)
}
}
ProjectileType::Instant(instant_projectile) => {
(true, Some(instant_projectile.target_player))
}
ProjectileType::Targeted(targeted_projectile) => {
let Some(target_entity) = entity_map.0.get(&targeted_projectile.target_player.0)
else {
return (true, None);
};
let Ok(target_position) = player_positions.get(*target_entity) else {
return (true, None);
};
(
targeted_projectile.position.distance(target_position.0) <= f32::EPSILON,
Some(targeted_projectile.target_player),
)
}
})();
if despawn {
if let Some(target_player) = maybe_target_player {
if let Some(target_entity) = entity_map.0.get(&target_player.0) {
if let Ok(mut health) = healths.get_mut(*target_entity) {
health.0 = (health.0 - projectile.damage).max(0.);
let _ = connection_manager
.send_message_to_target::<Channel1, HealthChanged>(
HealthChanged(HealthEvent {
target_player,
health_gained: -projectile.damage,
}),
NetworkTarget::All,
);
}
}
}
commands.entity(entity).despawn();
}
}
}
fn cooldown_decrement(mut cooldowns: Query<&mut Cooldown>, time: Res<Time>) {
let dt = time.delta();
for mut cooldown in cooldowns.iter_mut() {
for ability_slot in AbilitySlot::all() {
cooldown.0[ability_slot] = cooldown.0[ability_slot].saturating_sub(dt);
}
}
}
fn timers_tick(mut health_regen_timer: ResMut<HealthRegenTimer>, time: Res<Time>) {
health_regen_timer.0.tick(time.delta());
}
const HEALTH_REGEN: f32 = 5.;
fn health_regen(
health_regen_timer: Res<HealthRegenTimer>,
mut connection_manager: ResMut<ServerConnectionManager>,
mut healths: Query<(&PlayerId, &mut Health, &EffectiveStats)>,
) {
if health_regen_timer.0.just_finished() {
for (target_player, mut health, effective_stats) in healths.iter_mut() {
health.0 = (health.0 + HEALTH_REGEN).min(effective_stats.0.max_health);
let _ = connection_manager.send_message_to_target::<Channel1, HealthChanged>(
HealthChanged(HealthEvent {
target_player: *target_player,
health_gained: HEALTH_REGEN,
}),
NetworkTarget::All,
);
}
}
}
fn effective_stats(
mut effective_statses: Query<(&Champion, &mut EffectiveStats, &Buffs, &mut Health)>,
) {
for (champion, mut effective_stats, buffs, mut health) in effective_statses.iter_mut() {
let mut stats = champion.base_stats().0;
if buffs.slow.is_some() {
stats.movement_speed *= 0.85;
}
if buffs.speed.is_some() {
stats.movement_speed *= 1.25;
}
if buffs.haste.is_some() {
stats.attack_speed *= 0.5;
}
effective_stats.0 = stats;
health.0 = health.0.min(effective_stats.0.max_health);
}
}
fn buffs_tick(mut buffses: Query<&mut Buffs>, time: Res<Time>) {
let dt = time.delta();
for mut buffs in buffses.iter_mut() {
if let Some(ref mut timer) = &mut buffs.haste {
timer.tick(dt);
}
if let Some(ref mut timer) = &mut buffs.slow {
timer.tick(dt);
}
if let Some(ref mut timer) = &mut buffs.speed {
timer.tick(dt);
}
}
}
fn buffs_despawn(mut buffses: Query<&mut Buffs>) {
for mut buffs in buffses.iter_mut() {
if let Some(timer) = &buffs.haste {
if timer.finished() {
buffs.haste = None;
}
}
if let Some(timer) = &buffs.slow {
if timer.finished() {
buffs.slow = None;
}
}
if let Some(timer) = &buffs.speed {
if timer.finished() {
buffs.speed = None;
}
}
}
}
|