Initial import from the monolithic Qt.
[profile/ivi/qtdeclarative.git] / examples / declarative / tutorials / samegame / samegame2 / samegame.js
1 //![0]
2 var blockSize = 40;
3 var maxColumn = 10;
4 var maxRow = 15;
5 var maxIndex = maxColumn * maxRow;
6 var board = new Array(maxIndex);
7 var component;
8
9 //Index function used instead of a 2D array
10 function index(column, row) {
11     return column + (row * maxColumn);
12 }
13
14 function startNewGame() {
15     //Delete blocks from previous game
16     for (var i = 0; i < maxIndex; i++) {
17         if (board[i] != null)
18             board[i].destroy();
19     }
20
21     //Calculate board size
22     maxColumn = Math.floor(background.width / blockSize);
23     maxRow = Math.floor(background.height / blockSize);
24     maxIndex = maxRow * maxColumn;
25
26     //Initialize Board
27     board = new Array(maxIndex);
28     for (var column = 0; column < maxColumn; column++) {
29         for (var row = 0; row < maxRow; row++) {
30             board[index(column, row)] = null;
31             createBlock(column, row);
32         }
33     }
34 }
35
36 function createBlock(column, row) {
37     if (component == null)
38         component = Qt.createComponent("Block.qml");
39
40     // Note that if Block.qml was not a local file, component.status would be
41     // Loading and we should wait for the component's statusChanged() signal to
42     // know when the file is downloaded and ready before calling createObject().
43     if (component.status == Component.Ready) {
44         var dynamicObject = component.createObject(background);
45         if (dynamicObject == null) {
46             console.log("error creating block");
47             console.log(component.errorString());
48             return false;
49         }
50         dynamicObject.x = column * blockSize;
51         dynamicObject.y = row * blockSize;
52         dynamicObject.width = blockSize;
53         dynamicObject.height = blockSize;
54         board[index(column, row)] = dynamicObject;
55     } else {
56         console.log("error loading block component");
57         console.log(component.errorString());
58         return false;
59     }
60     return true;
61 }
62 //![0]
63