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
|
use crate::protocol::*;
use crate::server::network::*;
use crate::shared::champion::*;
use crate::shared::cooldown::*;
use crate::shared::health::*;
use crate::shared::imperative::*;
use crate::shared::projectile::*;
use crate::shared::*;
use bevy::prelude::*;
use bevy::utils::Duration;
use bevy::utils::HashMap;
use lightyear::prelude::*;
use lightyear::server::events::MessageEvent;
use rand::Rng;
mod network;
#[derive(Resource, Default)]
struct EntityMap(HashMap<ClientId, Entity>);
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 = 1.;
#[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(Update, timers_ticket)
.add_systems(Update, health_regen.after(timers_ticket))
.add_systems(
Update,
(
imperative_attack.after(cooldown_decrement),
imperative_walk_to,
)
.after(player_input),
)
.add_systems(
Update,
(
projectile_move.after(imperative_walk_to),
projectile_despawn,
)
.chain(),
)
.add_systems(Update, cooldown_decrement)
.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 {
return;
};
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>,
) {
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;
}
}
_ => {}
}
}
}
}
}
const MOVEMENT_SPEED: f32 = 80.;
fn imperative_walk_to(
mut players: Query<(Entity, &mut Imperative)>,
mut positions: Query<&mut PlayerPosition>,
time: Res<Time>,
) {
for (entity, mut imperative) 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,
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 imperative_attack(
entity_map: Res<EntityMap>,
mut commands: Commands,
mut cooldowns: Query<&mut Cooldown>,
mut players: Query<(&PlayerId, &mut Imperative)>,
mut positions: Query<&mut PlayerPosition>,
champions: Query<&Champion>,
time: Res<Time>,
) {
for (id, mut imperative) in players.iter_mut() {
match *imperative {
Imperative::Attack(target_player) => {
let Some(entity) = entity_map.0.get(&id.0) else {
*imperative = Imperative::Idle;
return;
};
let Ok(champion) = champions.get(*entity) else {
*imperative = Imperative::Idle;
return;
};
let Some(target_entity) = entity_map.0.get(&target_player.0) else {
*imperative = Imperative::Idle;
return;
};
let Ok([mut position, target_position]) =
positions.get_many_mut([*entity, *target_entity])
else {
*imperative = Imperative::Idle;
return;
};
let distance = target_position.0.distance(position.0);
if distance > Stats::from_champion(*champion).attack_range {
let (new_position, _) = move_to_target(
position.0,
target_position.0,
MOVEMENT_SPEED * time.delta().as_secs_f32(),
);
position.0 = new_position;
} else {
let Ok(mut cooldown) = cooldowns.get_mut(*entity) else {
*imperative = Imperative::Idle;
return;
};
if cooldown.a_cooldown.is_zero() {
cooldown.a_cooldown = Duration::from_secs_f32(1.5);
commands.spawn(ProjectileBundle {
projectile: Projectile {
target_player,
source_player: *id,
damage: 4.,
},
position: ProjectilePosition(position.0),
replicate: Replicate::default(),
});
}
}
}
_ => {}
}
}
}
const PROJECTILE_SPEED: f32 = 150.;
fn projectile_move(
entity_map: Res<EntityMap>,
mut projectile_positions: Query<&mut ProjectilePosition>,
player_positions: Query<&PlayerPosition>,
projectiles: Query<(Entity, &mut Projectile)>,
time: Res<Time>,
) {
for (entity, projectile) in projectiles.iter() {
if let Some(target_entity) = entity_map.0.get(&projectile.target_player.0) {
if let Ok(mut position) = projectile_positions.get_mut(entity) {
if let Ok(target_position) = player_positions.get(*target_entity) {
let (new_position, _) = move_to_target(
position.0,
target_position.0,
PROJECTILE_SPEED * time.delta().as_secs_f32(),
);
position.0 = new_position;
}
}
}
}
}
fn projectile_despawn(
entity_map: Res<EntityMap>,
mut commands: Commands,
mut healths: Query<&mut Health>,
player_positions: Query<&PlayerPosition>,
projectile_positions: Query<&ProjectilePosition>,
projectiles: Query<(Entity, &mut Projectile)>,
) {
for (entity, projectile) in projectiles.iter() {
let Some(target_entity) = entity_map.0.get(&projectile.target_player.0) else {
commands.entity(entity).despawn();
return;
};
let Ok(position) = projectile_positions.get(entity) else {
commands.entity(entity).despawn();
return;
};
let Ok(target_position) = player_positions.get(*target_entity) else {
commands.entity(entity).despawn();
return;
};
if position.0.distance(target_position.0) <= f32::EPSILON {
if let Ok(mut health) = healths.get_mut(*target_entity) {
health.0 = (health.0 - projectile.damage).max(0.);
}
commands.entity(entity).despawn();
}
}
}
fn cooldown_decrement(mut cooldowns: Query<&mut Cooldown>, time: Res<Time>) {
for mut cooldown in cooldowns.iter_mut() {
cooldown.a_cooldown = cooldown.a_cooldown.saturating_sub(time.delta());
cooldown.q_cooldown = cooldown.q_cooldown.saturating_sub(time.delta());
cooldown.w_cooldown = cooldown.w_cooldown.saturating_sub(time.delta());
cooldown.e_cooldown = cooldown.e_cooldown.saturating_sub(time.delta());
cooldown.d_cooldown = cooldown.d_cooldown.saturating_sub(time.delta());
cooldown.f_cooldown = cooldown.f_cooldown.saturating_sub(time.delta());
}
}
fn timers_ticket(mut health_regen_timer: ResMut<HealthRegenTimer>, time: Res<Time>) {
health_regen_timer.0.tick(time.delta());
}
fn health_regen(health_regen_timer: Res<HealthRegenTimer>, mut healths: Query<&mut Health>) {
if health_regen_timer.0.just_finished() {
for mut health in healths.iter_mut() {
health.0 = (health.0 + 1.).min(MAX_HEALTH);
}
}
}
|