PySide QML Tutorial Advanced 4: Difference between revisions
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
[[Category:LanguageBindings::PySide]] | |||
==Adding some flair== | = PySide QML Advanced Tutorial 4: Finishing Touches = | ||
== Adding some flair == | |||
Now we’re going to do two things to liven up the game: animate the blocks and add a High Score system. | Now we’re going to do two things to liven up the game: animate the blocks and add a High Score system. | ||
We’ve also cleaned up the directory structure for our application files. We now have a lot of files, so all the JavaScript and | We’ve also cleaned up the directory structure for our application files. We now have a lot of files, so all the JavaScript and QML files outside of ''samegame.qml'' have been moved into a new sub-directory named “content”. | ||
In anticipation of the new block animations, ''Block.qml'' file is now renamed to ''BoomBlock.qml''. | In anticipation of the new block animations, ''Block.qml'' file is now renamed to ''BoomBlock.qml''. | ||
==Animating block movement== | == Animating block movement == | ||
First we will animate the blocks so that they move in a fluid manner. QML has a number of methods for adding fluid movement, and in this case we’re going to use the Behavior element to add a SpringAnimation. In BoomBlock.qml, we apply a SpringAnimation behavior to the x and y properties so that the block will follow and animate its movement in a spring-like fashion towards the specified position (whose values will be set by ''samegame.js''). Here is the code added to ''BoomBlock.qml'': | |||
<code><br /> property bool spawned: false | |||
Behavior on x {<br /> enabled: spawned;<br /> SpringAnimation{ spring: 2; damping: 0.2 }<br /> }<br /> Behavior on y {<br /> SpringAnimation{ spring: 2; damping: 0.2 }<br /> }<br /></code> | |||
The ''spring'' and ''damping'' values can be changed to modify the spring-like effect of the animation. | The ''spring'' and ''damping'' values can be changed to modify the spring-like effect of the animation. | ||
Line 17: | Line 23: | ||
The enabled: spawned setting refers to the spawned value that is set from ''createBlock()'' in ''samegame.js''. This ensures the ''SpringAnimation'' on the x is only enabled after ''createBlock()'' has set the block to the correct position. Otherwise, the blocks will slide out of the corner (0,0) when a game begins, instead of falling from the top in rows. (Try commenting out ''enabled: spawned'' and see for yourself.) | The enabled: spawned setting refers to the spawned value that is set from ''createBlock()'' in ''samegame.js''. This ensures the ''SpringAnimation'' on the x is only enabled after ''createBlock()'' has set the block to the correct position. Otherwise, the blocks will slide out of the corner (0,0) when a game begins, instead of falling from the top in rows. (Try commenting out ''enabled: spawned'' and see for yourself.) | ||
==Animating block opacity changes== | == Animating block opacity changes == | ||
Next, we will add a smooth exit animation. For this, we’ll use a Behavior element, which allows us to specify a default animation when a property change occurs. In this case, when the ''opacity'' of a Block changes, we will animate the opacity value so that it gradually fades in and out, instead of abruptly changing between fully visible and invisible. To do this, we’ll apply a Behavior on the ''opacity'' property of the ''Image'' element in ''BoomBlock.qml'': | Next, we will add a smooth exit animation. For this, we’ll use a Behavior element, which allows us to specify a default animation when a property change occurs. In this case, when the ''opacity'' of a Block changes, we will animate the opacity value so that it gradually fades in and out, instead of abruptly changing between fully visible and invisible. To do this, we’ll apply a Behavior on the ''opacity'' property of the ''Image'' element in ''BoomBlock.qml'': | ||
<code><br /> Image {<br /> id: img | |||
anchors.fill: parent<br /> source: {<br /> if (type 0) | |||
return &quot;../../shared/pics/redStone.png&quot;; | |||
else if (type 1)<br /> return "../../shared/pics/blueStone.png&quot;;<br /> else<br /> return "../../shared/pics/greenStone.png&quot;;<br /> }<br /> opacity: 0 | |||
Behavior on opacity {<br /> NumberAnimation { properties:"opacity&quot;; duration: 200 }<br /> }<br /> }<br /></code> | |||
Note the ''opacity: 0'' which means the block is transparent when it is first created. We could set the opacity in ''samegame.js'' when we create and destroy the blocks, but instead we’ll use states, since this is useful for the next animation we’re going to add. Initially, we add these States to the root element of ''BoomBlock.qml'': | Note the ''opacity: 0'' which means the block is transparent when it is first created. We could set the opacity in ''samegame.js'' when we create and destroy the blocks, but instead we’ll use states, since this is useful for the next animation we’re going to add. Initially, we add these States to the root element of ''BoomBlock.qml'': | ||
<code><br />property bool dying: false<br />states: [<br /> State{ name: "AliveState&quot;; when: spawned true &amp;&amp; dying false<br /> PropertyChanges { target: img; opacity: 1 }<br /> },<br /> State{ name: "DeathState&quot;; when: dying == true<br /> PropertyChanges { target: img; opacity: 0 }<br /> }<br />]<br /></code> | |||
Now blocks will automatically fade in, as we already set ''spawned'' to true when we implemented the block animations. To fade out, we set ''dying'' to true instead of setting opacity to 0 when a block is destroyed (in the ''floodFill()'' function). | Now blocks will automatically fade in, as we already set ''spawned'' to true when we implemented the block animations. To fade out, we set ''dying'' to true instead of setting opacity to 0 when a block is destroyed (in the ''floodFill()'' function). | ||
===Adding particle effects=== | === Adding particle effects === | ||
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 ''BoomBlock.qml'', like so: | 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 ''BoomBlock.qml'', like so: | ||
<code><br /> Particles {<br /> id: particles | |||
width: 1; height: 1<br /> anchors.centerIn: parent | |||
emissionRate: 0<br /> lifeSpan: 700; lifeSpanDeviation: 600<br /> angle: 0; angleDeviation: 360;<br /> velocity: 100; velocityDeviation: 30<br /> source: {<br /> if (type 0) | |||
return &quot;../../shared/pics/redStar.png&quot;; | |||
else if (type 1)<br /> return "../../shared/pics/blueStar.png&quot;;<br /> else<br /> return "../../shared/pics/greenStar.png&quot;;<br /> }<br /> }<br /></code> | |||
To fully understand this you should read the Particles documentation, but it’s important to note that ''emissionRate'' is set to zero so that particles are not emitted normally. 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 like this: | To fully understand this you should read the Particles documentation, but it’s important to note that ''emissionRate'' is set to zero so that particles are not emitted normally. 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 like this: | ||
<code><br /> states: [<br /> State {<br /> name: "AliveState&quot;<br /> when: spawned true &amp;&amp; dying false<br /> PropertyChanges { target: img; opacity: 1 }<br /> }, | |||
State {<br /> name: "DeathState&quot;<br /> when: dying == true<br /> StateChangeScript { script: particles.burst(50); }<br /> PropertyChanges { target: img; opacity: 0 }<br /> StateChangeScript { script: block.destroy(1000); }<br /> }<br /> ]<br /></code> | |||
Now the game is beautifully animated, with subtle (or not-so-subtle) animations added for all of the player’s actions. The end result is shown below, with a different set of images to demonstrate basic theming: | Now the game is beautifully animated, with subtle (or not-so-subtle) animations added for all of the player’s actions. The end result is shown below, with a different set of images to demonstrate basic theming: | ||
Line 35: | Line 63: | ||
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. | 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. | ||
==Keeping a High Scores table== | == Keeping a High Scores table == | ||
Another feature we might want to add to the game is a method of storing and retrieving high scores. | Another feature we might want to add to the game is a method of storing and retrieving high scores. | ||
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. This requires a few changes to ''Dialog.qml''. In addition to a Text element, it now has a ''TextInput'' child item for receiving keyboard text input: | 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. This requires a few changes to ''Dialog.qml''. In addition to a Text element, it now has a ''TextInput'' child item for receiving keyboard text input: | ||
<code><br />Rectangle {<br />…<br /> TextInput {<br /> id: textInput<br /> anchors { verticalCenter: parent.verticalCenter; left: dialogText.right }<br /> width: 80<br /> text: "" | |||
onAccepted: container.hide() // close dialog when Enter is pressed<br /> }<br />…<br />}<br /></code> | |||
We’ll also add a ''showWithInput()'' function. The text input will only be visible if this function is called instead of ''show()''. When the dialog is closed, it emits a ''closed()'' signal, and other elements can retrieve the text entered by the user through an ''inputText'' property: | We’ll also add a ''showWithInput()'' function. The text input will only be visible if this function is called instead of ''show()''. When the dialog is closed, it emits a ''closed()'' signal, and other elements can retrieve the text entered by the user through an ''inputText'' property: | ||
<code><br />Rectangle {<br />…<br /> property string inputText: textInput.text<br /> signal closed | |||
function show(text) {<br /> dialogText.text = text;<br /> container.opacity = 1;<br /> textInput.opacity = 0;<br /> } | |||
function showWithInput(text) {<br /> show(text);<br /> textInput.opacity = 1;<br /> textInput.focus = true;<br /> textInput.text = ""<br /> } | |||
function hide() {<br /> textInput.focus = false;<br /> container.opacity = 0;<br /> container.closed();<br /> }<br />…<br />}<br /></code> | |||
Now the dialog can be used in ''samegame.qml'': | Now the dialog can be used in ''samegame.qml'': | ||
When the dialog emits the ''closed'' signal, we call the new ''saveHighScore()'' function in ''samegame.js'', which stores the high score locally in an | <code><br /> Dialog {<br /> id: nameInputDialog<br /> anchors.centerIn: parent<br /> z: 100 | ||
onClosed: {<br /> if (nameInputDialog.inputText != "")<br /> SameGame.saveHighScore(nameInputDialog.inputText);<br /> }<br /> }<br /></code> | |||
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. | |||
The nameInputDialog is activated in the ''victoryCheck()'' function in ''samegame.js'': | The nameInputDialog is activated in the ''victoryCheck()'' function in ''samegame.js'': | ||
===Storing high scores offline=== | <code><br />function vitoryCheck() {<br />…<br /> //Check whether game has finished<br /> if (deservesBonus || !(floodMoveCheck(0, maxRow - 1, <s>1))) {<br /> gameDuration = new Date()</s> gameDuration;<br /> nameInputDialog.showWithInput("You won! Please enter your name: ");<br /> }<br />}<br /></code> | ||
=== Storing high scores offline === | |||
Now we need to implement the functionality to actually save the High Scores table. | Now we need to implement the functionality to actually save the High Scores table. | ||
Here is the ''saveHighScore()'' function in ''samegame.js'': | Here is the ''saveHighScore()'' function in ''samegame.js'': | ||
<code><br />function saveHighScore(name) {<br /> if (scoresURL != "")<br /> sendHighScore(name); | |||
var db = openDatabaseSync("SameGameScores&quot;, "1.0&quot;, "Local SameGame High Scores&quot;, 100);<br /> var dataStr = "INSERT INTO Scores VALUES (?, ?, ?, ?)";<br /> var data = [name, gameCanvas.score, maxColumn + "x&quot; + maxRow, Math.floor(gameDuration / 1000)];<br /> db.transaction(function(tx) {<br /> tx.executeSql('CREATE TABLE IF NOT EXISTS Scores(name TEXT, score NUMBER, gridSize TEXT, time NUMBER)');<br /> tx.executeSql(dataStr, data); | |||
var rs = tx.executeSql('SELECT * FROM Scores WHERE gridSize = "12x17&quot; ORDER BY score desc LIMIT 10');<br /> var r = "SCORES for a standard sized grid\n\n&quot;<br /> for (var i = 0; i < rs.rows.length; i+'') {<br /> r''= (i + 1) + ". " + rs.rows.item(i).name + ' got ' + rs.rows.item(i).score + ' points in ' + rs.rows.item(i).time + ' seconds.';<br /> }<br /> dialog.show®;<br /> });<br />}<br /></code> | |||
First we call ''sendHighScore()'' (explained in the section below) if it is possible to send the high scores to an online database. | First we call ''sendHighScore()'' (explained in the section below) if it is possible to send the high scores to an online database. | ||
Then, we use the Offline Storage | 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. | ||
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 | 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. | ||
===Storing high scores online=== | === Storing high scores online === | ||
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 | 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 simple: the high score data is posted to a php script running on a server somewhere, and that server then stores it and displays it to visitors. You could also request an XML or QML file from that same server, which contains and displays the scores, but that’s beyond the scope of this tutorial. The php script we use here is available in the examples directory. | ||
If the player entered their name we can send the data to the web service us | If the player entered their name we can send the data to the web service us | ||
Line 69: | Line 121: | ||
If the player enters a name, we send the data to the service using this code in ''samegame.js'': | If the player enters a name, we send the data to the service using this code in ''samegame.js'': | ||
<code><br />function sendHighScore(name) {<br /> var postman = new XMLHttpRequest()<br /> var postData = "name=" + name + "&score=" + gameCanvas.score + "&gridSize=" + maxColumn + "x&quot; + maxRow + "&time=" + Math.floor(gameDuration / 1000);<br /> postman.open("POST&quot;, scoresURL, true);<br /> postman.setRequestHeader("Content-Type&quot;, "application/x-www-form-urlencoded&quot;);<br /> postman.onreadystatechange = function() {<br /> if (postman.readyState == postman.DONE) {<br /> dialog.show("Your score has been uploaded.");<br /> }<br /> }<br /> postman.send(postData);<br />}<br /></code> | |||
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 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 score data to the web server. If it had returned a QML file &#40;or a URL to a QML file&amp;#41; you could instantiate it in much the same way as you did with the blocks. | |||
An alternate way to access and submit web-based data would be to use QML elements designed for this purpose. XmlListModel 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). | |||
= That’s it! = | |||
* Build your application with | By following this tutorial you’ve seen how you can write a fully functional application in QML: | ||
* Build your application with QML elements. | |||
* Add application logic with JavaScript code. | * Add application logic with JavaScript code. | ||
* Add animations with Behaviors and states. | * Add animations with Behaviors and states. | ||
* Store persistent application data using, for example, the Offline Storage | * Store persistent application data using, for example, the Offline Storage API or XMLHttpRequest. | ||
Revision as of 10:03, 24 February 2015
PySide QML Advanced Tutorial 4: Finishing Touches
Adding some flair
Now we’re going to do two things to liven up the game: animate the blocks and add a High Score system.
We’ve also cleaned up the directory structure for our application files. We now have a lot of files, so all the JavaScript and QML files outside of samegame.qml have been moved into a new sub-directory named “content”.
In anticipation of the new block animations, Block.qml file is now renamed to BoomBlock.qml.
Animating block movement
First we will animate the blocks so that they move in a fluid manner. QML has a number of methods for adding fluid movement, and in this case we’re going to use the Behavior element to add a SpringAnimation. In BoomBlock.qml, we apply a SpringAnimation behavior to the x and y properties so that the block will follow and animate its movement in a spring-like fashion towards the specified position (whose values will be set by samegame.js). Here is the code added to BoomBlock.qml:
<br /> property bool spawned: false
Behavior on x {<br /> enabled: spawned;<br /> SpringAnimation{ spring: 2; damping: 0.2 }<br /> }<br /> Behavior on y {<br /> SpringAnimation{ spring: 2; damping: 0.2 }<br /> }<br />
The spring and damping values can be changed to modify the spring-like effect of the animation.
The enabled: spawned setting refers to the spawned value that is set from createBlock() in samegame.js. This ensures the SpringAnimation on the x is only enabled after createBlock() has set the block to the correct position. Otherwise, the blocks will slide out of the corner (0,0) when a game begins, instead of falling from the top in rows. (Try commenting out enabled: spawned and see for yourself.)
Animating block opacity changes
Next, we will add a smooth exit animation. For this, we’ll use a Behavior element, which allows us to specify a default animation when a property change occurs. In this case, when the opacity of a Block changes, we will animate the opacity value so that it gradually fades in and out, instead of abruptly changing between fully visible and invisible. To do this, we’ll apply a Behavior on the opacity property of the Image element in BoomBlock.qml:
<br /> Image {<br /> id: img
anchors.fill: parent<br /> source: {<br /> if (type 0)
return &quot;../../shared/pics/redStone.png&quot;;
else if (type 1)<br /> return "../../shared/pics/blueStone.png&quot;;<br /> else<br /> return "../../shared/pics/greenStone.png&quot;;<br /> }<br /> opacity: 0
Behavior on opacity {<br /> NumberAnimation { properties:"opacity&quot;; duration: 200 }<br /> }<br /> }<br />
Note the opacity: 0 which means the block is transparent when it is first created. We could set the opacity in samegame.js when we create and destroy the blocks, but instead we’ll use states, since this is useful for the next animation we’re going to add. Initially, we add these States to the root element of BoomBlock.qml:
<br />property bool dying: false<br />states: [<br /> State{ name: "AliveState&quot;; when: spawned true &amp;&amp; dying false<br /> PropertyChanges { target: img; opacity: 1 }<br /> },<br /> State{ name: "DeathState&quot;; when: dying == true<br /> PropertyChanges { target: img; opacity: 0 }<br /> }<br />]<br />
Now blocks will automatically fade in, as we already set spawned to true when we implemented the block animations. To fade out, we set dying to true instead of setting opacity to 0 when a block is destroyed (in the floodFill() function).
Adding particle effects
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 BoomBlock.qml, like so:
<br /> Particles {<br /> id: particles
width: 1; height: 1<br /> anchors.centerIn: parent
emissionRate: 0<br /> lifeSpan: 700; lifeSpanDeviation: 600<br /> angle: 0; angleDeviation: 360;<br /> velocity: 100; velocityDeviation: 30<br /> source: {<br /> if (type 0)
return &quot;../../shared/pics/redStar.png&quot;;
else if (type 1)<br /> return "../../shared/pics/blueStar.png&quot;;<br /> else<br /> return "../../shared/pics/greenStar.png&quot;;<br /> }<br /> }<br />
To fully understand this you should read the Particles documentation, but it’s important to note that emissionRate is set to zero so that particles are not emitted normally. 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 like this:
<br /> states: [<br /> State {<br /> name: "AliveState&quot;<br /> when: spawned true &amp;&amp; dying false<br /> PropertyChanges { target: img; opacity: 1 }<br /> },
State {<br /> name: "DeathState&quot;<br /> when: dying == true<br /> StateChangeScript { script: particles.burst(50); }<br /> PropertyChanges { target: img; opacity: 0 }<br /> StateChangeScript { script: block.destroy(1000); }<br /> }<br /> ]<br />
Now the game is beautifully animated, with subtle (or not-so-subtle) animations added for all of the player’s actions. The end result is shown below, with a different set of images to demonstrate basic theming:
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.
Keeping a High Scores table
Another feature we might want to add to the game is a method of storing and retrieving high scores.
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. This requires a few changes to Dialog.qml. In addition to a Text element, it now has a TextInput child item for receiving keyboard text input:
<br />Rectangle {<br />…<br /> TextInput {<br /> id: textInput<br /> anchors { verticalCenter: parent.verticalCenter; left: dialogText.right }<br /> width: 80<br /> text: ""
onAccepted: container.hide() // close dialog when Enter is pressed<br /> }<br />…<br />}<br />
We’ll also add a showWithInput() function. The text input will only be visible if this function is called instead of show(). When the dialog is closed, it emits a closed() signal, and other elements can retrieve the text entered by the user through an inputText property:
<br />Rectangle {<br />…<br /> property string inputText: textInput.text<br /> signal closed
function show(text) {<br /> dialogText.text = text;<br /> container.opacity = 1;<br /> textInput.opacity = 0;<br /> }
function showWithInput(text) {<br /> show(text);<br /> textInput.opacity = 1;<br /> textInput.focus = true;<br /> textInput.text = ""<br /> }
function hide() {<br /> textInput.focus = false;<br /> container.opacity = 0;<br /> container.closed();<br /> }<br />…<br />}<br />
Now the dialog can be used in samegame.qml:
<br /> Dialog {<br /> id: nameInputDialog<br /> anchors.centerIn: parent<br /> z: 100
onClosed: {<br /> if (nameInputDialog.inputText != "")<br /> SameGame.saveHighScore(nameInputDialog.inputText);<br /> }<br /> }<br />
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.
The nameInputDialog is activated in the victoryCheck() function in samegame.js:
<br />function vitoryCheck() {<br />…<br /> //Check whether game has finished<br /> if (deservesBonus || !(floodMoveCheck(0, maxRow - 1, <s>1))) {<br /> gameDuration = new Date()</s> gameDuration;<br /> nameInputDialog.showWithInput("You won! Please enter your name: ");<br /> }<br />}<br />
Storing high scores offline
Now we need to implement the functionality to actually save the High Scores table.
Here is the saveHighScore() function in samegame.js:
<br />function saveHighScore(name) {<br /> if (scoresURL != "")<br /> sendHighScore(name);
var db = openDatabaseSync("SameGameScores&quot;, "1.0&quot;, "Local SameGame High Scores&quot;, 100);<br /> var dataStr = "INSERT INTO Scores VALUES (?, ?, ?, ?)";<br /> var data = [name, gameCanvas.score, maxColumn + "x&quot; + maxRow, Math.floor(gameDuration / 1000)];<br /> db.transaction(function(tx) {<br /> tx.executeSql('CREATE TABLE IF NOT EXISTS Scores(name TEXT, score NUMBER, gridSize TEXT, time NUMBER)');<br /> tx.executeSql(dataStr, data);
var rs = tx.executeSql('SELECT * FROM Scores WHERE gridSize = "12x17&quot; ORDER BY score desc LIMIT 10');<br /> var r = "SCORES for a standard sized grid\n\n&quot;<br /> for (var i = 0; i < rs.rows.length; i+'') {<br /> r''= (i + 1) + ". " + rs.rows.item(i).name + ' got ' + rs.rows.item(i).score + ' points in ' + rs.rows.item(i).time + ' seconds.';<br /> }<br /> dialog.show®;<br /> });<br />}<br />
First we call sendHighScore() (explained in the section below) if it is possible to send the high scores to an online database.
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.
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.
Storing high scores online
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 simple: the high score data is posted to a php script running on a server somewhere, and that server then stores it and displays it to visitors. You could also request an XML or QML file from that same server, which contains and displays the scores, but that’s beyond the scope of this tutorial. The php script we use here is available in the examples directory.
If the player entered their name we can send the data to the web service us
If the player enters a name, we send the data to the service using this code in samegame.js:
<br />function sendHighScore(name) {<br /> var postman = new XMLHttpRequest()<br /> var postData = "name=" + name + "&score=" + gameCanvas.score + "&gridSize=" + maxColumn + "x&quot; + maxRow + "&time=" + Math.floor(gameDuration / 1000);<br /> postman.open("POST&quot;, scoresURL, true);<br /> postman.setRequestHeader("Content-Type&quot;, "application/x-www-form-urlencoded&quot;);<br /> postman.onreadystatechange = function() {<br /> if (postman.readyState == postman.DONE) {<br /> dialog.show("Your score has been uploaded.");<br /> }<br /> }<br /> postman.send(postData);<br />}<br />
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 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 score data to the web server. If it had returned a QML file (or a URL to a QML file&#41; you could instantiate it in much the same way as you did with the blocks.
An alternate way to access and submit web-based data would be to use QML elements designed for this purpose. XmlListModel 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).
That’s it!
By following this tutorial you’ve seen how you can write a fully functional application in QML:
- Build your application with QML elements.
- Add application logic with JavaScript code.
- Add animations with Behaviors and states.
- Store persistent application data using, for example, the Offline Storage API or XMLHttpRequest.