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
use bevy::{app::AppExit, prelude::*};
use de_gui::{ButtonCommands, GuiCommands, OuterStyle};

use crate::{menu::Menu, MenuState};

pub(crate) struct MainMenuPlugin;

impl Plugin for MainMenuPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(OnEnter(MenuState::MainMenu), setup)
            .add_systems(Update, button_system.run_if(in_state(MenuState::MainMenu)));
    }
}

#[derive(Component, Clone, Copy)]
enum ButtonAction {
    SwithState(MenuState),
    Quit,
}

fn setup(mut commands: GuiCommands, menu: Res<Menu>) {
    let column_node = commands
        .spawn(NodeBundle {
            style: Style {
                flex_direction: FlexDirection::Column,
                width: Val::Percent(25.),
                height: Val::Percent(100.),
                margin: UiRect::all(Val::Auto),
                align_items: AlignItems::Center,
                justify_content: JustifyContent::Center,
                ..default()
            },
            ..default()
        })
        .id();
    commands.entity(menu.root_node()).add_child(column_node);

    button(
        &mut commands,
        column_node,
        ButtonAction::SwithState(MenuState::SinglePlayerGame),
        "Singleplayer",
    );
    button(
        &mut commands,
        column_node,
        ButtonAction::SwithState(MenuState::Multiplayer),
        "Multiplayer",
    );
    button(&mut commands, column_node, ButtonAction::Quit, "Quit Game");
}

fn button(commands: &mut GuiCommands, parent: Entity, action: ButtonAction, caption: &str) {
    let button = commands
        .spawn_button(
            OuterStyle {
                width: Val::Percent(100.),
                height: Val::Percent(8.),
                margin: UiRect::new(
                    Val::Percent(0.),
                    Val::Percent(0.),
                    Val::Percent(2.),
                    Val::Percent(2.),
                ),
            },
            caption,
        )
        .insert(action)
        .id();
    commands.entity(parent).add_child(button);
}

fn button_system(
    mut next_state: ResMut<NextState<MenuState>>,
    mut exit: EventWriter<AppExit>,
    interactions: Query<(&Interaction, &ButtonAction), Changed<Interaction>>,
) {
    for (&interaction, &action) in interactions.iter() {
        if let Interaction::Pressed = interaction {
            match action {
                ButtonAction::SwithState(state) => next_state.set(state),
                ButtonAction::Quit => {
                    exit.send(AppExit);
                }
            };
        }
    }
}