From b354e858c85d20a56b95cdafef4602cd4a8fe87a Mon Sep 17 00:00:00 2001 From: Baitinq Date: Sun, 18 Dec 2022 20:51:28 +0100 Subject: [PATCH] Snake: Add pause/continue game menu action This patch adds an action in the Snake's game menu that allows for easy pausing/unpausing of the game state. In order to do this, the commit adds new pause()/start() functions in the SnakeGame class ;) --- Userland/Games/Snake/SnakeGame.cpp | 15 +++++++++++++-- Userland/Games/Snake/SnakeGame.h | 2 ++ Userland/Games/Snake/main.cpp | 15 +++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/Userland/Games/Snake/SnakeGame.cpp b/Userland/Games/Snake/SnakeGame.cpp index 98652d1efe..e21d500d94 100644 --- a/Userland/Games/Snake/SnakeGame.cpp +++ b/Userland/Games/Snake/SnakeGame.cpp @@ -59,6 +59,17 @@ SnakeGame::SnakeGame(NonnullRefPtrVector food_bitmaps) m_high_score_text = DeprecatedString::formatted("Best: {}", m_high_score); } +void SnakeGame::pause() +{ + stop_timer(); +} + +void SnakeGame::start() +{ + static constexpr int timer_ms = 100; + start_timer(timer_ms); +} + void SnakeGame::reset() { m_head = { m_rows / 2, m_columns / 2 }; @@ -68,8 +79,8 @@ void SnakeGame::reset() m_score_text = "Score: 0"; m_is_new_high_score = false; m_velocity_queue.clear(); - stop_timer(); - start_timer(100); + pause(); + start(); spawn_fruit(); update(); } diff --git a/Userland/Games/Snake/SnakeGame.h b/Userland/Games/Snake/SnakeGame.h index 1f6edb21ec..e5c07d3ed2 100644 --- a/Userland/Games/Snake/SnakeGame.h +++ b/Userland/Games/Snake/SnakeGame.h @@ -18,6 +18,8 @@ public: static ErrorOr> create(); virtual ~SnakeGame() override = default; + void start(); + void pause(); void reset(); private: diff --git a/Userland/Games/Snake/main.cpp b/Userland/Games/Snake/main.cpp index 5065f5cebe..23a8697261 100644 --- a/Userland/Games/Snake/main.cpp +++ b/Userland/Games/Snake/main.cpp @@ -53,6 +53,21 @@ ErrorOr serenity_main(Main::Arguments arguments) TRY(game_menu->try_add_action(GUI::Action::create("&New Game", { Mod_None, Key_F2 }, TRY(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/reload.png"sv)), [&](auto&) { game->reset(); }))); + static DeprecatedString const pause_text = "&Pause Game"sv; + auto const pause_icon = TRY(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/pause.png"sv)); + static DeprecatedString const continue_text = "&Continue Game"sv; + auto const continue_icon = TRY(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/play.png"sv)); + TRY(game_menu->try_add_action(GUI::Action::create(pause_text, { Mod_None, Key_Space }, pause_icon, [&](auto& action) { + if (game->has_timer()) { + game->pause(); + action.set_text(continue_text); + action.set_icon(continue_icon); + } else { + game->start(); + action.set_text(pause_text); + action.set_icon(pause_icon); + } + }))); TRY(game_menu->try_add_separator()); TRY(game_menu->try_add_action(GUI::CommonActions::make_quit_action([](auto&) { GUI::Application::the()->quit();