From One To Multiple Tiles
After modeling a single tile, this step creates a grid of them. For the grid to be a game board, you need two features:
-
A data model: An array created as a model in code, where each element describes the tile data structure, such as:
- URL of the image
- Whether the image is visible
- If the player has solved this tile.
-
A way of creating multiple instances of the tiles.
With Slint you declare an array of structures based on a model using square brackets. Use a for loop to create multiple instances of the same element.
The for loop is declarative and automatically updates when the model changes. The loop instantiates all the MemoryTile elements and places them on a grid based on their index with spacing between the tiles.
First, add the tile data structure definition at the top of the ui/app-window.slint
file:
Next, replace the _export component MainWindow inherits Window { … } section at the bottom of the ui/app-window.slint
file with the following:
The for tile[i] in memory_tiles:
syntax declares a variable tile
which contains the data of one element from the memory_tiles
array,
and a variable i
which is the index of the tile. The code uses the i
index to calculate the position of a tile, based on its row and column,
using modulo and integer division to create a 4 by 4 grid.
Running the code opens a window that shows 8 tiles, which a player can open individually.