Creating The Tiles From Rust

This step places the game tiles randomly. The code uses the rand dependency for the randomization. Add it to the Cargo.toml file using the cargo command.

cargo add rand@0.8

Change the main function to the following:

fn main() {
    use slint::Model;

    let main_window = MainWindow::new().unwrap();

    // Fetch the tiles from the model
    let mut tiles: Vec<TileData> = main_window.get_memory_tiles().iter().collect();
    // Duplicate them to ensure that we have pairs
    tiles.extend(tiles.clone());

    // Randomly mix the tiles
    use rand::seq::SliceRandom;
    let mut rng = rand::thread_rng();
    tiles.shuffle(&mut rng);

    // Assign the shuffled Vec to the model property
    let tiles_model = std::rc::Rc::new(slint::VecModel::from(tiles));
    main_window.set_memory_tiles(tiles_model.into());

    main_window.run().unwrap();
}

The code takes the list of tiles, duplicates it, and shuffles it, accessing the memory_tiles property through the Rust code.

For each top-level property, Slint generates a getter and a setter function. In this case get_memory_tiles and set_memory_tiles. Since memory_tiles is a Slint array represented as a Rc<dyn slint::Model>.

You can't change the model generated by Slint, but you can extract the tiles from it and put them in a VecModel which implements the Model trait. VecModel lets you make changes and you can use it to replace the static generated model.

The code clones the tiles_model because you use it later to update the game logic.

Running this code opens a window that now shows a 4 by 4 grid of rectangles, which show or hide the icons when a player clicks on them.

There's one last aspect missing now, the rules for the game.