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:

  1.         Item {
  2.             id: gameCanvas
  3.  
  4.             property int score: 0
  5.             property int blockSize: 40
  6.  
  7.             width: parent.width - (parent.width % blockSize)
  8.             height: parent.height - (parent.height % blockSize)
  9.             anchors.centerIn: parent
  10.  
  11.             MouseArea {
  12.                 anchors.fill: parent
  13.                 onClicked: SameGame.handleClick(mouse.x, mouse.y)
  14.             }
  15.         }

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:

  1. function handleClick(xPos, yPos) {
  2.     var column = Math.floor(xPos / gameCanvas.blockSize);
  3.     var row = Math.floor(yPos / gameCanvas.blockSize);
  4.     if (column >= maxColumn || column < 0 || row >= maxRow || row < 0)
  5.         return;
  6.     if (board[index(column, row)] == null)
  7.         return;
  8.     //If it's a valid block, remove it and all connected (does nothing if it's not connected)
  9.     floodFill(column, row, -1);
  10.     if (fillFound <= 0)
  11.         return;
  12.     gameCanvas.score += (fillFound - 1) * (fillFound - 1);
  13.     shuffleDown();
  14.     victoryCheck();
  15. }

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.

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:

  1. function victoryCheck() {
  2.     //Award bonus points if no blocks left
  3.     var deservesBonus = true;
  4.     for (var column = maxColumn - 1; column >= 0; column--)
  5.         if (board[index(column, maxRow - 1)] != null)
  6.         deservesBonus = false;
  7.     if (deservesBonus)
  8.         gameCanvas.score += 500;
  9.  
  10.     //Check whether game has finished
  11.     if (deservesBonus || !(floodMoveCheck(0, maxRow - 1, -1)))
  12.         dialog.show("Game Over. Your score is " + gameCanvas.score);
  13. }

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:

  1. import QtQuick 1.0
  2.  
  3. Rectangle {
  4.     id: container
  5.  
  6.     function show(text) {
  7.         dialogText.text = text;
  8.         container.opacity = 1;
  9.     }
  10.  
  11.     function hide() {
  12.         container.opacity = 0;
  13.     }
  14.  
  15.     width: dialogText.width + 20
  16.     height: dialogText.height + 20
  17.     opacity: 0
  18.  
  19.     Text {
  20.         id: dialogText
  21.         anchors.centerIn: parent
  22.         text: ""
  23.     }
  24.  
  25.     MouseArea {
  26.         anchors.fill: parent
  27.         onClicked: hide();
  28.     }
  29. }
  30. And this is how it is used in the main samegame.qml file:
  31.  
  32.     Dialog {
  33.         id: dialog
  34.         anchors.centerIn: parent
  35.         z: 100
  36.     }

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:

  1. import QtQuick 1.0
  2.  
  3. Item {
  4.     id: block
  5.  
  6.     property int type: 0
  7.  
  8.     Image {
  9.         id: img
  10.  
  11.         anchors.fill: parent
  12.         source: {
  13.             if (type == 0)
  14.                 return "../shared/pics/redStone.png";
  15.             else if (type == 1)
  16.                 return "../shared/pics/blueStone.png";
  17.             else
  18.                 return "../shared/pics/greenStone.png";
  19.         }
  20.     }
  21. }

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:

  1. import QtQuick 1.0
  2. import "samegame.js" as SameGame
  3.  
  4. Rectangle {
  5.     id: screen
  6.  
  7.     width: 490; height: 720
  8.  
  9.     SystemPalette { id: activePalette }
  10.  
  11.     Item {
  12.         width: parent.width
  13.         anchors { top: parent.top; bottom: toolBar.top }
  14.  
  15.         Image {
  16.             id: background
  17.             anchors.fill: parent
  18.             source: "../shared/pics/background.jpg"
  19.             fillMode: Image.PreserveAspectCrop
  20.         }
  21.  
  22.         Item {
  23.             id: gameCanvas
  24.  
  25.             property int score: 0
  26.             property int blockSize: 40
  27.  
  28.             width: parent.width - (parent.width % blockSize)
  29.             height: parent.height - (parent.height % blockSize)
  30.             anchors.centerIn: parent
  31.  
  32.             MouseArea {
  33.                 anchors.fill: parent
  34.                 onClicked: SameGame.handleClick(mouse.x, mouse.y)
  35.             }
  36.         }
  37.     }
  38.  
  39.     Dialog {
  40.         id: dialog
  41.         anchors.centerIn: parent
  42.         z: 100
  43.     }
  44.  
  45.     Rectangle {
  46.         id: toolBar
  47.         width: parent.width; height: 30
  48.         color: activePalette.window
  49.         anchors.bottom: screen.bottom
  50.  
  51.         Button {
  52.             anchors { left: parent.left; verticalCenter: parent.verticalCenter }
  53.             text: "New Game"
  54.             onClicked: SameGame.startNewGame()
  55.         }
  56.  
  57.         Text {
  58.             id: score
  59.             anchors { right: parent.right; verticalCenter: parent.verticalCenter }
  60.             text: "Score: Who knows?"
  61.         }
  62.     }
  63. }

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 QML 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!

Categories: