this repo has no description
1use bevy::prelude::*;
2
3use crate::ghost::BerriesEaten;
4
5pub fn leaderboard_plugin(app: &mut App) {
6 app.add_systems(Startup, setup.after(crate::ghost::setup))
7 .add_systems(FixedPostUpdate, update_leaderboard);
8}
9
10#[derive(Component)]
11pub struct LeaderBoard;
12
13#[derive(Component)]
14pub struct Lowest;
15
16pub fn setup(mut commands: Commands) {
17 let id = commands
18 .spawn((
19 children![Text::new("Ghost Leaderboard")],
20 Node {
21 position_type: PositionType::Absolute,
22 top: px(10),
23 left: px(10),
24 flex_direction: FlexDirection::Column,
25 ..default()
26 },
27 ))
28 .id();
29
30 let list = commands
31 .spawn((
32 Node {
33 flex_direction: FlexDirection::Column,
34 ..default()
35 },
36 LeaderBoard,
37 ChildOf(id),
38 ))
39 .id();
40
41 commands.spawn((
42 Text::new("Waiting for ghosts..."),
43 TextFont::from_font_size(17.5),
44 TextColor(Color::oklch(0.7, 0.2, 0.0)),
45 Lowest,
46 ChildOf(id),
47 ));
48
49 for n in 0..10 {
50 let color = Color::oklch(0.7, 0.2, 90.0.lerp(135.0, (10 - n) as f32 / 10.0));
51
52 commands.spawn((
53 Text::new("Waiting for ghosts..."),
54 TextFont::from_font_size(17.5),
55 TextColor(color),
56 ChildOf(list),
57 ));
58 }
59}
60
61pub fn update_leaderboard(
62 board: Single<&Children, With<LeaderBoard>>,
63 mut lowest: Single<&mut Text, With<Lowest>>,
64 mut texts: Query<&mut Text, Without<Lowest>>,
65 ghosts: Query<(&Name, &BerriesEaten)>,
66) {
67 ghosts
68 .iter()
69 .sort_by_key::<(&Name, &BerriesEaten), usize>(|(_, e)| e.0)
70 .rev()
71 .zip(board.iter())
72 .for_each(|((ghost, eaten), text)| {
73 texts.get_mut(text).unwrap().0 =
74 format!("{:<10} ate {} berries!", ghost.to_string(), eaten.0);
75 });
76
77 let low = ghosts
78 .iter()
79 .sort_by_key::<(Entity, &BerriesEaten), usize>(|(_, e)| e.0)
80 .next()
81 .unwrap();
82
83 lowest.0 = format!("{:<10} ate {} berries!", low.0.to_string(), low.1.0);
84}