1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 02:07:36 +00:00

Snake: Make initialization from GML fallible

Replace the C_OBJECT factory functions with a custom try_create() which
loads the various bitmaps. Any failures there are now propagated.
This commit is contained in:
Sam Atkins 2022-12-29 17:31:34 +00:00 committed by Tim Flynn
parent b32f5dbcff
commit 2069a5a2a0
3 changed files with 11 additions and 9 deletions

View file

@ -19,7 +19,7 @@ REGISTER_WIDGET(Snake, Game);
namespace Snake {
static NonnullRefPtrVector<Gfx::Bitmap> load_food_bitmaps()
ErrorOr<NonnullRefPtr<Game>> Game::try_create()
{
static constexpr auto food_bitmaps_files = Array {
"/res/emoji/U+1F41F.png"sv,
@ -54,23 +54,23 @@ static NonnullRefPtrVector<Gfx::Bitmap> load_food_bitmaps()
};
NonnullRefPtrVector<Gfx::Bitmap> food_bitmaps;
food_bitmaps.ensure_capacity(food_bitmaps_files.size());
TRY(food_bitmaps.try_ensure_capacity(food_bitmaps_files.size()));
for (auto file : food_bitmaps_files) {
auto bitmap = Gfx::Bitmap::try_load_from_file(file);
if (bitmap.is_error()) {
dbgln("\033[31;1mCould not load bitmap file\033[0m '{}': {}", file, bitmap.error());
VERIFY_NOT_REACHED();
return bitmap.release_error();
}
food_bitmaps.unchecked_append(bitmap.release_value());
}
return food_bitmaps;
return adopt_nonnull_ref_or_enomem(new (nothrow) Game(move(food_bitmaps)));
}
Game::Game()
: m_food_bitmaps(load_food_bitmaps())
Game::Game(NonnullRefPtrVector<Gfx::Bitmap> food_bitmaps)
: m_food_bitmaps(move(food_bitmaps))
{
set_font(Gfx::FontDatabase::default_fixed_width_font().bold_variant());
reset();

View file

@ -14,9 +14,11 @@
namespace Snake {
class Game : public GUI::Frame {
C_OBJECT(Game);
C_OBJECT_ABSTRACT(Game);
public:
static ErrorOr<NonnullRefPtr<Game>> try_create();
virtual ~Game() override = default;
void start();
@ -28,7 +30,7 @@ public:
Function<bool(u32)> on_score_update;
private:
Game();
explicit Game(NonnullRefPtrVector<Gfx::Bitmap> food_bitmaps);
virtual void paint_event(GUI::PaintEvent&) override;
virtual void keydown_event(GUI::KeyEvent&) override;

View file

@ -49,7 +49,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
window->resize(324, 345);
auto widget = TRY(window->try_set_main_widget<GUI::Widget>());
widget->load_from_gml(snake_gml);
TRY(widget->try_load_from_gml(snake_gml));
auto& game = *widget->find_descendant_of_type_named<Snake::Game>("game");
game.set_focus(true);