Skip to content

用代码生成牌面

这一步将游戏牌随机摆放。

代码使用 rand 依赖来实现随机化。使用 cargo 命令将其添加到 Cargo.toml 文件中。

Terminal window
cargo add rand@0.9
bash

将 main 函数修改为以下内容:

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::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.clone().into());
main_window.run().unwrap();
}

代码获取牌列表,将其复制并打乱,通过 Rust 代码访问 memory_tiles 属性。

对于每个顶层属性, Slint 会生成一个 getter 和一个 setter 函数。在本例中为 get_memory_tiles 和 set_memory_tiles。 由于 memory_tiles 是一个 Slint 数组,表示为 Rc<dyn slint::Model>。

你无法更改 Slint 生成的模型,但可以从中提取牌并将它们 放入实现了 Model trait 的 VecModel 中。 VecModel 允许你进行修改,你可以用它来替换静态生成的模型。

运行这段代码会打开一个窗口,现在显示一个 4×4 的矩形网格,当玩家点击它们时 会显示或隐藏图标。

现在还缺少最后一方面内容,即游戏规则。


© 2026 SixtyFPS GmbH