1
0
Fork 0
slint-memory-game/src/main.rs

62 lines
1.9 KiB
Rust
Raw Permalink Normal View History

2023-05-03 14:57:56 -04:00
::slint::include_modules!();
2023-05-03 14:10:32 -04:00
2023-05-03 14:57:56 -04:00
fn main() -> Result<(), slint::PlatformError> {
use ::rand::seq::SliceRandom;
use ::slint::{Model, Timer, VecModel};
use std::rc::Rc;
use std::time::Duration;
2023-05-03 13:54:11 -04:00
2023-05-03 14:57:56 -04:00
let main_window = MainWindow::new()?;
2023-05-03 14:10:32 -04:00
2023-05-03 14:57:56 -04:00
// Fetch the tiles from the model, and then duplicate them so we have pairs
2023-05-03 14:10:32 -04:00
let mut tiles: Vec<TileData> = main_window.get_memory_tiles().iter().collect();
tiles.extend(tiles.clone());
2023-05-03 14:57:56 -04:00
// Randomize the tiles
2023-05-03 14:10:32 -04:00
let mut rng = rand::thread_rng();
tiles.shuffle(&mut rng);
// Update the model
let tiles_model = Rc::new(VecModel::from(tiles));
2023-05-03 14:32:05 -04:00
main_window.set_memory_tiles(tiles_model.clone().into());
let main_window_weak = main_window.as_weak();
2023-05-03 14:57:56 -04:00
2023-05-03 14:32:05 -04:00
main_window.on_check_if_pair_solved(move || {
let mut flipped_tiles = tiles_model
.iter()
.enumerate()
.filter(|(_, tile)| tile.image_visible && !tile.solved);
if let (Some((t1_idx, mut t1)), Some((t2_idx, mut t2))) =
(flipped_tiles.next(), flipped_tiles.next())
{
let is_pair_solved = t1 == t2;
if is_pair_solved {
t1.solved = true;
t2.solved = true;
2023-05-03 14:57:56 -04:00
tiles_model.set_row_data(t1_idx, t1);
2023-05-03 14:32:05 -04:00
tiles_model.set_row_data(t2_idx, t2);
} else {
let main_window = main_window_weak.unwrap();
let tiles_model = tiles_model.clone();
2023-05-03 14:57:56 -04:00
main_window.set_disable_tiles(true);
2023-05-03 14:32:05 -04:00
Timer::single_shot(Duration::from_secs(1), move || {
main_window.set_disable_tiles(false);
2023-05-03 14:57:56 -04:00
2023-05-03 14:32:05 -04:00
t1.image_visible = false;
t2.image_visible = false;
2023-05-03 14:57:56 -04:00
tiles_model.set_row_data(t1_idx, t1);
2023-05-03 14:32:05 -04:00
tiles_model.set_row_data(t2_idx, t2);
});
}
}
});
2023-05-03 14:10:32 -04:00
2023-05-03 14:57:56 -04:00
main_window.run()?;
Ok(())
2023-05-03 13:54:11 -04:00
}