1use audio_code::prelude::*;
7
8struct Settings {
10 volume: f32,
11 difficulty: usize,
12 name: String,
13}
14
15struct MainMenu;
16
17fn main_menu() -> Menu {
18 Menu::new("main", "Main menu")
19 .button("play", "Play")
20 .button("options", "Options")
21 .button("name", "Change name")
22 .button("quit", "Quit")
23 .closable(false)
24 .wrap(true)
25}
26
27fn options_menu(s: &Settings) -> Menu {
28 Menu::new("options", "Options")
29 .slider("volume", "Volume", s.volume * 100.0, 0.0, 100.0, 10.0)
30 .choice("difficulty", "Difficulty", &["Easy", "Normal", "Hard"], s.difficulty)
31 .text_field("name", "Player name", s.name.clone())
32 .button("back", "Back")
33}
34
35impl Scene for MainMenu {
36 fn start(&mut self, ctx: &mut Context) {
37 ctx.ui.set_sound_data(UiSound::Navigate, Synth::triangle(1800.0).length(0.025).decay(150.0).volume(0.4));
40 ctx.ui.set_sound_data(UiSound::Wrap, Synth::triangle(1800.0).sweep_to(2600.0).length(0.06).decay(60.0).volume(0.4));
41 ctx.ui.set_sound_data(UiSound::Typing, Synth::noise().length(0.012).decay(300.0).volume(0.25));
42 ctx.ui.set_sound_data(
43 UiSound::Activate,
44 Synth::sine(880.0).length(0.04).volume(0.35).then(Synth::sine(1320.0).length(0.08).decay(40.0).volume(0.35)),
45 );
46 ctx.insert(Settings { volume: 0.8, difficulty: 1, name: "Player".into() });
47 ctx.ui.open(main_menu());
48 }
49
50 fn on_ui(&mut self, event: &UiEvent, ctx: &mut Context) {
51 match event {
52 UiEvent::Activated { menu, item } => match (menu.as_str(), item.as_str()) {
53 ("main", "play") => {
54 let s = ctx.get::<Settings>().expect("settings exist");
55 let text = format!("Good luck, {}! (this is where your game would start)", s.name);
56 ctx.ui.message("intro", text);
57 }
58 ("main", "options") => {
59 let menu = options_menu(ctx.get::<Settings>().expect("settings exist"));
60 ctx.ui.open(menu);
61 }
62 ("main", "name") => ctx.ui.open(TextInput::new("name", "Enter your name").max_length(20).required()),
63 ("main", "quit") => ctx.ui.open(Confirm::new("quit", "Do you really want to quit?").default_no()),
64 ("options", "back") => ctx.ui.close(),
65 _ => {}
66 },
67 UiEvent::Changed { menu, item, value } if menu == "options" => {
68 let s = ctx.get_mut::<Settings>().expect("settings exist");
69 match item.as_str() {
70 "volume" => s.volume = value.as_f32() / 100.0,
71 "difficulty" => s.difficulty = value.as_index(),
72 "name" => s.name = value.as_str().to_string(),
73 _ => {}
74 }
75 let volume = s.volume;
76 ctx.audio.set_master_volume(volume);
77 }
78 UiEvent::TextSubmitted { id, text } if id == "name" => {
79 ctx.get_mut::<Settings>().expect("settings exist").name = text.clone();
80 ctx.speech.speak_queued(format!("Hello, {text}"));
81 }
82 UiEvent::Confirmed { id, yes: true } if id == "quit" => ctx.quit(),
83 _ => {}
84 }
85 }
86
87 fn update(&mut self, _ctx: &mut Context) {}
88}
89
90fn main() -> audio_code::Result<()> {
91 Engine::new("Menu demo").echo_speech(true).run(MainMenu)
92}