Warning: That file was not part of the compilation database. It may have many parsing errors.

1/****************************************************************************
2**
3** Copyright (C) 2017 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the documentation of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:FDL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Free Documentation License Usage
18** Alternatively, this file may be used under the terms of the GNU Free
19** Documentation License version 1.3 as published by the Free Software
20** Foundation and appearing in the file included in the packaging of
21** this file. Please review the following information to ensure
22** the GNU Free Documentation License version 1.3 requirements
23** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
24** $QT_END_LICENSE$
25**
26****************************************************************************/
27
28/*!
29\page qml-advtutorial.html tutorial
30\title QML Advanced Tutorial
31\brief A more advanced tutorial, showing how to use QML to create a game.
32\nextpage QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks
33
34This tutorial walks step-by-step through the creation of a full application using QML.
35It assumes that you already know the basics of QML (for example, from reading the
36\l{QML Tutorial}{simple tutorial}).
37
38In this tutorial we write a game, \e {Same Game}, based on the Same Game application
39included in the declarative \c examples directory, which looks like this:
40
41\image declarative-samegame.png
42
43We will cover concepts for producing a fully functioning application, including
44JavaScript integration, using QML \l{State}{Qt Quick States} and \l{Behavior}{Behaviors} to
45manage components and enhance your interface, and storing persistent application data.
46
47An understanding of JavaScript is helpful to understand parts of this tutorial, but if you don't
48know JavaScript you can still get a feel for how you can integrate backend logic to create and
49control QML types.
50
51
52Tutorial chapters:
53
54\list 1
55\li \l {QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks}{Creating the Game Canvas and Blocks}
56\li \l {QML Advanced Tutorial 2 - Populating the Game Canvas}{Populating the Game Canvas}
57\li \l {QML Advanced Tutorial 3 - Implementing the Game Logic}{Implementing the Game Logic}
58\li \l {QML Advanced Tutorial 4 - Finishing Touches}{Finishing Touches}
59\endlist
60
61All the code in this tutorial can be found in Qt's \c examples/quick/tutorials/samegame
62directory.
63*/
64
65/*!
66\title QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks
67\contentspage QML Advanced Tutorial
68\previouspage QML Advanced Tutorial
69\nextpage QML Advanced Tutorial 2 - Populating the Game Canvas
70
71\example tutorials/samegame/samegame1
72
73\section2 Creating the Application Screen
74
75The first step is to create the basic QML items in your application.
76
77To begin with, we create our Same Game application with a main screen like this:
78
79\image declarative-adv-tutorial1.png
80
81This is defined by the main application file, \c samegame.qml, which looks like this:
82
83\snippet tutorials/samegame/samegame1/samegame.qml 0
84
85This gives you a basic game window that includes the main canvas for the
86blocks, a "New Game" button and a score display.
87
88One item you may not recognize here
89is the \l SystemPalette item. This provides access to the Qt system palette
90and is used to give the button a more native look-and-feel.
91
92Notice the anchors for the \c Item, \c Button and \c Text types are set using
93group (dot) notation for readability.
94
95\section2 Adding \c Button and \c Block Components
96
97The \c Button item in the code above is defined in a separate component file named \c Button.qml.
98To create a functional button, we use the QML types \l Text and \l MouseArea inside a \l Rectangle.
99Here is the \c Button.qml code:
100
101\snippet tutorials/samegame/samegame1/Button.qml 0
102
103This essentially defines a rectangle that contains text and can be clicked. The \l MouseArea
104has an \c onClicked() handler that is implemented to emit the \c clicked() signal of the
105\c container when the area is clicked.
106
107In Same Game, the screen is filled with small blocks when the game begins.
108Each block is just an item that contains an image. The block
109code is defined in a separate \c Block.qml file:
110
111\snippet tutorials/samegame/samegame1/Block.qml 0
112
113At the moment, the block doesn't do anything; it is just an image. As the
114tutorial progresses we will animate and give behaviors to the blocks.
115We have not added any code yet to create the blocks; we will do this
116in the next chapter.
117
118We have set the image to be the size of its parent Item using \c {anchors.fill: parent}.
119This means that when we dynamically create and resize the block items
120later on in the tutorial, the image will be scaled automatically to the
121correct size.
122
123Notice the relative path for the Image type's \c source property.
124This path is relative to the location of the file that contains the \l Image type.
125Alternatively, you could set the Image source to an absolute file path or a URL
126that contains an image.
127
128You should be familiar with the code so far. We have just created some basic
129types to get started. Next, we will populate the game canvas with some blocks.
130*/
131
132
133/*!
134\title QML Advanced Tutorial 2 - Populating the Game Canvas
135\contentspage QML Advanced Tutorial
136\previouspage QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks
137\nextpage QML Advanced Tutorial 3 - Implementing the Game Logic
138
139\example tutorials/samegame/samegame2
140
141\section2 Generating the Blocks in JavaScript
142
143Now that we've written some types, let's start writing the game.
144
145The first task is to generate the game blocks. Each time the New Game button
146is clicked, the game canvas is populated with a new, random set of
147blocks. Since we need to dynamically generate new blocks for each new game,
148we cannot use \l Repeater to define the blocks. Instead, we will
149create the blocks in JavaScript.
150
151Here is the JavaScript code for generating the blocks, contained in a new
152file, \c samegame.js. The code is explained below.
153
154\snippet tutorials/samegame/samegame2/samegame.js 0
155
156The \c startNewGame() function deletes the blocks created in the previous game and
157calculates the number of rows and columns of blocks required to fill the game window for the new game.
158Then, it creates an array to store all the game
159blocks, and calls \c createBlock() to create enough blocks to fill the game window.
160
161The \c createBlock() function creates a block from the \c Block.qml file
162and moves the new block to its position on the game canvas. This involves several steps:
163
164\list
165
166\li \l {QtQml::Qt::createComponent()}{Qt.createComponent()} is called to
167 generate a type from \c Block.qml. If the component is ready,
168 we can call \c createObject() to create an instance of the \c Block
169 item.
170
171\li If \c createObject() returned null (i.e. if there was an error
172 while loading the object), print the error information.
173
174\li Place the block in its position on the board and set its width and
175 height. Also, store it in the blocks array for future reference.
176
177\li Finally, print error information to the console if the component
178 could not be loaded for some reason (for example, if the file is
179 missing).
180
181\endlist
182
183
184\section2 Connecting JavaScript Components to QML
185
186Now we need to call the JavaScript code in \c samegame.js from our QML files.
187To do this, we add this line to \c samegame.qml which imports
188the JavaScript file as a \l{QML Modules}{module}:
189
190\snippet tutorials/samegame/samegame2/samegame.qml 2
191
192This allows us to refer to any functions within \c samegame.js using "SameGame"
193as a prefix: for example, \c SameGame.startNewGame() or \c SameGame.createBlock().
194This means we can now connect the New Game button's \c onClicked handler to the \c startNewGame()
195function, like this:
196
197\snippet tutorials/samegame/samegame2/samegame.qml 1
198
199So, when you click the New Game button, \c startNewGame() is called and generates a field of blocks, like this:
200
201\image declarative-adv-tutorial2.png
202
203Now, we have a screen of blocks, and we can begin to add the game mechanics.
204
205*/
206
207/*!
208\title QML Advanced Tutorial 3 - Implementing the Game Logic
209\contentspage QML Advanced Tutorial
210\previouspage QML Advanced Tutorial 2 - Populating the Game Canvas
211\nextpage QML Advanced Tutorial 4 - Finishing Touches
212
213\example tutorials/samegame/samegame3
214
215\section2 Making a Playable Game
216
217Now that we have all the game components, we can add the game logic that
218dictates how a player interacts with the blocks and plays the game
219until it is won or lost.
220
221To do this, we have added the following functions to \c samegame.js:
222
223\list
224\li \c{handleClick(x,y)}
225\li \c{floodFill(xIdx,yIdx,type)}
226\li \c{shuffleDown()}
227\li \c{victoryCheck()}
228\li \c{floodMoveCheck(xIdx, yIdx, type)}
229\endlist
230
231As this is a tutorial about QML, not game design, we will only discuss \c handleClick() and \c victoryCheck() below since they interface directly with the QML types. Note that although the game logic here is written in JavaScript, it could have been written in C++ and then exposed to QML.
232
233\section3 Enabling Mouse Click Interaction
234
235To make it easier for the JavaScript code to interface with the QML types, we have added an Item called \c gameCanvas to \c samegame.qml. It replaces the background as the item which contains the blocks. It also accepts mouse input from the user. Here is the item code:
236
237\snippet tutorials/samegame/samegame3/samegame.qml 1
238
239The \c gameCanvas item is the exact size of the board, and has a \c score property and a \l MouseArea to handle mouse clicks.
240The blocks are now created as its children, and its dimensions are used to determine the board size so that
241the application scales to the available screen size.
242Since its size is bound to a multiple of \c blockSize, \c blockSize was moved out of \c samegame.js and into \c samegame.qml as a QML property.
243Note that it can still be accessed from the script.
244
245When clicked, the \l MouseArea calls \c{handleClick()} in \c samegame.js, which determines whether the player's click should cause any blocks to be removed, and updates \c gameCanvas.score with the current score if necessary. Here is the \c handleClick() function:
246
247\snippet tutorials/samegame/samegame3/samegame.js 1
248
249Note that if \c score was a global variable in the \c{samegame.js} file you would not be able to bind to it. You can only bind to QML properties.
250
251\section3 Updating the Score
252
253When the player clicks a block and triggers \c handleClick(), \c handleClick() also calls \c victoryCheck() to update the score and to check whether the player has completed the game. Here is the \c victoryCheck() code:
254
255\snippet tutorials/samegame/samegame3/samegame.js 2
256
257This updates the \c gameCanvas.score value and displays a "Game Over" dialog if the game is finished.
258
259The Game Over dialog is created using a \c Dialog type that is defined in \c Dialog.qml. Here is the \c Dialog.qml code. Notice how it is designed to be usable imperatively from the script file, via the functions and signals:
260
261\snippet tutorials/samegame/samegame3/Dialog.qml 0
262
263And this is how it is used in the main \c samegame.qml file:
264
265\snippet tutorials/samegame/samegame3/samegame.qml 2
266
267We give the dialog a \l {Item::z}{z} value of 100 to ensure it is displayed on top of our other components. The default \c z value for an item is 0.
268
269
270\section3 A Dash of Color
271
272It's not much fun to play Same Game if all the blocks are the same color, so we've modified the \c createBlock() function in \c samegame.js to randomly create a different type of block (for either red, green or blue) each time it is called. \c Block.qml has also changed so that each block contains a different image depending on its type:
273
274\snippet tutorials/samegame/samegame3/Block.qml 0
275
276
277\section2 A Working Game
278
279Now we now have a working game! The blocks can be clicked, the player can score, and the game can end (and then you can start a new one).
280Here is a screenshot of what has been accomplished so far:
281
282\image declarative-adv-tutorial3.png
283
284This is what \c samegame.qml looks like now:
285
286\snippet tutorials/samegame/samegame3/samegame.qml 0
287
288The game works, but it's a little boring right now. Where are the smooth animated transitions? Where are the high scores?
289If you were a QML expert you could have written these in the first iteration, but in this tutorial they've been saved
290until the next chapter - where your application becomes alive!
291
292*/
293
294/*!
295\title QML Advanced Tutorial 4 - Finishing Touches
296\contentspage QML Advanced Tutorial
297\previouspage QML Advanced Tutorial 3 - Implementing the Game Logic
298
299\example tutorials/samegame/samegame4
300
301\section2 Adding Some Flair
302
303Now we're going to do two things to liven up the game: animate the blocks and add a High Score system.
304
305We've also cleaned up the directory structure for our application files. We now have a lot of files, so all the
306JavaScript and QML files outside of \c samegame.qml have been moved into a new sub-directory named "content".
307
308In anticipation of the new block animations, \c Block.qml file is now renamed to \c BoomBlock.qml.
309
310\section3 Animating Block Movement
311
312First we will animate the blocks so that they move in a fluid manner. QML has a number of methods for adding fluid
313movement, and in this case we're going to use the \l Behavior type to add a \l SpringAnimation.
314In \c BoomBlock.qml, we apply a \l SpringAnimation behavior to the \c x and \c y properties so that the
315block will follow and animate its movement in a spring-like fashion towards the specified position (whose
316values will be set by \c samegame.js).Here is the code added to \c BoomBlock.qml:
317
318\snippet tutorials/samegame/samegame4/content/BoomBlock.qml 1
319
320The \c spring and \c damping values can be changed to modify the spring-like effect of the animation.
321
322The \c {enabled: spawned} setting refers to the \c spawned value that is set from \c createBlock() in \c samegame.js.
323This ensures the \l SpringAnimation on the \c x is only enabled after \c createBlock() has set the block to
324the correct position. Otherwise, the blocks will slide out of the corner (0,0) when a game begins, instead of falling
325from the top in rows. (Try commenting out \c {enabled: spawned} and see for yourself.)
326
327\section3 Animating Block Opacity Changes
328
329Next, we will add a smooth exit animation. For this, we'll use a \l Behavior type, which allows us to specify
330a default animation when a property change occurs. In this case, when the \c opacity of a Block changes, we will
331animate the opacity value so that it gradually fades in and out, instead of abruptly changing between fully
332visible and invisible. To do this, we'll apply a \l Behavior on the \c opacity property of the \c Image
333type in \c BoomBlock.qml:
334
335\snippet tutorials/samegame/samegame4/content/BoomBlock.qml 2
336
337Note the \c{opacity: 0} which means the block is transparent when it is first created. We could set the opacity
338in \c samegame.js when we create and destroy the blocks,
339but instead we'll use \l{Qt Quick States}{states}, since this is useful for the next animation we're going to add.
340Initially, we add these States to the root type of \c{BoomBlock.qml}:
341\code
342 property bool dying: false
343 states: [
344 State{ name: "AliveState"; when: spawned == true && dying == false
345 PropertyChanges { target: img; opacity: 1 }
346 },
347 State{ name: "DeathState"; when: dying == true
348 PropertyChanges { target: img; opacity: 0 }
349 }
350 ]
351\endcode
352
353Now blocks will automatically fade in, as we already set \c spawned to true when we implemented the block animations.
354To fade out, we set \c dying to true instead of setting opacity to 0 when a block is destroyed (in the \c floodFill() function).
355
356\section3 Adding Particle Effects
357
358Finally, we'll add a cool-looking particle effect to the blocks when they are destroyed. To do this, we first add a \l ParticleSystem in
359\c BoomBlock.qml, like so:
360
361\snippet tutorials/samegame/samegame4/content/BoomBlock.qml 3
362
363To fully understand this you should read \l {Using the Qt Quick Particle System}, but it's important to note that \c emitRate is set
364to zero so that particles are not emitted normally.
365Also, we extend the \c dying State, which creates a burst of particles by calling the \c burst() method on the particles type. The code for the states now look
366like this:
367
368\snippet tutorials/samegame/samegame4/content/BoomBlock.qml 4
369
370Now the game is beautifully animated, with subtle (or not-so-subtle) animations added for all of the
371player's actions. The end result is shown below, with a different set of images to demonstrate basic theming:
372
373\image declarative-adv-tutorial4.gif
374
375The theme change here is produced simply by replacing the block images. This can be done at runtime by changing the \l Image \c source property, so for a further challenge, you could add a button that toggles between themes with different images.
376
377\section2 Keeping a High Scores Table
378
379Another feature we might want to add to the game is a method of storing and retrieving high scores.
380
381To do this, we will show a dialog when the game is over to request the player's name and add it to a High Scores table.
382This requires a few changes to \c Dialog.qml. In addition to a \c Text type, it now has a
383\c TextInput child item for receiving keyboard text input:
384
385\snippet tutorials/samegame/samegame4/content/Dialog.qml 0
386\dots 4
387\snippet tutorials/samegame/samegame4/content/Dialog.qml 2
388\dots 4
389\snippet tutorials/samegame/samegame4/content/Dialog.qml 3
390
391We'll also add a \c showWithInput() function. The text input will only be visible if this function
392is called instead of \c show(). When the dialog is closed, it emits a \c closed() signal, and
393other types can retrieve the text entered by the user through an \c inputText property:
394
395\snippet tutorials/samegame/samegame4/content/Dialog.qml 0
396\snippet tutorials/samegame/samegame4/content/Dialog.qml 1
397\dots 4
398\snippet tutorials/samegame/samegame4/content/Dialog.qml 3
399
400Now the dialog can be used in \c samegame.qml:
401
402\snippet tutorials/samegame/samegame4/samegame.qml 0
403
404When the dialog emits the \c closed signal, we call the new \c saveHighScore() function in \c samegame.js, which stores the high score locally in an SQL database and also send the score to an online database if possible.
405
406The \c nameInputDialog is activated in the \c victoryCheck() function in \c samegame.js:
407
408\snippet tutorials/samegame/samegame4/content/samegame.js 3
409\dots 4
410\snippet tutorials/samegame/samegame4/content/samegame.js 4
411
412\section3 Storing High Scores Offline
413
414Now we need to implement the functionality to actually save the High Scores table.
415
416Here is the \c saveHighScore() function in \c samegame.js:
417
418\snippet tutorials/samegame/samegame4/content/samegame.js 2
419
420First we call \c sendHighScore() (explained in the section below) if it is possible to send the high scores to an online database.
421
422Then, we use the \l{QtQuick.LocalStorage}{Local Storage API} to maintain a persistent SQL database unique to this application. We create an offline storage database for the high scores using \c openDatabaseSync() and prepare the data and SQL query that we want to use to save it. The offline storage API uses SQL queries for data manipulation and retrieval, and in the \c db.transaction() call we use three SQL queries to initialize the database (if necessary), and then add to and retrieve high scores. To use the returned data, we turn it into a string with one line per row returned, and show a dialog containing that string.
423
424This is one way of storing and displaying high scores locally, but certainly not the only way. A more complex alternative would be to create a high score dialog component, and pass it the results for processing and display (instead of reusing the \c Dialog). This would allow a more themeable dialog that could better present the high scores. If your QML is the UI for a C++ application, you could also have passed the score to a C++ function to store it locally in a variety of ways, including a simple format without SQL or in another SQL database.
425
426\section3 Storing High Scores Online
427
428You've seen how you can store high scores locally, but it is also easy to integrate a web-enabled high score storage into your QML application. The implementation we've done her is very
429simple: the high score data is posted to a php script running on a server somewhere, and that server then stores it and
430displays it to visitors. You could also request an XML or QML file from that same server, which contains and displays the scores,
431but that's beyond the scope of this tutorial. The php script we use here is available in the \c examples directory.
432
433If the player entered their name we can send the data to the web service us
434
435If the player enters a name, we send the data to the service using this code in \c samegame.js:
436
437\snippet tutorials/samegame/samegame4/content/samegame.js 1
438
439The \l XMLHttpRequest in this code is the same as the \c XMLHttpRequest() as you'll find in standard browser JavaScript, and can be used in the same way to dynamically get XML
440or QML from the web service to display the high scores. We don't worry about the response in this case - we just post the high
441score data to the web server. If it had returned a QML file (or a URL to a QML file) you could instantiate it in much the same
442way as you did with the blocks.
443
444An alternate way to access and submit web-based data would be to use QML types designed for this purpose. XmlListModel
445makes it very easy to fetch and display XML based data such as RSS in a QML application (see the Flickr demo for an example).
446
447
448\section2 That's It!
449
450By following this tutorial you've seen how you can write a fully functional application in QML:
451
452\list
453\li Build your application with \l {Qt Quick QML Types}{QML types}
454\li Add application logic \l{JavaScript Expressions in QML Documents}{with JavaScript code}
455\li Add animations with \l {Behavior}{Behaviors} and \l{Qt Quick States}{states}
456\li Store persistent application data using, for example, \l QtQuick.LocalStorage or \l XMLHttpRequest
457\endlist
458
459There is so much more to learn about QML that we haven't been able to cover in this tutorial. Check out all the
460examples and the \l {Qt Quick}{documentation} to see all the things you can do with QML!
461*/
462

Warning: That file was not part of the compilation database. It may have many parsing errors.