-
Notifications
You must be signed in to change notification settings - Fork 16
/
client.rs
487 lines (452 loc) · 15.7 KB
/
client.rs
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
use std::collections::HashMap;
use bevy::{
asset::Assets,
audio::{AudioPlayer, Volume},
input::ButtonInput,
prelude::{
default, AssetServer, BuildChildren, Bundle, Button, Camera2d, Changed, ChildBuild, Circle,
Color, Commands, Component, DespawnRecursiveExt, Entity, EventReader, EventWriter, KeyCode,
Local, Mesh, Mesh2d, PlaybackSettings, Query, Res, ResMut, Resource, Text, Transform, Vec2,
Vec3, With, Without,
},
sprite::{ColorMaterial, MeshMaterial2d, Sprite},
state::state::NextState,
text::{TextColor, TextFont, TextSpan},
ui::{
AlignItems, BackgroundColor, Interaction, JustifyContent, Node, PositionType, UiRect, Val,
},
};
use bevy_quinnet::{
client::{
certificate::CertificateVerificationMode, connection::ClientEndpointConfiguration,
QuinnetClient,
},
shared::ClientId,
};
use crate::{
protocol::{ClientChannel, ClientMessage, PaddleInput, ServerMessage},
BrickId, CollisionEvent, CollisionSound, GameState, Score, Velocity, WallLocation, BALL_SIZE,
BALL_SPEED, BRICK_SIZE, GAP_BETWEEN_BRICKS, LOCAL_BIND_IP, PADDLE_SIZE, SERVER_HOST,
SERVER_PORT, TIME_STEP,
};
const SCOREBOARD_FONT_SIZE: f32 = 40.0;
const SCOREBOARD_TEXT_PADDING: Val = Val::Px(5.0);
pub(crate) const BACKGROUND_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
const PADDLE_COLOR: Color = Color::srgb(0.3, 0.3, 0.7);
const OPPONENT_PADDLE_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
const BALL_COLOR: Color = Color::srgb(0.35, 0.35, 0.6);
const OPPONENT_BALL_COLOR: Color = Color::srgb(0.9, 0.6, 0.6);
const BRICK_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
const WALL_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
const TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
const SCORE_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
const NORMAL_BUTTON_COLOR: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON_COLOR: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON_COLOR: Color = Color::srgb(0.35, 0.75, 0.35);
const BUTTON_TEXT_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
const BOLD_FONT: &str = "fonts/FiraSans-Bold.ttf";
const NORMAL_FONT: &str = "fonts/FiraMono-Medium.ttf";
const COLLISION_SOUND_EFFECT: &str = "sounds/breakout_collision.ogg";
#[derive(Resource, Debug, Clone, Default)]
pub(crate) struct ClientData {
self_id: ClientId,
}
#[derive(Resource, Default)]
pub(crate) struct NetworkMapping {
// Network entity id to local entity id
map: HashMap<Entity, Entity>,
}
#[derive(Resource, Default)]
pub struct BricksMapping {
map: HashMap<BrickId, Entity>,
}
// This resource tracks the game's score
#[derive(Resource)]
pub(crate) struct Scoreboard {
pub(crate) score: i32,
}
#[derive(Component)]
pub(crate) struct Paddle;
#[derive(Component)]
pub(crate) struct Ball;
#[derive(Component)]
pub(crate) struct Brick;
/// The buttons in the main menu.
#[derive(Clone, Copy, Component)]
pub(crate) enum MenuItem {
Host,
Join,
}
#[derive(Bundle)]
struct WallBundle {
sprite: Sprite,
transform: Transform,
}
pub(crate) fn start_connection(mut client: ResMut<QuinnetClient>) {
client
.open_connection(
ClientEndpointConfiguration::from_ips(SERVER_HOST, SERVER_PORT, LOCAL_BIND_IP, 0),
CertificateVerificationMode::SkipVerification,
ClientChannel::channels_configuration(),
)
.unwrap();
}
fn spawn_paddle(commands: &mut Commands, position: &Vec3, owned: bool) -> Entity {
commands
.spawn((
Sprite::from_color(
if owned {
PADDLE_COLOR
} else {
OPPONENT_PADDLE_COLOR
},
Vec2::ONE,
),
Transform {
translation: *position,
scale: PADDLE_SIZE,
..default()
},
Paddle,
))
.id()
}
pub(crate) fn spawn_bricks(
commands: &mut Commands,
bricks: &mut ResMut<BricksMapping>,
offset: Vec2,
rows: usize,
columns: usize,
) {
let mut brick_id = 0;
for row in 0..rows {
for column in 0..columns {
let brick_position = Vec2::new(
offset.x + column as f32 * (BRICK_SIZE.x + GAP_BETWEEN_BRICKS),
offset.y + row as f32 * (BRICK_SIZE.y + GAP_BETWEEN_BRICKS),
);
let brick = commands
.spawn((
Sprite {
color: BRICK_COLOR,
..default()
},
Transform {
translation: brick_position.extend(0.0),
scale: Vec3::new(BRICK_SIZE.x, BRICK_SIZE.y, 1.0),
..default()
},
Brick,
))
.id();
bricks.map.insert(brick_id, brick);
brick_id += 1;
}
}
}
pub(crate) fn handle_server_messages(
mut commands: Commands,
mut client: ResMut<QuinnetClient>,
mut client_data: ResMut<ClientData>,
mut entity_mapping: ResMut<NetworkMapping>,
mut next_state: ResMut<NextState<GameState>>,
mut paddles: Query<&mut Transform, With<Paddle>>,
mut balls: Query<
(
&mut Transform,
&mut Velocity,
&mut MeshMaterial2d<ColorMaterial>,
),
(With<Ball>, Without<Paddle>),
>,
mut bricks: ResMut<BricksMapping>,
mut scoreboard: ResMut<Scoreboard>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
mut collision_events: EventWriter<CollisionEvent>,
) {
while let Some((_, message)) = client
.connection_mut()
.try_receive_message::<ServerMessage>()
{
match message {
ServerMessage::InitClient { client_id } => {
client_data.self_id = client_id;
}
ServerMessage::SpawnPaddle {
owner_client_id,
entity,
position,
} => {
let paddle = spawn_paddle(
&mut commands,
&position,
owner_client_id == client_data.self_id,
);
entity_mapping.map.insert(entity, paddle);
}
ServerMessage::SpawnBall {
owner_client_id,
entity,
position,
direction,
} => {
let ball = commands
.spawn((
Mesh2d(meshes.add(Circle::default())),
MeshMaterial2d(materials.add(player_color_from_bool(
owner_client_id == client_data.self_id,
))),
Transform::from_translation(position).with_scale(BALL_SIZE),
Ball,
Velocity(direction.normalize() * BALL_SPEED),
))
.id();
entity_mapping.map.insert(entity, ball);
}
ServerMessage::SpawnBricks {
offset,
rows,
columns,
} => spawn_bricks(&mut commands, &mut bricks, offset, rows, columns),
ServerMessage::StartGame {} => next_state.set(GameState::Running),
ServerMessage::BrickDestroyed {
by_client_id,
brick_id,
} => {
if by_client_id == client_data.self_id {
scoreboard.score += 1;
} else {
scoreboard.score -= 1;
}
if let Some(brick_entity) = bricks.map.get(&brick_id) {
commands.entity(*brick_entity).despawn();
}
}
ServerMessage::BallCollided {
owner_client_id,
entity,
position,
velocity,
} => {
if let Some(local_ball) = entity_mapping.map.get(&entity) {
if let Ok((mut ball_transform, mut ball_velocity, mut ball_mat)) =
balls.get_mut(*local_ball)
{
ball_transform.translation = position;
ball_velocity.0 = velocity;
ball_mat.0 = materials.add(player_color_from_bool(
owner_client_id == client_data.self_id,
));
}
}
// Sends a collision event so that other systems can react to the collision
collision_events.send_default();
}
ServerMessage::PaddleMoved { entity, position } => {
if let Some(local_paddle) = entity_mapping.map.get(&entity) {
if let Ok(mut paddle_transform) = paddles.get_mut(*local_paddle) {
paddle_transform.translation = position;
}
}
}
}
}
}
#[derive(Default)]
pub(crate) struct PaddleState {
current_input: PaddleInput,
}
pub(crate) fn move_paddle(
mut client: ResMut<QuinnetClient>,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut local: Local<PaddleState>,
) {
let mut paddle_input = PaddleInput::None;
if keyboard_input.pressed(KeyCode::ArrowLeft) {
paddle_input = PaddleInput::Left;
}
if keyboard_input.pressed(KeyCode::ArrowRight) {
paddle_input = PaddleInput::Right;
}
if local.current_input != paddle_input {
client.connection_mut().try_send_message_on(
ClientChannel::PaddleCommands,
ClientMessage::PaddleInput {
input: paddle_input.clone(),
},
);
local.current_input = paddle_input;
}
}
pub(crate) fn update_scoreboard(
scoreboard: Res<Scoreboard>,
mut query: Query<(&mut TextSpan, &mut TextColor), With<Score>>,
) {
let (mut text, mut text_color) = query.single_mut();
text.0 = scoreboard.score.to_string();
text_color.0 = player_color_from_bool(scoreboard.score >= 0);
}
pub(crate) fn play_collision_sound(
mut commands: Commands,
mut collision_events: EventReader<CollisionEvent>,
sound: Res<CollisionSound>,
) {
// Play a sound once per frame if a collision occurred.
if !collision_events.is_empty() {
// This prevents events staying active on the next frame.
collision_events.clear();
commands.spawn((
AudioPlayer(sound.clone()),
// auto-despawn the entity when playback finishes
PlaybackSettings::DESPAWN.with_volume(Volume::new(0.2)),
));
}
}
pub(crate) fn setup_main_menu(mut commands: Commands, asset_server: Res<AssetServer>) {
// Camera
commands.spawn(Camera2d::default());
let button_style = Node {
width: Val::Px(150.0),
height: Val::Px(65.0),
// center button
margin: UiRect::all(Val::Auto),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
..default()
};
let text_font = TextFont {
font: asset_server.load(BOLD_FONT),
font_size: 40.,
..Default::default()
};
let text_color = TextColor(BUTTON_TEXT_COLOR);
commands
.spawn((
Node {
width: Val::Vw(100.0),
height: Val::Vh(100.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::NONE.into()),
))
.with_children(|parent| {
parent
.spawn((
button_style.clone(),
Button,
BackgroundColor(NORMAL_BUTTON_COLOR.into()),
MenuItem::Host,
))
.with_children(|parent| {
parent.spawn((Text("Host".into()), text_font.clone(), text_color.clone()));
});
parent
.spawn((
button_style.clone(),
Button,
BackgroundColor(NORMAL_BUTTON_COLOR.into()),
MenuItem::Join,
))
.with_children(|parent| {
parent.spawn((Text("Join".into()), text_font.clone(), text_color.clone()));
});
});
}
pub(crate) fn handle_menu_buttons(
mut interaction_query: Query<
(&Interaction, &mut BackgroundColor, &MenuItem),
(Changed<Interaction>, With<Button>),
>,
mut next_state: ResMut<NextState<GameState>>,
) {
for (interaction, mut color, item) in &mut interaction_query {
match *interaction {
Interaction::Pressed => {
*color = PRESSED_BUTTON_COLOR.into();
match item {
MenuItem::Host => next_state.set(GameState::HostingLobby),
MenuItem::Join => next_state.set(GameState::JoiningLobby),
}
}
Interaction::Hovered => *color = HOVERED_BUTTON_COLOR.into(),
Interaction::None => *color = NORMAL_BUTTON_COLOR.into(),
}
}
}
pub(crate) fn teardown_main_menu(mut commands: Commands, query: Query<Entity, With<Button>>) {
for entity in query.iter() {
commands.entity(entity).despawn_recursive();
}
}
pub(crate) fn setup_breakout(mut commands: Commands, asset_server: Res<AssetServer>) {
// Sound
let ball_collision_sound = asset_server.load(COLLISION_SOUND_EFFECT);
commands.insert_resource(CollisionSound(ball_collision_sound));
// Scoreboard
commands
.spawn((
Node {
position_type: PositionType::Absolute,
top: SCOREBOARD_TEXT_PADDING,
left: SCOREBOARD_TEXT_PADDING,
..default()
},
Text("Score: ".into()),
TextFont {
font: asset_server.load(BOLD_FONT),
font_size: SCOREBOARD_FONT_SIZE,
..default()
},
TextColor(TEXT_COLOR),
))
.with_child((
TextSpan("".into()),
TextFont {
font: asset_server.load(NORMAL_FONT),
font_size: SCOREBOARD_FONT_SIZE,
..default()
},
TextColor(SCORE_COLOR),
Score,
));
// Walls
commands.spawn(WallBundle::new(WallLocation::Left));
commands.spawn(WallBundle::new(WallLocation::Right));
commands.spawn(WallBundle::new(WallLocation::Bottom));
commands.spawn(WallBundle::new(WallLocation::Top));
}
pub(crate) fn apply_velocity(mut query: Query<(&mut Transform, &Velocity), With<Ball>>) {
for (mut transform, velocity) in &mut query {
transform.translation.x += velocity.x * TIME_STEP;
transform.translation.y += velocity.y * TIME_STEP;
}
}
fn player_color_from_bool(owned: bool) -> Color {
if owned {
BALL_COLOR
} else {
OPPONENT_BALL_COLOR
}
}
impl WallBundle {
fn new(location: WallLocation) -> WallBundle {
WallBundle {
sprite: Sprite::from_color(WALL_COLOR, Vec2::ONE),
transform: Transform {
// We need to convert our Vec2 into a Vec3, by giving it a z-coordinate
// This is used to determine the order of our sprites
translation: location.position().extend(0.0),
// The z-scale of 2D objects must always be 1.0,
// or their ordering will be affected in surprising ways.
// See https://github.com/bevyengine/bevy/issues/4149
scale: location.size().extend(1.0),
..default()
},
}
}
}