PySide QML Tutorial Advanced 3: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
No edit summary
Line 1: Line 1:
=PySide <span class="caps">QML</span> Advanced Tutorial 3: Implementing the Game Logic=
[[Category:LanguageBindings::PySide]]


==Making a playable game==
= PySide QML Advanced Tutorial 3: Implementing the Game Logic =
 
== Making a playable game ==


Now that we have all the game components, we can add the game logic that dictates how a player interacts with the blocks and plays the game until it is won or lost.
Now that we have all the game components, we can add the game logic that dictates how a player interacts with the blocks and plays the game until it is won or lost.
Line 13: Line 15:
* ''floodMoveCheck(xIdx, yIdx, type)''
* ''floodMoveCheck(xIdx, yIdx, type)''


As this is a tutorial about <span class="caps">QML</span>, not game design, we will only discuss ''handleClick()'' and ''victoryCheck()'' below since they interface directly with the <span class="caps">QML</span> elements. Note that although the game logic here is written in JavaScript, it could have been written in Python and then exposed to <span class="caps">QML</span>.
As this is a tutorial about QML, not game design, we will only discuss ''handleClick()'' and ''victoryCheck()'' below since they interface directly with the QML elements. Note that although the game logic here is written in JavaScript, it could have been written in Python and then exposed to QML.


==Enabling mouse click interaction==
== Enabling mouse click interaction ==


To make it easier for the JavaScript code to interface with the <span class="caps">QML</span> elements, we have added an Item called ''gameCanvas'' to ''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:
To make it easier for the JavaScript code to interface with the QML elements, we have added an Item called ''gameCanvas'' to ''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:


The ''gameCanvas'' item is the exact size of the board, and has a score property and a MouseArea to handle mouse clicks. The blocks are now created as its children, and its dimensions are used to determine the board size so that the application scales to the available screen size. Since its size is bound to a multiple of ''blockSize'', ''blockSize'' was moved out of ''samegame.js'' and into ''samegame.qml'' as a <span class="caps">QML</span> property. Note that it can still be accessed from the script.
<code><br /> Item {<br /> id: gameCanvas


When clicked, the MouseArea calls ''handleClick()'' in ''samegame.js'', which determines whether the player’s click should cause any blocks to be removed, and updates ''gameCanvas.score'' with the current score if necessary. Here is the ''handleClick()'' function:
property int score: 0<br /> property int blockSize: 40


Note that if score was a global variable in the ''samegame.js'' file you would not be able to bind to it. You can only bind to <span class="caps">QML</span> properties.
width: parent.width - (parent.width % blockSize)<br /> height: parent.height - (parent.height % blockSize)<br /> anchors.centerIn: parent


===Updating the score¶===
MouseArea {<br /> anchors.fill: parent<br /> onClicked: SameGame.handleClick(mouse.x, mouse.y)<br /> }<br /> }<br /></code>


When 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:
The ''gameCanvas'' item is the exact size of the board, and has a score property and a MouseArea to handle mouse clicks. The blocks are now created as its children, and its dimensions are used to determine the board size so that the application scales to the available screen size. Since its size is bound to a multiple of ''blockSize'', ''blockSize'' was moved out of ''samegame.js'' and into ''samegame.qml'' as a QML property. Note that it can still be accessed from the script.


This updates the ''gameCanvas.score'' value and displays a “Game Over” dialog if the game is finished.
When clicked, the MouseArea calls ''handleClick()'' in ''samegame.js'', which determines whether the player’s click should cause any blocks to be removed, and updates ''gameCanvas.score'' with the current score if necessary. Here is the ''handleClick()'' function:
 
The Game Over dialog is created using a ''Dialog'' element that is defined in ''Dialog.qml''. Here is the ''Dialog.qml'' code. Notice how it is designed to be usable imperatively from the script file, via the functions and signals:
 
We give the dialog a z value of 100 to ensure it is displayed on top of our other components. The default z value for an item is 0.
 
===A dash of color¶===


It’s not much fun to play Same Game if all the blocks are the same color, so we’ve modified the ''createBlock()'' function in ''samegame.js'' to randomly create a different type of block (for either red, green or blue) each time it is called. ''Block.qml'' has also changed so that each block contains a different image depending on its type:
<code><br />function handleClick(xPos, yPos) {<br /> var column = Math.floor(xPos / gameCanvas.blockSize);<br /> var row = Math.floor(yPos / gameCanvas.blockSize);<br /> if (column &gt;= maxColumn || column &lt; 0 || row &gt;= maxRow || row &lt; 0)<br /> return;<br /> if (board[index(column, row)] == null)<br /> return;<br /> //If it's a valid block, remove it and all connected (does nothing if it's not connected)<br /> floodFill(column, row, <s>1);<br /> if (fillFound &lt;= 0)<br /> return;<br /> gameCanvas.score ''= (fillFound - 1) * (fillFound - 1);<br /> shuffleDown();<br /> victoryCheck();<br />}<br /></code>
<br />Note that if score was a global variable in the ''samegame.js'' file you would not be able to bind to it. You can only bind to QML properties.
<br />h3. Updating the score¶
<br />When 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:
<br /><code><br />function victoryCheck() {<br /> //Award bonus points if no blocks left<br /> var deservesBonus = true;<br /> for (var column = maxColumn - 1; column &gt;= 0; column—)<br /> if (board[index(column, maxRow - 1)] != null)<br /> deservesBonus = false;<br /> if (deservesBonus)<br /> gameCanvas.score''= 500;
<br /> //Check whether game has finished<br /> if (deservesBonus || !(floodMoveCheck(0, maxRow</s> 1, <s>1)))<br /> dialog.show(&quot;Game Over. Your score is &quot; + gameCanvas.score);<br />}<br /></code>
<br />This updates the ''gameCanvas.score'' value and displays a “Game Over” dialog if the game is finished.
<br />The Game Over dialog is created using a ''Dialog'' element that is defined in ''Dialog.qml''. Here is the ''Dialog.qml'' code. Notice how it is designed to be usable imperatively from the script file, via the functions and signals:
<br /><code><br />import QtQuick 1.0
<br />Rectangle {<br /> id: container
<br /> function show(text) {<br /> dialogText.text = text;<br /> container.opacity = 1;<br /> }
<br /> function hide() {<br /> container.opacity = 0;<br /> }
<br /> width: dialogText.width + 20<br /> height: dialogText.height + 20<br /> opacity: 0
<br /> Text {<br /> id: dialogText<br /> anchors.centerIn: parent<br /> text: &quot;&quot;<br /> }
<br /> MouseArea {<br /> anchors.fill: parent<br /> onClicked: hide();<br /> }<br />}<br />And this is how it is used in the main samegame.qml file:
<br /> Dialog {<br /> id: dialog<br /> anchors.centerIn: parent<br /> z: 100<br /> }<br /></code>
<br />We give the dialog a z value of 100 to ensure it is displayed on top of our other components. The default z value for an item is 0.
<br />h3. A dash of color¶
<br />It’s not much fun to play Same Game if all the blocks are the same color, so we've modified the ''createBlock()'' function in ''samegame.js'' to randomly create a different type of block (for either red, green or blue) each time it is called. ''Block.qml'' has also changed so that each block contains a different image depending on its type:
<br /><code><br />import QtQuick 1.0
<br />Item {<br /> id: block
<br /> property int type: 0
<br /> Image {<br /> id: img
<br /> anchors.fill: parent<br /> source: {<br /> if (type  0)
                return &amp;quot;../shared/pics/redStone.png&amp;quot;;
            else if (type  1)<br /> return &quot;../shared/pics/blueStone.png&amp;quot;;<br /> else<br /> return &quot;../shared/pics/greenStone.png&amp;quot;;<br /> }<br /> }<br />}<br /></code>
<br />h2. A working game
<br />Now 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). Here is a screenshot of what has been accomplished so far:


==A working game==
<br />This is what ''samegame.qml'' looks like now:
<br /><code><br />import QtQuick 1.0<br />import &quot;samegame.js&amp;quot; as SameGame
<br />Rectangle {<br /> id: screen
<br /> width: 490; height: 720
<br /> SystemPalette { id: activePalette }
<br /> Item {<br /> width: parent.width<br /> anchors { top: parent.top; bottom: toolBar.top }
<br /> Image {<br /> id: background<br /> anchors.fill: parent<br /> source: &quot;../shared/pics/background.jpg&amp;quot;<br /> fillMode: Image.PreserveAspectCrop<br /> }
<br /> Item {<br /> id: gameCanvas
<br /> property int score: 0<br /> property int blockSize: 40
<br /> width: parent.width</s> (parent.width % blockSize)<br /> height: parent.height - (parent.height % blockSize)<br /> anchors.centerIn: parent


Now 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). Here is a screenshot of what has been accomplished so far:
MouseArea {<br /> anchors.fill: parent<br /> onClicked: SameGame.handleClick(mouse.x, mouse.y)<br /> }<br /> }<br /> }


This is what ''samegame.qml'' looks like now:
Dialog {<br /> id: dialog<br /> anchors.centerIn: parent<br /> z: 100<br /> }


The game works, but it’s a little boring right now. Where are the smooth animated transitions? Where are the high scores? If you were a <span class="caps">QML</span> expert you could have written these in the first iteration, but in this tutorial they’ve been saved until the next chapter – where your application becomes alive!
Rectangle {<br /> id: toolBar<br /> width: parent.width; height: 30<br /> color: activePalette.window<br /> anchors.bottom: screen.bottom


===Categories:===
Button {<br /> anchors { left: parent.left; verticalCenter: parent.verticalCenter }<br /> text: &quot;New Game&amp;quot;<br /> onClicked: SameGame.startNewGame()<br /> }


* [[:Category:LanguageBindings|LanguageBindings]]
Text {<br /> id: score<br /> anchors { right: parent.right; verticalCenter: parent.verticalCenter }<br /> text: &quot;Score: Who knows?&quot;<br /> }<br /> }<br />}<br /></code>
** [[:Category:LanguageBindings::PySide|PySide]]

Revision as of 10:18, 24 February 2015


PySide QML Advanced Tutorial 3: Implementing the Game Logic

Making a playable game

Now that we have all the game components, we can add the game logic that dictates how a player interacts with the blocks and plays the game until it is won or lost.

To do this, we have added the following functions to samegame.js:

  • handleClick(x,y)
  • floodFill(xIdx,yIdx,type)
  • shuffleDown()
  • victoryCheck()
  • floodMoveCheck(xIdx, yIdx, type)

As this is a tutorial about QML, not game design, we will only discuss handleClick() and victoryCheck() below since they interface directly with the QML elements. Note that although the game logic here is written in JavaScript, it could have been written in Python and then exposed to QML.

Enabling mouse click interaction

To make it easier for the JavaScript code to interface with the QML elements, we have added an Item called gameCanvas to 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:

<br /> Item {<br /> id: gameCanvas

property int score: 0<br /> property int blockSize: 40

width: parent.width - (parent.width % blockSize)<br /> height: parent.height - (parent.height % blockSize)<br /> anchors.centerIn: parent

MouseArea {<br /> anchors.fill: parent<br /> onClicked: SameGame.handleClick(mouse.x, mouse.y)<br /> }<br /> }<br />

The gameCanvas item is the exact size of the board, and has a score property and a MouseArea to handle mouse clicks. The blocks are now created as its children, and its dimensions are used to determine the board size so that the application scales to the available screen size. Since its size is bound to a multiple of blockSize, blockSize was moved out of samegame.js and into samegame.qml as a QML property. Note that it can still be accessed from the script.

When clicked, the MouseArea calls handleClick() in samegame.js, which determines whether the player’s click should cause any blocks to be removed, and updates gameCanvas.score with the current score if necessary. Here is the handleClick() function:

<br />function handleClick(xPos, yPos) {<br /> var column = Math.floor(xPos / gameCanvas.blockSize);<br /> var row = Math.floor(yPos / gameCanvas.blockSize);<br /> if (column &gt;= maxColumn || column &lt; 0 || row &gt;= maxRow || row &lt; 0)<br /> return;<br /> if (board[index(column, row)] == null)<br /> return;<br /> //If it's a valid block, remove it and all connected (does nothing if it's not connected)<br /> floodFill(column, row, <s>1);<br /> if (fillFound &lt;= 0)<br /> return;<br /> gameCanvas.score ''= (fillFound - 1) * (fillFound - 1);<br /> shuffleDown();<br /> victoryCheck();<br />}<br />


Note that if score was a global variable in the samegame.js file you would not be able to bind to it. You can only bind to QML properties.
h3. Updating the score¶
When 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:


<br />function victoryCheck() {<br /> //Award bonus points if no blocks left<br /> var deservesBonus = true;<br /> for (var column = maxColumn - 1; column &gt;= 0; column—)<br /> if (board[index(column, maxRow - 1)] != null)<br /> deservesBonus = false;<br /> if (deservesBonus)<br /> gameCanvas.score''= 500;
<br /> //Check whether game has finished<br /> if (deservesBonus || !(floodMoveCheck(0, maxRow</s> 1, <s>1)))<br /> dialog.show(&quot;Game Over. Your score is &quot; + gameCanvas.score);<br />}<br />


This updates the gameCanvas.score value and displays a “Game Over” dialog if the game is finished.
The Game Over dialog is created using a Dialog element that is defined in Dialog.qml. Here is the Dialog.qml code. Notice how it is designed to be usable imperatively from the script file, via the functions and signals:


<br />import QtQuick 1.0
<br />Rectangle {<br /> id: container
<br /> function show(text) {<br /> dialogText.text = text;<br /> container.opacity = 1;<br /> }
<br /> function hide() {<br /> container.opacity = 0;<br /> }
<br /> width: dialogText.width + 20<br /> height: dialogText.height + 20<br /> opacity: 0
<br /> Text {<br /> id: dialogText<br /> anchors.centerIn: parent<br /> text: &quot;&quot;<br /> }
<br /> MouseArea {<br /> anchors.fill: parent<br /> onClicked: hide();<br /> }<br />}<br />And this is how it is used in the main samegame.qml file:
<br /> Dialog {<br /> id: dialog<br /> anchors.centerIn: parent<br /> z: 100<br /> }<br />


We give the dialog a z value of 100 to ensure it is displayed on top of our other components. The default z value for an item is 0.
h3. A dash of color¶
It’s not much fun to play Same Game if all the blocks are the same color, so we've modified the createBlock() function in samegame.js to randomly create a different type of block (for either red, green or blue) each time it is called. Block.qml has also changed so that each block contains a different image depending on its type:


<br />import QtQuick 1.0
<br />Item {<br /> id: block
<br /> property int type: 0
<br /> Image {<br /> id: img
<br /> anchors.fill: parent<br /> source: {<br /> if (type  0)
                return &amp;quot;../shared/pics/redStone.png&amp;quot;;
            else if (type  1)<br /> return &quot;../shared/pics/blueStone.png&amp;quot;;<br /> else<br /> return &quot;../shared/pics/greenStone.png&amp;quot;;<br /> }<br /> }<br />}<br />


h2. A working game
Now 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). Here is a screenshot of what has been accomplished so far:


This is what samegame.qml looks like now:


<br />import QtQuick 1.0<br />import &quot;samegame.js&amp;quot; as SameGame
<br />Rectangle {<br /> id: screen
<br /> width: 490; height: 720
<br /> SystemPalette { id: activePalette }
<br /> Item {<br /> width: parent.width<br /> anchors { top: parent.top; bottom: toolBar.top }
<br /> Image {<br /> id: background<br /> anchors.fill: parent<br /> source: &quot;../shared/pics/background.jpg&amp;quot;<br /> fillMode: Image.PreserveAspectCrop<br /> }
<br /> Item {<br /> id: gameCanvas
<br /> property int score: 0<br /> property int blockSize: 40
<br /> width: parent.width</s> (parent.width % blockSize)<br /> height: parent.height - (parent.height % blockSize)<br /> anchors.centerIn: parent

MouseArea {<br /> anchors.fill: parent<br /> onClicked: SameGame.handleClick(mouse.x, mouse.y)<br /> }<br /> }<br /> }

Dialog {<br /> id: dialog<br /> anchors.centerIn: parent<br /> z: 100<br /> }

Rectangle {<br /> id: toolBar<br /> width: parent.width; height: 30<br /> color: activePalette.window<br /> anchors.bottom: screen.bottom

Button {<br /> anchors { left: parent.left; verticalCenter: parent.verticalCenter }<br /> text: &quot;New Game&amp;quot;<br /> onClicked: SameGame.startNewGame()<br /> }

Text {<br /> id: score<br /> anchors { right: parent.right; verticalCenter: parent.verticalCenter }<br /> text: &quot;Score: Who knows?&quot;<br /> }<br /> }<br />}<br />