Creating The Tiles From JavaScript
What we'll do is take the list of tiles declared in the .slint language, duplicate it, and shuffle it.
We'll do so by accessing the memory_tiles
property through the JavaScript code - in our case memory_tiles
.
Since memory_tiles
is an array in the .slint
language, it's represented as a JavaScript Array
.
We can't modify the model generated by the .slint, but we can extract the tiles from it, and put it
in a slint.ArrayModel
which implements the Model
interface.
ArrayModel
allows us to make modifications and we can use it to replace the static generated model.
We modify the main function like so:
// main.js
let slint = require("slint-ui");
let ui = require("./memory.slint");
let mainWindow = new ui.MainWindow();
let initial_tiles = mainWindow.memory_tiles;
let tiles = initial_tiles.concat(initial_tiles.map((tile) => Object.assign({}, tile)));
for (let i = tiles.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * i);
[tiles[i], tiles[j]] = [tiles[j], tiles[i]];
}
let model = new slint.ArrayModel(tiles);
mainWindow.memory_tiles = model;
mainWindow.run();
Running this gives us a window on the screen that now shows a 4 by 4 grid of rectangles, which can show or obscure the icons when clicking. There's only one last aspect missing now, the rules for the game.