forked from chris-hinson/waste
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiplayer_menu.rs
608 lines (567 loc) · 23.3 KB
/
multiplayer_menu.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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
#![allow(unused)]
use crate::backgrounds::{Tile, WIN_H, WIN_W};
use crate::camera::MenuCamera;
use crate::game_client::{
self, get_addr, get_randomized_port, ClientMarker, GameClient, HostMarker, PlayerType,
SocketInfo,
};
use crate::networking::{MultiplayerMode, MultiplayerModeSelected};
use crate::player::Player;
use crate::GameState;
use bevy::{prelude::*, ui::*};
use iyes_loopless::prelude::*;
use std::fmt::format;
use std::net::{Ipv4Addr, UdpSocket};
use std::str::from_utf8;
use std::sync::mpsc::{self, channel, Receiver, Sender};
use std::{io, thread};
const MULT_MENU_BACKGROUND: &str = "backgrounds/multiplayer_screen.png";
const TEXT_COLOR: Color = Color::rgb(0.9, 0.9, 0.9);
const NORMAL_BUTTON: Color = Color::rgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::rgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::rgb(0.75, 0.35, 0.35);
pub struct MultMenuPlugin;
#[derive(Component)]
pub(crate) struct MultMenuBackground;
#[derive(Component)]
pub(crate) struct MultOptionsText;
#[derive(Component)]
pub(crate) struct HostPVPButton;
#[derive(Component)]
pub(crate) struct ClientPVPButton;
#[derive(Component)]
pub(crate) struct HostPVEButton;
#[derive(Component)]
pub(crate) struct ClientPVEButton;
#[derive(Component)]
pub(crate) struct MultMenuUIElement;
// Builds plugin for multiplayer menu
impl Plugin for MultMenuPlugin {
fn build(&self, app: &mut App) {
app.add_enter_system(GameState::MultiplayerMenu, setup_mult)
// .add_system(udp_message_listener
// .run_if_resource_exists::<ClientMarker>())
.add_system_set(
ConditionSet::new()
// Only run handlers in MultiplayerMenu state
.run_in_state(GameState::MultiplayerMenu)
.with_system(mult_options)
.with_system(host_pvp_button_handler)
.with_system(client_pvp_button_handler)
.with_system(host_pve_button_handler)
.with_system(client_pve_button_handler)
.into(),
)
.add_exit_system(GameState::MultiplayerMenu, despawn_mult_menu);
}
}
/// System to listen for UDP messages. The socket is non-blocking intentionally,
/// so this works by running an "infinite" loop that will continually try to fill a
/// 2048 byte buffer until the OS tells it that recv would block, and then it will exit the loop
/// and return.
fn udp_message_listener(game_client: ResMut<GameClient>, mut commands: Commands) {
loop {
let mut buf = [0; 2048];
match game_client.socket.udp_socket.recv_from(&mut buf) {
Ok(result) => {
info!("Got into message checker... Read {} bytes", result.0);
let val = String::from_utf8((&buf[0..result.0]).to_vec()).unwrap();
info!("{}", val);
if val == "TRUE" {
commands.insert_resource(NextState(GameState::MultiplayerPvPBattle));
}
}
Err(err) => {
// If we run into this specific kind of error, it just means that the OS
// doesn't have anything ready for us to read yet, so we will stop trying.
// This whole system will run again on the next frame, so that's fine.
// This error is expected to be hit a LOT, any time a message is not ready for us.
if err.kind() != io::ErrorKind::WouldBlock {
// An ACTUAL error occurred
error!("{}", err);
// This should pulse an event and then return;
return;
}
// We're done listening
break;
}
}
}
}
fn despawn_mult_menu(
mut commands: Commands,
camera_query: Query<Entity, With<MenuCamera>>,
background_query: Query<Entity, With<MultMenuBackground>>,
mult_ui_element_query: Query<Entity, With<MultMenuUIElement>>,
) {
// Despawn cameras
for c in camera_query.iter() {
commands.entity(c).despawn();
}
// Despawn Main Menu Background
for bckg in background_query.iter() {
commands.entity(bckg).despawn();
}
if mult_ui_element_query.is_empty() {
error!("ui elements are here!");
}
// Despawn multiplayer UI elements
mult_ui_element_query.for_each(|mult_ui_element| {
commands.entity(mult_ui_element).despawn_recursive();
});
}
fn setup_mult(
mut commands: Commands,
asset_server: Res<AssetServer>,
cameras: Query<
Entity,
(
With<Camera2d>,
Without<MenuCamera>,
Without<Player>,
Without<Tile>,
),
>,
// game_channel: Res<GameChannel>,
game_client: Res<GameClient>,
) {
cameras.for_each(|camera| {
commands.entity(camera).despawn();
});
//creates camera for UI
let camera = Camera2dBundle::default();
commands.spawn_bundle(camera).insert(MenuCamera);
commands
.spawn_bundle(SpriteBundle {
texture: asset_server.load(MULT_MENU_BACKGROUND),
transform: Transform::from_xyz(0., 0., 0.),
..default()
})
.insert(MultMenuBackground);
// HOST PVP BUTTON
commands
.spawn_bundle(ButtonBundle {
style: Style {
size: Size::new(Val::Px(400.0), 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,
position_type: PositionType::Absolute,
position: UiRect {
bottom: Val::Px(450.),
left: Val::Px((WIN_W * 0.685) / 2.),
..default()
},
..default()
},
color: NORMAL_BUTTON.into(),
..default()
})
.with_children(|parent| {
parent.spawn_bundle(TextBundle::from_section(
"HOST PVP GAME",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: TEXT_COLOR,
},
));
})
.insert(HostPVPButton)
.insert(MultMenuUIElement);
// CLIENT BUTTON
commands
.spawn_bundle(ButtonBundle {
style: Style {
size: Size::new(Val::Px(400.0), 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,
position_type: PositionType::Absolute,
position: UiRect {
bottom: Val::Px(350.),
left: Val::Px((WIN_W * 0.685) / 2.),
..default()
},
..default()
},
color: NORMAL_BUTTON.into(),
..default()
})
.with_children(|parent| {
parent.spawn_bundle(TextBundle::from_section(
"JOIN PVP GAME",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: TEXT_COLOR,
},
));
})
.insert(ClientPVPButton)
.insert(MultMenuUIElement);
// HOST PVE BUTTON
commands
.spawn_bundle(ButtonBundle {
style: Style {
size: Size::new(Val::Px(400.0), 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,
position_type: PositionType::Absolute,
position: UiRect {
bottom: Val::Px(250.),
left: Val::Px((WIN_W * 0.685) / 2.),
..default()
},
..default()
},
color: NORMAL_BUTTON.into(),
..default()
})
.with_children(|parent| {
parent.spawn_bundle(TextBundle::from_section(
"HOST PVE GAME",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: TEXT_COLOR,
},
));
})
.insert(HostPVEButton)
.insert(MultMenuUIElement);
// CLIENT BUTTON
commands
.spawn_bundle(ButtonBundle {
style: Style {
size: Size::new(Val::Px(400.0), 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,
position_type: PositionType::Absolute,
position: UiRect {
bottom: Val::Px(150.),
left: Val::Px((WIN_W * 0.685) / 2.),
..default()
},
..default()
},
color: NORMAL_BUTTON.into(),
..default()
})
.with_children(|parent| {
parent.spawn_bundle(TextBundle::from_section(
"JOIN PVE GAME",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: TEXT_COLOR,
},
));
})
.insert(ClientPVEButton)
.insert(MultMenuUIElement);
}
pub(crate) fn mult_options(mut commands: Commands, asset_server: Res<AssetServer>) {
commands
.spawn_bundle(
// Create a TextBundle that has a Text with a single section.
TextBundle::from_section(
"Select multiplayer options below.",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::WHITE,
},
) // Set the alignment of the Text
.with_text_alignment(TextAlignment::TOP_CENTER)
// Set the style of the TextBundle itself.
.with_style(Style {
align_self: AlignSelf::FlexEnd,
position_type: PositionType::Absolute,
position: UiRect {
top: Val::Px(125.0),
left: Val::Px((WIN_W * 0.3) / 2.),
..default()
},
..default()
}),
)
.insert(MultOptionsText)
.insert(MultMenuUIElement);
}
pub(crate) fn host_pvp_button_handler(
mut interaction_query: Query<
(&Interaction, &mut UiColor, &Children),
(Changed<Interaction>, With<HostPVPButton>),
>,
mut text_query: Query<&mut Text>,
// game_channel: Res<GameChannel>,
mut game_client: ResMut<GameClient>,
mut commands: Commands,
) {
for (interaction, mut color, children) in &mut interaction_query {
let mut text = text_query
.get_mut(*children.iter().next().unwrap())
.unwrap();
match *interaction {
Interaction::Clicked => {
info!("Hosting pvp game...");
text.sections[0].value = "HOST PVP GAME".to_string();
*color = PRESSED_BUTTON.into();
// Having a listener here doesn't make sense. Networking listeners should not be attached to
// button clicks. What this should do, most likely, is set the current game client to be a host,
// and change the state into a listening state. Once in a listening state, the host waits for a
// CONNECT or similar request, and then handles it from there. Listening should NOT occur in an
// interaction query, and ESPECIALLY not just one time. This should be a `loop`ed operation.
// In all honesty, it should just be able to use the udp_message_listener system above.
// If player clicks on host button, designate them as the host
game_client.player_type = PlayerType::Host;
commands.insert_resource(HostMarker {});
commands.insert_resource(MultiplayerModeSelected {
mode: MultiplayerMode::PvP,
});
commands.insert_resource(NextState(GameState::MultiplayerWaiting));
// let mut buf = [0; 2048];
// match game_client.socket.udp_socket.recv(&mut buf) {
// Ok(received) => {
// println!("received {received} bytes. The msg is: {}", from_utf8(&buf[..received]).unwrap());
// info!("GETS TO HOST BUTTON CLICKED");
// let client_info = from_utf8(&buf[..received]).unwrap().to_string();
// game_client.socket.udp_socket.connect(client_info);
// //game_client.ready_for_battle = true;
// // for z in 1..10 {
// let cloned = game_client.socket.udp_socket.try_clone().unwrap();
// cloned.send(b"TRUE");
// // }
// commands.insert_resource(NextState(GameState::MultiplayerBattle));
// },
// Err(e) => {
// //info!("No message was received: {}", e)
// }
// }
}
Interaction::Hovered => {
text.sections[0].value = "HOST PVP GAME".to_string();
*color = HOVERED_BUTTON.into();
}
Interaction::None => {
text.sections[0].value = "HOST PVP GAME".to_string();
*color = NORMAL_BUTTON.into();
}
}
}
}
pub(crate) fn client_pvp_button_handler(
mut interaction_query: Query<
(&Interaction, &mut UiColor, &Children),
(Changed<Interaction>, With<ClientPVPButton>),
>,
mut text_query: Query<&mut Text>,
mut game_client: ResMut<GameClient>,
mut commands: Commands,
) {
for (interaction, mut color, children) in &mut interaction_query {
let mut text = text_query
.get_mut(*children.iter().next().unwrap())
.unwrap();
match *interaction {
Interaction::Clicked => {
text.sections[0].value = "JOIN PVP GAME".to_string();
*color = PRESSED_BUTTON.into();
// if player clicks on client button, designate them as the client
game_client.player_type = PlayerType::Client;
commands.insert_resource(ClientMarker {});
commands.insert_resource(MultiplayerModeSelected {
mode: MultiplayerMode::PvP,
});
commands.insert_resource(NextState(GameState::MultiplayerWaiting));
// get host IP
println!("Enter in host IP address.");
let mut host_ip_addr: String = String::new();
//placeholder value for scope purposes
let mut ipv4_addr = Ipv4Addr::new(127, 0, 0, 1);
match io::stdin().read_line(&mut host_ip_addr) {
Ok(_) => {
host_ip_addr = host_ip_addr.trim().to_string();
}
Err(_e) => {
error!("ERROR while reading in host's IP address: {}", _e);
}
}
// get host port
println!("Enter in host port.");
let mut host_port: String = String::new();
match io::stdin().read_line(&mut host_port) {
Ok(_) => {
host_port = host_port.trim().to_string();
}
Err(_e) => {
error!("ERROR while reading in host's port number: {}", _e);
}
}
let host_addr_port = format!("{}:{}", host_ip_addr, host_port);
info!("printed this: {}", host_addr_port);
game_client.socket.udp_socket.connect(host_addr_port);
let client_info = game_client.socket.socket_addr.to_string();
game_client
.socket
.udp_socket
.send(client_info.as_bytes())
.expect("Error on send");
}
Interaction::Hovered => {
text.sections[0].value = "JOIN PVP GAME".to_string();
*color = HOVERED_BUTTON.into();
}
Interaction::None => {
text.sections[0].value = "JOIN PVP GAME".to_string();
*color = NORMAL_BUTTON.into();
}
}
}
}
pub(crate) fn host_pve_button_handler(
mut interaction_query: Query<
(&Interaction, &mut UiColor, &Children),
(Changed<Interaction>, With<HostPVEButton>),
>,
mut text_query: Query<&mut Text>,
// game_channel: Res<GameChannel>,
mut game_client: ResMut<GameClient>,
mut commands: Commands,
) {
for (interaction, mut color, children) in &mut interaction_query {
let mut text = text_query
.get_mut(*children.iter().next().unwrap())
.unwrap();
match *interaction {
Interaction::Clicked => {
info!("Hosting pve game...");
text.sections[0].value = "HOST PVE GAME".to_string();
*color = PRESSED_BUTTON.into();
// Having a listener here doesn't make sense. Networking listeners should not be attached to
// button clicks. What this should do, most likely, is set the current game client to be a host,
// and change the state into a listening state. Once in a listening state, the host waits for a
// CONNECT or similar request, and then handles it from there. Listening should NOT occur in an
// interaction query, and ESPECIALLY not just one time. This should be a `loop`ed operation.
// In all honesty, it should just be able to use the udp_message_listener system above.
// If player clicks on host button, designate them as the host
game_client.player_type = PlayerType::Host;
commands.insert_resource(HostMarker {});
commands.insert_resource(MultiplayerModeSelected {
mode: MultiplayerMode::PvE,
});
commands.insert_resource(NextState(GameState::MultiplayerWaiting));
// let mut buf = [0; 2048];
// match game_client.socket.udp_socket.recv(&mut buf) {
// Ok(received) => {
// println!("received {received} bytes. The msg is: {}", from_utf8(&buf[..received]).unwrap());
// info!("GETS TO HOST BUTTON CLICKED");
// let client_info = from_utf8(&buf[..received]).unwrap().to_string();
// game_client.socket.udp_socket.connect(client_info);
// //game_client.ready_for_battle = true;
// // for z in 1..10 {
// let cloned = game_client.socket.udp_socket.try_clone().unwrap();
// cloned.send(b"TRUE");
// // }
// commands.insert_resource(NextState(GameState::MultiplayerBattle));
// },
// Err(e) => {
// //info!("No message was received: {}", e)
// }
// }
}
Interaction::Hovered => {
text.sections[0].value = "HOST PVE GAME".to_string();
*color = HOVERED_BUTTON.into();
}
Interaction::None => {
text.sections[0].value = "HOST PVE GAME".to_string();
*color = NORMAL_BUTTON.into();
}
}
}
}
pub(crate) fn client_pve_button_handler(
mut interaction_query: Query<
(&Interaction, &mut UiColor, &Children),
(Changed<Interaction>, With<ClientPVEButton>),
>,
mut text_query: Query<&mut Text>,
mut game_client: ResMut<GameClient>,
mut commands: Commands,
) {
for (interaction, mut color, children) in &mut interaction_query {
let mut text = text_query
.get_mut(*children.iter().next().unwrap())
.unwrap();
match *interaction {
Interaction::Clicked => {
text.sections[0].value = "JOIN PVE GAME".to_string();
*color = PRESSED_BUTTON.into();
// if player clicks on client button, designate them as the client
game_client.player_type = PlayerType::Client;
commands.insert_resource(ClientMarker {});
commands.insert_resource(MultiplayerModeSelected {
mode: MultiplayerMode::PvE,
});
commands.insert_resource(NextState(GameState::MultiplayerWaiting));
// get host IP
println!("Enter in host IP address.");
let mut host_ip_addr: String = String::new();
//placeholder value for scope purposes
let mut ipv4_addr = Ipv4Addr::new(127, 0, 0, 1);
match io::stdin().read_line(&mut host_ip_addr) {
Ok(_) => {
host_ip_addr = host_ip_addr.trim().to_string();
}
Err(_e) => {
error!("ERROR while reading in host's IP address: {}", _e);
}
}
// get host port
println!("Enter in host port.");
let mut host_port: String = String::new();
match io::stdin().read_line(&mut host_port) {
Ok(_) => {
host_port = host_port.trim().to_string();
}
Err(_e) => {
error!("ERROR while reading in host's port number: {}", _e);
}
}
let host_addr_port = format!("{}:{}", host_ip_addr, host_port);
info!("printed this: {}", host_addr_port);
game_client.socket.udp_socket.connect(host_addr_port);
let client_info = game_client.socket.socket_addr.to_string();
game_client
.socket
.udp_socket
.send(client_info.as_bytes())
.expect("Error on send");
}
Interaction::Hovered => {
text.sections[0].value = "JOIN PVE GAME".to_string();
*color = HOVERED_BUTTON.into();
}
Interaction::None => {
text.sections[0].value = "JOIN PVE GAME".to_string();
*color = NORMAL_BUTTON.into();
}
}
}
}