1 | // Copyright © SixtyFPS GmbH <info@slint.dev> |
2 | // SPDX-License-Identifier: MIT |
3 | |
4 | // clang-format off |
5 | // main.cpp |
6 | |
7 | #include "memory_game_logic.h" // generated header from memory_game_logic.slint |
8 | |
9 | #include <random> // Added |
10 | |
11 | int main() |
12 | { |
13 | auto main_window = MainWindow::create(); |
14 | auto old_tiles = main_window->get_memory_tiles(); |
15 | std::vector<TileData> new_tiles; |
16 | new_tiles.reserve(old_tiles->row_count() * 2); |
17 | for (int i = 0; i < old_tiles->row_count(); ++i) { |
18 | new_tiles.push_back(*old_tiles->row_data(i)); |
19 | new_tiles.push_back(*old_tiles->row_data(i)); |
20 | } |
21 | std::default_random_engine rng {}; |
22 | std::shuffle(new_tiles.begin(), new_tiles.end(), rng); |
23 | |
24 | auto tiles_model = std::make_shared<slint::VectorModel<TileData>>(new_tiles); |
25 | main_window->set_memory_tiles(tiles_model); |
26 | |
27 | // ANCHOR: game_logic |
28 | |
29 | main_window->on_check_if_pair_solved( |
30 | [main_window_weak = slint::ComponentWeakHandle(main_window)] { |
31 | auto main_window = *main_window_weak.lock(); |
32 | auto tiles_model = main_window->get_memory_tiles(); |
33 | int first_visible_index = -1; |
34 | TileData first_visible_tile; |
35 | for (int i = 0; i < tiles_model->row_count(); ++i) { |
36 | auto tile = *tiles_model->row_data(i); |
37 | if (!tile.image_visible || tile.solved) |
38 | continue; |
39 | if (first_visible_index == -1) { |
40 | first_visible_index = i; |
41 | first_visible_tile = tile; |
42 | continue; |
43 | } |
44 | bool is_pair_solved = tile == first_visible_tile; |
45 | if (is_pair_solved) { |
46 | first_visible_tile.solved = true; |
47 | tiles_model->set_row_data(first_visible_index, |
48 | first_visible_tile); |
49 | tile.solved = true; |
50 | tiles_model->set_row_data(i, tile); |
51 | return; |
52 | } |
53 | main_window->set_disable_tiles(true); |
54 | |
55 | slint::Timer::single_shot(std::chrono::seconds(1), |
56 | [=]() mutable { |
57 | main_window->set_disable_tiles(false); |
58 | first_visible_tile.image_visible = false; |
59 | tiles_model->set_row_data(first_visible_index, |
60 | first_visible_tile); |
61 | tile.image_visible = false; |
62 | tiles_model->set_row_data(i, tile); |
63 | }); |
64 | } |
65 | }); |
66 | // ANCHOR_END: game_logic |
67 | main_window->run(); |
68 | } |
69 | // clang-format on |
70 | |