Sophie

Sophie

distrib > Mageia > 7 > i586 > media > core-updates > by-pkgid > 6e2327ca1c896c6d674ae53117299f21 > files > 1802

qtdeclarative5-doc-5.12.6-1.mga7.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- advtutorial.qdoc -->
  <title>QML Advanced Tutorial 2 - Populating the Game Canvas | Qt Quick 5.12.6</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td >Qt 5.12</td><td ><a href="qtquick-index.html">Qt Quick</a></td><td >QML Advanced Tutorial 2 - Populating the Game Canvas</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right"><a href="qtquick-index.html">Qt 5.12.6 Reference Documentation</a></td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
  <link rel="prev" href="qtquick-tutorials-samegame-samegame1-example.html" />
  <link rel="next" href="qtquick-tutorials-samegame-samegame3-example.html" />
<p class="naviNextPrevious headerNavi">
<a class="prevPage" href="qtquick-tutorials-samegame-samegame1-example.html">QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks</a>
<span class="naviSeparator">  &#9702;  </span>
<a class="nextPage" href="qtquick-tutorials-samegame-samegame3-example.html">QML Advanced Tutorial 3 - Implementing the Game Logic</a>
</p><p/>
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level2"><a href="#generating-the-blocks-in-javascript">Generating the Blocks in JavaScript</a></li>
<li class="level2"><a href="#connecting-javascript-components-to-qml">Connecting JavaScript Components to QML</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">QML Advanced Tutorial 2 - Populating the Game Canvas</h1>
<span class="subtitle"></span>
<!-- $$$tutorials/samegame/samegame2-description -->
<div class="descr"> <a name="details"></a>
<a name="generating-the-blocks-in-javascript"></a>
<h3 id="generating-the-blocks-in-javascript">Generating the Blocks in JavaScript</h3>
<p>Now that we've written some types, let's start writing the game.</p>
<p>The first task is to generate the game blocks. Each time the New Game button is clicked, the game canvas is populated with a new, random set of blocks. Since we need to dynamically generate new blocks for each new game, we cannot use <a href="qml-qtquick-repeater.html">Repeater</a> to define the blocks. Instead, we will create the blocks in JavaScript.</p>
<p>Here is the JavaScript code for generating the blocks, contained in a new file, <code>samegame.js</code>. The code is explained below.</p>
<pre class="js">

  var blockSize = 40;
  var maxColumn = 10;
  var maxRow = 15;
  var maxIndex = maxColumn * maxRow;
  var board = new Array(maxIndex);
  var component;

  //Index function used instead of a 2D array
  function index(column, row) {
      return column + (row * maxColumn);
  }

  function startNewGame() {
      //Delete blocks from previous game
      for (var i = 0; i < maxIndex; i++) {
          if (board[i] != null)
              board[i].destroy();
      }

      //Calculate board size
      maxColumn = Math.floor(background.width / blockSize);
      maxRow = Math.floor(background.height / blockSize);
      maxIndex = maxRow * maxColumn;

      //Initialize Board
      board = new Array(maxIndex);
      for (var column = 0; column < maxColumn; column++) {
          for (var row = 0; row < maxRow; row++) {
              board[index(column, row)] = null;
              createBlock(column, row);
          }
      }
  }

  function createBlock(column, row) {
      if (component == null)
          component = Qt.createComponent("Block.qml");

      // Note that if Block.qml was not a local file, component.status would be
      // Loading and we should wait for the component's statusChanged() signal to
      // know when the file is downloaded and ready before calling createObject().
      if (component.status == Component.Ready) {
          var dynamicObject = component.createObject(background);
          if (dynamicObject == null) {
              console.log("error creating block");
              console.log(component.errorString());
              return false;
          }
          dynamicObject.x = column * blockSize;
          dynamicObject.y = row * blockSize;
          dynamicObject.width = blockSize;
          dynamicObject.height = blockSize;
          board[index(column, row)] = dynamicObject;
      } else {
          console.log("error loading block component");
          console.log(component.errorString());
          return false;
      }
      return true;
  }

</pre>
<p>The <code>startNewGame()</code> function deletes the blocks created in the previous game and calculates the number of rows and columns of blocks required to fill the game window for the new game. Then, it creates an array to store all the game blocks, and calls <code>createBlock()</code> to create enough blocks to fill the game window.</p>
<p>The <code>createBlock()</code> function creates a block from the <code>Block.qml</code> file and moves the new block to its position on the game canvas. This involves several steps:</p>
<ul>
<li>Qt.createComponent() is called to generate a type from <code>Block.qml</code>. If the component is ready, we can call <code>createObject()</code> to create an instance of the <code>Block</code> item.</li>
<li>If <code>createObject()</code> returned null (i.e&#x2e; if there was an error while loading the object), print the error information.</li>
<li>Place the block in its position on the board and set its width and height. Also, store it in the blocks array for future reference.</li>
<li>Finally, print error information to the console if the component could not be loaded for some reason (for example, if the file is missing).</li>
</ul>
<a name="connecting-javascript-components-to-qml"></a>
<h3 id="connecting-javascript-components-to-qml">Connecting JavaScript Components to QML</h3>
<p>Now we need to call the JavaScript code in <code>samegame.js</code> from our QML files. To do this, we add this line to <code>samegame.qml</code> which imports the JavaScript file as a module:</p>
<pre class="qml">

  import "samegame.js" as SameGame

</pre>
<p>This allows us to refer to any functions within <code>samegame.js</code> using &quot;SameGame&quot; as a prefix: for example, <code>SameGame.startNewGame()</code> or <code>SameGame.createBlock()</code>. This means we can now connect the New Game button's <code>onClicked</code> handler to the <code>startNewGame()</code> function, like this:</p>
<pre class="qml">

          Button {
              anchors { left: parent.left; verticalCenter: parent.verticalCenter }
              text: "New Game"
              onClicked: SameGame.startNewGame()
          }

</pre>
<p>So, when you click the New Game button, <code>startNewGame()</code> is called and generates a field of blocks, like this:</p>
<p class="centerAlign"><img src="images/declarative-adv-tutorial2.png" alt="" /></p><p>Now, we have a screen of blocks, and we can begin to add the game mechanics.</p>
<p>Files:</p>
<ul>
<li><a href="qtquick-tutorials-samegame-samegame2-block-qml.html">tutorials/samegame/samegame2/Block.qml</a></li>
<li><a href="qtquick-tutorials-samegame-samegame2-button-qml.html">tutorials/samegame/samegame2/Button.qml</a></li>
<li><a href="qtquick-tutorials-samegame-samegame2-samegame-js.html">tutorials/samegame/samegame2/samegame.js</a></li>
<li><a href="qtquick-tutorials-samegame-samegame2-samegame-qml.html">tutorials/samegame/samegame2/samegame.qml</a></li>
<li><a href="qtquick-tutorials-samegame-samegame2-samegame2-qmlproject.html">tutorials/samegame/samegame2/samegame2.qmlproject</a></li>
</ul>
</div>
<!-- @@@tutorials/samegame/samegame2 -->
<p class="naviNextPrevious footerNavi">
<a class="prevPage" href="qtquick-tutorials-samegame-samegame1-example.html">QML Advanced Tutorial 1 - Creating the Game Canvas and Blocks</a>
<span class="naviSeparator">  &#9702;  </span>
<a class="nextPage" href="qtquick-tutorials-samegame-samegame3-example.html">QML Advanced Tutorial 3 - Implementing the Game Logic</a>
</p>
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2019 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br/>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br/>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>