-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtic_tac_toe.rs
708 lines (627 loc) · 22.7 KB
/
tic_tac_toe.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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! A game to showcase single-player and multiplier game.
//! Run it with `cargo run --example tic_tac_toe -- hotseat` to play locally or with `-- client` / `-- server`
use std::{
error::Error,
fmt::{self, Formatter},
net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket},
time::SystemTime,
};
use bevy::{prelude::*, utils::hashbrown::HashMap};
use bevy_replicon::prelude::*;
use bevy_replicon_renet::{
RenetChannelsExt, RepliconRenetPlugins,
netcode::{
ClientAuthentication, NetcodeClientTransport, NetcodeServerTransport, ServerAuthentication,
ServerConfig,
},
renet::{ConnectionConfig, RenetClient, RenetServer},
};
use clap::{Parser, ValueEnum};
use serde::{Deserialize, Serialize};
fn main() {
App::new()
.init_resource::<Cli>() // Parse CLI before creating window.
.add_plugins((
DefaultPlugins.build().set(WindowPlugin {
primary_window: Some(Window {
title: "Tic-Tac-Toe".into(),
resolution: (800.0, 600.0).into(),
..Default::default()
}),
..Default::default()
}),
RepliconPlugins.set(ServerPlugin {
// We start replication manually because we want to exchange cell mappings first.
replicate_after_connect: false,
..Default::default()
}),
RepliconRenetPlugins,
TicTacToePlugin,
))
.run();
}
struct TicTacToePlugin;
impl Plugin for TicTacToePlugin {
fn build(&self, app: &mut App) {
app.init_state::<GameState>()
.init_resource::<SymbolFont>()
.init_resource::<TurnSymbol>()
.replicate::<Symbol>()
.add_client_trigger::<CellPick>(Channel::Ordered)
.add_client_trigger::<MapCells>(Channel::Ordered)
.add_server_trigger::<MakeLocal>(Channel::Ordered)
.insert_resource(ClearColor(BACKGROUND_COLOR))
.add_observer(disconnect_by_client)
.add_observer(init_client)
.add_observer(make_local)
.add_observer(apply_pick)
.add_observer(init_symbols)
.add_observer(advance_turn)
.add_systems(Startup, (setup_ui, read_cli.map(Result::unwrap)))
.add_systems(
OnEnter(GameState::InGame),
(show_turn_text, show_turn_symbol),
)
.add_systems(OnEnter(GameState::Disconnected), show_disconnected_text)
.add_systems(OnEnter(GameState::Winner), show_winner_text)
.add_systems(OnEnter(GameState::Tie), show_tie_text)
.add_systems(OnEnter(GameState::Disconnected), stop_networking)
.add_systems(
Update,
(
show_connecting_text.run_if(resource_added::<RenetClient>),
show_waiting_client_text.run_if(resource_added::<RenetServer>),
client_start.run_if(client_just_connected),
(
disconnect_by_server.run_if(client_just_disconnected),
update_buttons_background.run_if(local_player_turn),
show_turn_symbol.run_if(resource_changed::<TurnSymbol>),
)
.run_if(in_state(GameState::InGame)),
),
);
}
}
const GRID_SIZE: usize = 3;
const BACKGROUND_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
// Bottom text defined in two sections, first for text and second for symbols with different font.
const TEXT_SECTION: usize = 0;
const SYMBOL_SECTION: usize = 1;
const CELL_SIZE: f32 = 100.0;
const LINE_THICKNESS: f32 = 10.0;
const BUTTON_SIZE: f32 = CELL_SIZE / 1.2;
const BUTTON_MARGIN: f32 = (CELL_SIZE + LINE_THICKNESS - BUTTON_SIZE) / 2.0;
fn read_cli(
mut commands: Commands,
cli: Res<Cli>,
channels: Res<RepliconChannels>,
) -> Result<(), Box<dyn Error>> {
const PROTOCOL_ID: u64 = 0;
match *cli {
Cli::Hotseat => {
info!("starting hotseat");
// Set all players to server to play from a single machine and start the game right away.
commands.spawn((LocalPlayer, Symbol::Cross));
commands.spawn((LocalPlayer, Symbol::Nought));
commands.set_state(GameState::InGame);
}
Cli::Server { port, symbol } => {
info!("starting server as {symbol} at port {port}");
let server_channels_config = channels.server_configs();
let client_channels_config = channels.client_configs();
let server = RenetServer::new(ConnectionConfig {
server_channels_config,
client_channels_config,
..Default::default()
});
let current_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, port))?;
let server_config = ServerConfig {
current_time,
max_clients: 1,
protocol_id: PROTOCOL_ID,
authentication: ServerAuthentication::Unsecure,
public_addresses: Default::default(),
};
let transport = NetcodeServerTransport::new(server_config, socket)?;
commands.insert_resource(server);
commands.insert_resource(transport);
commands.spawn((LocalPlayer, symbol));
}
Cli::Client { port, ip } => {
info!("connecting to {ip}:{port}");
let server_channels_config = channels.server_configs();
let client_channels_config = channels.client_configs();
let client = RenetClient::new(ConnectionConfig {
server_channels_config,
client_channels_config,
..Default::default()
});
let current_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
let client_id = current_time.as_millis() as u64;
let server_addr = SocketAddr::new(ip, port);
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))?;
let authentication = ClientAuthentication::Unsecure {
client_id,
protocol_id: PROTOCOL_ID,
server_addr,
user_data: None,
};
let transport = NetcodeClientTransport::new(current_time, authentication, socket)?;
commands.insert_resource(client);
commands.insert_resource(transport);
}
}
Ok(())
}
fn setup_ui(mut commands: Commands, symbol_font: Res<SymbolFont>) {
commands.spawn(Camera2d);
const LINES_COUNT: usize = GRID_SIZE + 1;
const BOARD_SIZE: f32 = CELL_SIZE * GRID_SIZE as f32 + LINES_COUNT as f32 * LINE_THICKNESS;
const BOARD_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
for line in 0..LINES_COUNT {
let position =
-BOARD_SIZE / 2.0 + line as f32 * (CELL_SIZE + LINE_THICKNESS) + LINE_THICKNESS / 2.0;
// Horizontal
commands.spawn((
Sprite {
color: BOARD_COLOR,
..Default::default()
},
Transform {
translation: Vec3::Y * position,
scale: Vec3::new(BOARD_SIZE, LINE_THICKNESS, 1.0),
..Default::default()
},
));
// Vertical
commands.spawn((
Sprite {
color: BOARD_COLOR,
..Default::default()
},
Transform {
translation: Vec3::X * position,
scale: Vec3::new(LINE_THICKNESS, BOARD_SIZE, 1.0),
..Default::default()
},
));
}
const TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
const FONT_SIZE: f32 = 32.0;
commands
.spawn(Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..Default::default()
})
.with_children(|parent| {
parent
.spawn(Node {
flex_direction: FlexDirection::Column,
width: Val::Px(BOARD_SIZE - LINE_THICKNESS),
height: Val::Px(BOARD_SIZE - LINE_THICKNESS),
..Default::default()
})
.with_children(|parent| {
parent
.spawn(Node {
display: Display::Grid,
grid_template_columns: vec![GridTrack::auto(); GRID_SIZE],
..Default::default()
})
.with_children(|parent| {
for index in 0..GRID_SIZE * GRID_SIZE {
parent.spawn(Cell { index }).observe(pick_cell);
}
});
parent
.spawn(Node {
margin: UiRect::top(Val::Px(20.0)),
justify_content: JustifyContent::Center,
..Default::default()
})
.with_children(|parent| {
parent
.spawn((
Text::default(),
TextFont {
font_size: FONT_SIZE,
..Default::default()
},
TextColor(TEXT_COLOR),
BottomText,
))
.with_child((
TextSpan::default(),
TextFont {
font: symbol_font.0.clone(),
font_size: FONT_SIZE,
..Default::default()
},
TextColor(TEXT_COLOR),
));
});
});
});
}
/// Converts point clicks into cell picking events.
///
/// We don't just send mouse clicks to save traffic, they contain a lot of extra information.
fn pick_cell(
trigger: Trigger<Pointer<Click>>,
mut commands: Commands,
turn_symbol: Res<TurnSymbol>,
game_state: Res<State<GameState>>,
cells: Query<&Cell>,
players: Query<&Symbol, With<LocalPlayer>>,
) {
if *game_state != GameState::InGame {
return;
}
if !local_player_turn(turn_symbol, players) {
return;
}
let cell = cells
.get(trigger.entity())
.expect("cells should have assigned indices");
// We don't check if a cell can't be picked on client on purpose
// just to demonstrate how server can receive invalid requests from a client.
info!("picking cell {}", cell.index);
commands.client_trigger(CellPick { index: cell.index });
}
/// Handles cell pick events.
///
/// Used only for single-player and server.
fn apply_pick(
trigger: Trigger<FromClient<CellPick>>,
mut commands: Commands,
cells: Query<(Entity, &Cell), Without<Symbol>>,
turn_symbol: Res<TurnSymbol>,
players: Query<&Symbol>,
) {
// It's good to check the received data because client could be cheating.
if trigger.client_entity != SERVER {
let symbol = *players
.get(trigger.client_entity)
.expect("all clients should have assigned symbols");
if symbol != **turn_symbol {
error!(
"`{}` chose cell {} at wrong turn",
trigger.client_entity, trigger.index
);
return;
}
}
let Some((entity, _)) = cells.iter().find(|(_, cell)| cell.index == trigger.index) else {
error!(
"`{}` has chosen occupied or invalid cell {}",
trigger.client_entity, trigger.index
);
return;
};
commands.entity(entity).insert(**turn_symbol);
}
/// Initializes spawned symbol on client after replication and on server / single-player right after the spawn.
fn init_symbols(
trigger: Trigger<OnAdd, Symbol>,
mut commands: Commands,
symbol_font: Res<SymbolFont>,
mut cells: Query<(&mut BackgroundColor, &Symbol), With<Button>>,
) {
let Ok((mut background, symbol)) = cells.get_mut(trigger.entity()) else {
return;
};
*background = BACKGROUND_COLOR.into();
commands
.entity(trigger.entity())
.remove::<Interaction>()
.with_children(|parent| {
parent.spawn((
Text::new(symbol.glyph()),
TextFont {
font: symbol_font.0.clone(),
font_size: 65.0,
..Default::default()
},
TextColor(symbol.color()),
));
});
}
/// Sends cell and local player entities and starts the game.
///
/// Replicon maps entities when you replicate them from server automatically.
/// But in this game we spawn cells beforehand. So we send a special event to
/// server to receive replication to already existing entities.
///
/// Used only for client.
fn client_start(mut commands: Commands, cells: Query<(Entity, &Cell)>) {
let mut entities = HashMap::new();
for (entity, cell) in &cells {
entities.insert(cell.index, entity);
}
commands.client_trigger(MapCells(entities));
commands.set_state(GameState::InGame);
}
/// Estabializes mappings between spawned client and server entities and starts the game.
///
/// Used only for server.
fn init_client(
trigger: Trigger<FromClient<MapCells>>,
mut commands: Commands,
cells: Query<(Entity, &Cell)>,
server_symbol: Single<&Symbol, With<LocalPlayer>>,
) {
// Usually entity map modified directly on an connected client entity,
// it's a required component of `ReplicatedClient`.
// But since we set `replicate_after_connect` to `false`,
// we insert it together with `ReplicatedClient`.
let mut entity_map = ClientEntityMap::default();
for (server_entity, cell) in &cells {
let Some(&client_entity) = trigger.get(&cell.index) else {
error!("received cells missing index {}, disconnecting", cell.index);
commands.set_state(GameState::Disconnected);
return;
};
entity_map.insert(server_entity, client_entity);
}
// Utilize client entity as a player for convenient lookups by `client_entity`.
commands.entity(trigger.client_entity).insert((
Player,
server_symbol.next(),
ReplicatedClient,
entity_map,
));
commands.server_trigger_targets(
ToClients {
mode: SendMode::Direct(trigger.client_entity),
event: MakeLocal,
},
trigger.client_entity,
);
commands.set_state(GameState::InGame);
}
fn make_local(trigger: Trigger<MakeLocal>, mut commands: Commands) {
commands.entity(trigger.entity()).insert(LocalPlayer);
}
/// Sets the game in disconnected state if client closes the connection.
///
/// Used only for server.
fn disconnect_by_client(
_trigger: Trigger<OnRemove, ConnectedClient>,
game_state: Res<State<GameState>>,
mut commands: Commands,
) {
info!("client closed the connection");
if *game_state == GameState::InGame {
commands.set_state(GameState::Disconnected);
}
}
/// Sets the game in disconnected state if server closes the connection.
///
/// Used only for client.
fn disconnect_by_server(mut commands: Commands) {
info!("server closed the connection");
commands.set_state(GameState::Disconnected);
}
/// Closes all sockets.
fn stop_networking(mut commands: Commands) {
commands.remove_resource::<RenetServer>();
commands.remove_resource::<RenetClient>();
}
/// Checks the winner and advances the turn.
fn advance_turn(
_trigger: Trigger<OnAdd, Symbol>,
mut commands: Commands,
mut turn_symbol: ResMut<TurnSymbol>,
symbols: Query<(&Cell, &Symbol)>,
) {
let mut board = [None; GRID_SIZE * GRID_SIZE];
for (cell, &symbol) in &symbols {
board[cell.index] = Some(symbol);
}
const WIN_CONDITIONS: [[usize; GRID_SIZE]; 8] = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for indices in WIN_CONDITIONS {
let symbols = indices.map(|index| board[index]);
if symbols[0].is_some() && symbols.windows(2).all(|symbols| symbols[0] == symbols[1]) {
commands.set_state(GameState::Winner);
info!("{} wins the game", **turn_symbol);
return;
}
}
if board.iter().all(Option::is_some) {
info!("game ended in a tie");
commands.set_state(GameState::Tie);
} else {
**turn_symbol = turn_symbol.next();
}
}
fn update_buttons_background(
mut buttons: Query<(&Interaction, &mut BackgroundColor), Changed<Interaction>>,
) {
const HOVER_COLOR: Color = Color::srgb(0.85, 0.85, 0.85);
const PRESS_COLOR: Color = Color::srgb(0.95, 0.95, 0.95);
for (interaction, mut background) in &mut buttons {
match interaction {
Interaction::Pressed => *background = PRESS_COLOR.into(),
Interaction::Hovered => *background = HOVER_COLOR.into(),
Interaction::None => *background = BACKGROUND_COLOR.into(),
};
}
}
fn show_turn_text(mut writer: TextUiWriter, text_entity: Single<Entity, With<BottomText>>) {
*writer.text(*text_entity, TEXT_SECTION) = "Current turn: ".into();
}
fn show_turn_symbol(
mut writer: TextUiWriter,
turn_symbol: Res<TurnSymbol>,
text_entity: Single<Entity, With<BottomText>>,
) {
*writer.text(*text_entity, SYMBOL_SECTION) = turn_symbol.glyph().into();
*writer.color(*text_entity, SYMBOL_SECTION) = turn_symbol.color().into();
}
fn show_disconnected_text(mut writer: TextUiWriter, text_entity: Single<Entity, With<BottomText>>) {
*writer.text(*text_entity, TEXT_SECTION) = "Disconnected".into();
writer.text(*text_entity, SYMBOL_SECTION).clear();
}
fn show_winner_text(mut writer: TextUiWriter, text_entity: Single<Entity, With<BottomText>>) {
*writer.text(*text_entity, TEXT_SECTION) = "Winner: ".into();
}
fn show_tie_text(mut writer: TextUiWriter, text_entity: Single<Entity, With<BottomText>>) {
*writer.text(*text_entity, TEXT_SECTION) = "Tie".into();
writer.text(*text_entity, SYMBOL_SECTION).clear();
}
fn show_connecting_text(mut writer: TextUiWriter, text_entity: Single<Entity, With<BottomText>>) {
*writer.text(*text_entity, TEXT_SECTION) = "Connecting".into();
}
fn show_waiting_client_text(
mut writer: TextUiWriter,
text_entity: Single<Entity, With<BottomText>>,
) {
*writer.text(*text_entity, TEXT_SECTION) = "Waiting client".into();
}
/// Returns `true` if the local player can select cells.
fn local_player_turn(
turn_symbol: Res<TurnSymbol>,
players: Query<&Symbol, With<LocalPlayer>>,
) -> bool {
players.iter().any(|&symbol| symbol == **turn_symbol)
}
const PORT: u16 = 5000;
#[derive(Parser, PartialEq, Resource)]
enum Cli {
Hotseat,
Server {
#[arg(short, long, default_value_t = PORT)]
port: u16,
#[arg(short, long, default_value_t = Symbol::Cross)]
symbol: Symbol,
},
Client {
#[arg(short, long, default_value_t = Ipv4Addr::LOCALHOST.into())]
ip: IpAddr,
#[arg(short, long, default_value_t = PORT)]
port: u16,
},
}
impl Default for Cli {
fn default() -> Self {
Self::parse()
}
}
/// Font to display unicode characters for [`Symbol`].
#[derive(Resource)]
struct SymbolFont(Handle<Font>);
impl FromWorld for SymbolFont {
fn from_world(world: &mut World) -> Self {
let asset_server = world.resource::<AssetServer>();
Self(asset_server.load("NotoEmoji-Regular.ttf"))
}
}
#[derive(States, Clone, Copy, Debug, Eq, Hash, PartialEq, Default)]
enum GameState {
#[default]
WaitingPlayer,
InGame,
Winner,
Tie,
Disconnected,
}
/// Contains symbol to be used this turn.
#[derive(Resource, Default, Deref, DerefMut)]
struct TurnSymbol(Symbol);
/// A component that defines the symbol of a [`Player`], current [`TurnSymbol`] or a filled cell (see [`CellPick`]).
#[derive(Clone, Component, Copy, Default, Deserialize, Eq, PartialEq, Serialize, ValueEnum)]
enum Symbol {
#[default]
Cross,
Nought,
}
impl Symbol {
fn glyph(self) -> &'static str {
match self {
Symbol::Cross => "❌",
Symbol::Nought => "⭕",
}
}
fn color(self) -> Color {
match self {
Symbol::Cross => Color::srgb(1.0, 0.5, 0.5),
Symbol::Nought => Color::srgb(0.5, 0.5, 1.0),
}
}
fn next(self) -> Self {
match self {
Symbol::Cross => Symbol::Nought,
Symbol::Nought => Symbol::Cross,
}
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Symbol::Cross => f.write_str("cross"),
Symbol::Nought => f.write_str("nought"),
}
}
}
/// Marker for UI node with bottom text.
#[derive(Component)]
struct BottomText;
/// Cell location on the grid.
///
/// We want to replicate all cells, so we just set [`Replicated`] as a required component.
#[derive(Component)]
#[require(
Button,
Replicated,
BackgroundColor(|| BackgroundColor(BACKGROUND_COLOR)),
Node(|| Node {
width: Val::Px(BUTTON_SIZE),
height: Val::Px(BUTTON_SIZE),
margin: UiRect::all(Val::Px(BUTTON_MARGIN)),
..Default::default()
})
)]
struct Cell {
index: usize,
}
/// Marker for a player entity.
#[derive(Component, Default)]
#[require(Replicated)]
struct Player;
/// Marks [`Player`] as locally controlled.
///
/// Used to determine if player can place a symbol.
///
/// See also [`local_player_turn`].
#[derive(Component)]
#[require(Player)]
struct LocalPlayer;
/// A trigger that indicates a symbol pick.
///
/// We don't replicate the whole UI, so we can't just send the picked entity because on server it may be different.
/// So we send the cell location in grid and calculate the entity on server based on this.
#[derive(Clone, Copy, Deserialize, Event, Serialize)]
struct CellPick {
index: usize,
}
/// A trigger to send client cell entities to server to estabialize mappings for replication.
///
/// See [`client_start`] for details.
#[derive(Event, Deref, Serialize, Deserialize)]
struct MapCells(HashMap<usize, Entity>);
/// A trigger that instructs the client to mark a specific entity as [`LocalPlayer`].
#[derive(Event, Serialize, Deserialize)]
struct MakeLocal;