~ubuntu-branches/ubuntu/natty/pyside/natty-proposed

« back to all changes in this revision

Viewing changes to doc/tutorials/qmladvancedtutorial/samegame4.rst

  • Committer: Bazaar Package Importer
  • Author(s): Didier Raboud
  • Date: 2011-04-01 15:21:05 UTC
  • mfrom: (1.2.4 upstream) (6.2.3 sid)
  • Revision ID: james.westby@ubuntu.com-20110401152105-perr3fu2o9fja5rd
Tags: 1.0.1-1
* New 1.0.1 upstream release
  - Bump the B-D chain versions:
    + generatorrunner to 0.6.8.
    + shiboken to 1.0.1.
 
* Move phonon-backend-gstreamer B-D earlier in the list to help the
  aptitude-based resolver (thanks to the pkg-kde team for the help!)
* Use dh_python2, hence get the debug files at the correct place.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
.. _samegame4:
 
2
 
 
3
QML Advanced Tutorial 4 - Finishing Touches
 
4
*******************************************
 
5
 
 
6
Adding some flair
 
7
=================
 
8
 
 
9
Now we're going to do two things to liven up the game: animate the blocks and add a High Score system.
 
10
 
 
11
We've also cleaned up the directory structure for our application files. We now have a lot of files, so all the
 
12
JavaScript and QML files outside of ``samegame.qml`` have been moved into a new sub-directory named "content".
 
13
 
 
14
In anticipation of the new block animations, ``Block.qml`` file is now renamed to ``BoomBlock.qml``.
 
15
 
 
16
Animating block movement
 
17
------------------------
 
18
 
 
19
First we will animate the blocks so that they move in a fluid manner. QML has a number of methods for adding fluid
 
20
movement, and in this case we're going to use the Behavior element to add a SpringAnimation.
 
21
In ``BoomBlock.qml``, we apply a SpringAnimation behavior to the ``x`` and ``y`` properties so that the
 
22
block will follow and animate its movement in a spring-like fashion towards the specified position (whose
 
23
values will be set by ``samegame.js``).Here is the code added to ``BoomBlock.qml``:
 
24
 
 
25
.. pysideinclude:: samegame/samegame4/content/BoomBlock.qml
 
26
    :snippet: 1
 
27
 
 
28
The ``spring`` and ``damping`` values can be changed to modify the spring-like effect of the animation.
 
29
 
 
30
The ``enabled: spawned`` setting refers to the ``spawned`` value that is set from ``createBlock()`` in ``samegame.js``.
 
31
This ensures the SpringAnimation on the ``x`` is only enabled after ``createBlock()`` has set the block to
 
32
the correct position. Otherwise, the blocks will slide out of the corner (0,0) when a game begins, instead of falling
 
33
from the top in rows. (Try commenting out ``enabled: spawned`` and see for yourself.)
 
34
 
 
35
Animating block opacity changes
 
36
-------------------------------
 
37
 
 
38
Next, we will add a smooth exit animation. For this, we'll use a Behavior element, which allows us to specify
 
39
a default animation when a property change occurs. In this case, when the ``opacity`` of a Block changes, we will
 
40
animate the opacity value so that it gradually fades in and out, instead of abruptly changing between fully
 
41
visible and invisible. To do this, we'll apply a Behavior on the ``opacity`` property of the ``Image``
 
42
element in ``BoomBlock.qml``:
 
43
 
 
44
.. pysideinclude:: samegame/samegame4/content/BoomBlock.qml
 
45
    :snippet: 2
 
46
 
 
47
Note the ``opacity: 0`` which means the block is transparent when it is first created. We could set the opacity
 
48
in ``samegame.js`` when we create and destroy the blocks,
 
49
but instead we'll use states, since this is useful for the next animation we're going to add.
 
50
Initially, we add these States to the root element of ``BoomBlock.qml``:
 
51
 
 
52
::
 
53
 
 
54
    property bool dying: false
 
55
    states: [
 
56
        State{ name: "AliveState"; when: spawned == true && dying == false
 
57
            PropertyChanges { target: img; opacity: 1 }
 
58
        },
 
59
        State{ name: "DeathState"; when: dying == true
 
60
            PropertyChanges { target: img; opacity: 0 }
 
61
        }
 
62
    ]
 
63
 
 
64
Now blocks will automatically fade in, as we already set ``spawned`` to true when we implemented the block animations.
 
65
To fade out, we set ``dying`` to true instead of setting opacity to 0 when a block is destroyed (in the ``floodFill()`` function).
 
66
 
 
67
Adding particle effects
 
68
-----------------------
 
69
 
 
70
Finally, we'll add a cool-looking particle effect to the blocks when they are destroyed. To do this, we first add a Particles element in
 
71
``BoomBlock.qml``, like so:
 
72
 
 
73
.. pysideinclude:: samegame/samegame4/content/BoomBlock.qml
 
74
    :snippet: 3
 
75
 
 
76
To fully understand this you should read the Particles documentation, but it's important to note that ``emissionRate`` is set
 
77
to zero so that particles are not emitted normally.
 
78
Also, we extend the ``dying`` State, which creates a burst of particles by calling the ``burst()`` method on the particles element. The code for the states now look
 
79
like this:
 
80
 
 
81
.. pysideinclude:: samegame/samegame4/content/BoomBlock.qml
 
82
    :snippet: 4
 
83
 
 
84
Now the game is beautifully animated, with subtle (or not-so-subtle) animations added for all of the
 
85
player's actions. The end result is shown below, with a different set of images to demonstrate basic theming:
 
86
 
 
87
.. figure:: declarative-adv-tutorial4.gif
 
88
    :align: center
 
89
 
 
90
The 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.
 
91
 
 
92
Keeping a High Scores table
 
93
===========================
 
94
 
 
95
Another feature we might want to add to the game is a method of storing and retrieving high scores.
 
96
 
 
97
To 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.
 
98
This requires a few changes to ``Dialog.qml``. In addition to a ``Text`` element, it now has a
 
99
``TextInput`` child item for receiving keyboard text input:
 
100
 
 
101
.. pysideinclude:: samegame/samegame4/content/Dialog.qml
 
102
    :snippet: 2
 
103
    :prepend: Rectangle {
 
104
              ...
 
105
    :append: ...
 
106
             }
 
107
 
 
108
 
 
109
We'll also add a ``showWithInput()`` function. The text input will only be visible if this function
 
110
is called instead of ``show()``. When the dialog is closed, it emits a ``closed()`` signal, and
 
111
other elements can retrieve the text entered by the user through an ``inputText`` property:
 
112
 
 
113
.. pysideinclude:: samegame/samegame4/content/Dialog.qml
 
114
    :snippet: 1
 
115
    :prepend: Rectangle {
 
116
              ...
 
117
    :append: ...
 
118
             }
 
119
 
 
120
Now the dialog can be used in ``samegame.qml``:
 
121
 
 
122
.. pysideinclude:: samegame/samegame4/samegame.qml
 
123
    :snippet: 0
 
124
 
 
125
When the dialog emits the ``closed`` signal, we call the new ``saveHighScore()`` function in ``samegame.js``, which stores the high score locally in an SQL database and also send the score to an online database if possible.
 
126
 
 
127
The ``nameInputDialog`` is activated in the ``victoryCheck()`` function in ``samegame.js``:
 
128
 
 
129
.. pysideinclude:: samegame/samegame4/content/samegame.js
 
130
    :snippet: 4
 
131
    :prepend: function vitoryCheck() {
 
132
              ...
 
133
 
 
134
Storing high scores offline
 
135
---------------------------
 
136
 
 
137
Now we need to implement the functionality to actually save the High Scores table.
 
138
 
 
139
Here is the ``saveHighScore()`` function in ``samegame.js``:
 
140
 
 
141
.. pysideinclude:: samegame/samegame4/content/samegame.js
 
142
    :snippet: 2
 
143
 
 
144
First we call ``sendHighScore()`` (explained in the section below) if it is possible to send the high scores to an online database.
 
145
 
 
146
Then, we use the Offline Storage API to maintain a persistant SQL database unique to this application. We create an offline storage database for the high scores using ``openDatabase()`` 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 retrival, and in the ``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.
 
147
 
 
148
This 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 ``Dialog``). This would allow a more themeable dialog that could beter present the high scores. If your QML is the UI for a Python application, you could also have passed the score to a Python function to store it locally in a variety of ways, including a simple format without SQL or in another SQL database.
 
149
 
 
150
Storing high scores online
 
151
--------------------------
 
152
 
 
153
You'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 here is very
 
154
simple: the high score data is posted to a php script running on a server somewhere, and that server then stores it and
 
155
displays it to visitors. You could also request an XML or QML file from that same server, which contains and displays the scores,
 
156
but that's beyond the scope of this tutorial. The php script we use here is available in the ``examples`` directory.
 
157
 
 
158
If the player entered their name we can send the data to the web service us
 
159
 
 
160
If the player enters a name, we send the data to the service using this code in ``samegame.js``:
 
161
 
 
162
.. pysideinclude:: samegame/samegame4/content/samegame.js
 
163
    :snippet: 1
 
164
 
 
165
The XMLHttpRequest in this code is the same as the ``XMLHttpRequest()`` as you'll find in standard browser JavaScript, and can be used in the same way to dynamically get XML
 
166
or 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
 
167
score 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
 
168
way as you did with the blocks.
 
169
 
 
170
An alternate way to access and submit web-based data would be to use QML elements designed for this purpose. XmlListModel
 
171
makes it very easy to fetch and display XML based data such as RSS in a QML application (see the Flickr demo for an example).
 
172
 
 
173
 
 
174
That's it!
 
175
==========
 
176
 
 
177
By following this tutorial you've seen how you can write a fully functional application in QML:
 
178
 
 
179
* Build your application with QML elements.
 
180
* Add application logic with JavaScript code.
 
181
* Add animations with Behaviors and states.
 
182
* Store persistent application data using, for example, the Offline Storage API or XMLHttpRequest.
 
183
 
 
184
There is so much more to learn about QML that we haven't been able to cover in this tutorial. Check out all the
 
185
demos and examples and the documentation to see all the things you can do with QML!
 
186
 
 
187
[Previous :ref:`samegame3`]
 
 
b'\\ No newline at end of file'