1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the examples of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
14 ** * Redistributions of source code must retain the above copyright
15 ** notice, this list of conditions and the following disclaimer.
16 ** * Redistributions in binary form must reproduce the above copyright
17 ** notice, this list of conditions and the following disclaimer in
18 ** the documentation and/or other materials provided with the
20 ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
21 ** of its contributors may be used to endorse or promote products derived
22 ** from this software without specific prior written permission.
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
39 ****************************************************************************/
41 /* This script file handles the game logic */
43 .import QtQuick.LocalStorage 2.0 as Sql
48 var maxIndex = maxColumn*maxRow;
49 var board = new Array(maxIndex);
50 var blockSrc = "Block.qml";
52 var component = Qt.createComponent(blockSrc);
54 var betweenTurns = false;
56 var puzzleLevel = null;
59 var gameMode = "arcade"; //Set in new game, then tweaks behaviour of other functions
62 function changeBlock(src)
65 component = Qt.createComponent(blockSrc);
68 // Index function used instead of a 2D array
69 function index(column, row)
71 return column + row * maxColumn;
74 function timeStr(msecs)
76 var secs = Math.floor(msecs/1000);
77 var m = Math.floor(secs/60);
78 var ret = "" + m + "m " + (secs%60) + "s";
84 if (gameCanvas == undefined)
86 // Delete blocks from previous game
87 for (var i = 0; i < maxIndex; i++) {
92 if (puzzleLevel != null){
93 puzzleLevel.destroy();
99 function startNewGame(gc, mode, map)
102 if (mode == undefined)
112 // Calculate board size
113 maxColumn = Math.floor(gameCanvas.width/gameCanvas.blockSize);
114 maxRow = Math.floor(gameCanvas.height/gameCanvas.blockSize);
115 maxIndex = maxRow * maxColumn;
116 if (gameMode == "arcade") //Needs to be after board sizing
121 board = new Array(maxIndex);
122 gameCanvas.score = 0;
123 gameCanvas.score2 = 0;
124 gameCanvas.moves = 0;
125 gameCanvas.curTurn = 1;
126 if (gameMode == "puzzle")
128 else//Note that we load them in reverse order for correct visual stacking
129 for (var column = maxColumn - 1; column >= 0; column--)
130 for (var row = maxRow - 1; row >= 0; row--)
131 createBlock(column, row);
132 if (gameMode == "puzzle")
133 getLevelHistory();//Needs to be after map load
134 gameDuration = new Date();
137 var fillFound; // Set after a floodFill call to the number of blocks found
138 var floodBoard; // Set to 1 if the floodFill reaches off that node
140 // NOTE: Be careful with vars named x,y, as the calling object's x,y are still in scope
141 function handleClick(x,y)
143 if (betweenTurns || gameOver || gameCanvas == undefined)
145 var column = Math.floor(x/gameCanvas.blockSize);
146 var row = Math.floor(y/gameCanvas.blockSize);
147 if (column >= maxColumn || column < 0 || row >= maxRow || row < 0)
149 if (board[index(column, row)] == null)
151 // If it's a valid block, remove it and all connected (does nothing if it's not connected)
152 floodFill(column,row, -1);
155 if (gameMode == "multiplayer" && gameCanvas.curTurn == 2)
156 gameCanvas.score2 += (fillFound - 1) * (fillFound - 1);
158 gameCanvas.score += (fillFound - 1) * (fillFound - 1);
159 if (gameMode == "multiplayer" && gameCanvas.curTurn == 2)
163 gameCanvas.moves += 1;
164 if (gameMode == "endless")
166 else if (gameMode != "multiplayer")
168 if (gameMode == "multiplayer" && !gc.gameOver){
170 gameCanvas.swapPlayers();//signal, animate and call turnChange() when ready
174 function floodFill(column,row,type)
176 if (board[index(column, row)] == null)
181 type = board[index(column,row)].type;
183 // Flood fill initialization
185 floodBoard = new Array(maxIndex);
187 if (column >= maxColumn || column < 0 || row >= maxRow || row < 0)
189 if (floodBoard[index(column, row)] == 1 || (!first && type != board[index(column, row)].type))
191 floodBoard[index(column, row)] = 1;
192 floodFill(column + 1, row, type);
193 floodFill(column - 1, row, type);
194 floodFill(column, row + 1, type);
195 floodFill(column, row - 1, type);
196 if (first == true && fillFound == 0)
197 return; // Can't remove single blocks
198 board[index(column, row)].dying = true;
199 board[index(column, row)] = null;
203 function shuffleDown()
206 for (var column = 0; column < maxColumn; column++) {
208 for (var row = maxRow - 1; row >= 0; row--) {
209 if (board[index(column,row)] == null) {
213 var obj = board[index(column, row)];
214 obj.y = (row + fallDist) * gameCanvas.blockSize;
215 board[index(column, row + fallDist)] = obj;
216 board[index(column, row)] = null;
223 for (column = 0; column < maxColumn; column++) {
224 if (board[index(column, maxRow - 1)] == null) {
228 for (row = 0; row < maxRow; row++) {
229 obj = board[index(column, row)];
232 obj.x = (column - fallDist) * gameCanvas.blockSize;
233 board[index(column - fallDist,row)] = obj;
234 board[index(column, row)] = null;
245 for (var column = 0; column < maxColumn; column++) {
247 for (var row = 0; row < maxRow; row++) {
248 if (board[index(column,row)] == null) {
252 var obj = board[index(column, row)];
253 obj.y = (row - fallDist) * gameCanvas.blockSize;
254 board[index(column, row - fallDist)] = obj;
255 board[index(column, row)] = null;
260 // Fall to the left (or should it be right, so as to be left for P2?)
262 for (column = 0; column < maxColumn; column++) {
263 if (board[index(column, 0)] == null) {
267 for (row = 0; row < maxRow; row++) {
268 obj = board[index(column, row)];
271 obj.x = (column - fallDist) * gameCanvas.blockSize;
272 board[index(column - fallDist,row)] = obj;
273 board[index(column, row)] = null;
280 function turnChange()//called by ui outside
282 betweenTurns = false;
283 if (gameCanvas.curTurn == 1){
285 gameCanvas.curTurn = 2;
289 gameCanvas.curTurn = 1;
296 for (var column = 0; column < maxColumn; column++) {
297 for (var row = 0; row < maxRow; row++) {
298 if (board[index(column, row)] == null)
299 createBlock(column, row);
304 function victoryCheck()
306 // Awards bonuses for no blocks left
307 var deservesBonus = true;
308 if (board[index(0,maxRow - 1)] != null || board[index(0,0)] != null)
309 deservesBonus = false;
310 // Checks for game over
312 if (gameCanvas.curTurn = 1)
313 gameCanvas.score += 1000;
315 gameCanvas.score2 += 1000;
317 gameOver = deservesBonus;
318 if (gameCanvas.curTurn == 1){
319 if (!(floodMoveCheck(0, maxRow - 1, -1)))
322 if (!(floodMoveCheck(0, 0, -1, true)))
325 if (gameMode == "puzzle"){
326 puzzleVictoryCheck(deservesBonus);//Takes it from here
330 var winnerScore = Math.max(gameCanvas.score, gameCanvas.score2);
331 if (gameMode == "multiplayer"){
332 gameCanvas.score = winnerScore;
333 saveHighScore(gameCanvas.score2);
335 saveHighScore(gameCanvas.score);
336 gameDuration = new Date() - gameDuration;
337 gameCanvas.gameOver = true;
341 // Only floods up and right, to see if it can find adjacent same-typed blocks
342 function floodMoveCheck(column, row, type, goDownInstead)
344 if (column >= maxColumn || column < 0 || row >= maxRow || row < 0)
346 if (board[index(column, row)] == null)
348 var myType = board[index(column, row)].type;
352 return floodMoveCheck(column + 1, row, myType, goDownInstead) ||
353 floodMoveCheck(column, row + 1, myType, goDownInstead);
355 return floodMoveCheck(column + 1, row, myType) ||
356 floodMoveCheck(column, row - 1, myType);
359 function createBlock(column,row,type)
361 // Note that we don't wait for the component to become ready. This will
362 // only work if the block QML is a local file. Otherwise the component will
363 // not be ready immediately. There is a statusChanged signal on the
364 // component you could use if you want to wait to load remote files.
365 if (component.status == 1){
366 if (type == undefined)
367 type = Math.floor(Math.random() * types);
368 if (type < 0 || type > 4) {
369 console.log("Invalid type requested");//TODO: Is this triggered by custom levels much?
372 var dynamicObject = component.createObject(gameCanvas,
374 "x": column*gameCanvas.blockSize,
375 "y": -1*gameCanvas.blockSize,
376 "width": gameCanvas.blockSize,
377 "height": gameCanvas.blockSize,
378 "particleSystem": gameCanvas.ps});
379 if (dynamicObject == null){
380 console.log("error creating block");
381 console.log(component.errorString());
384 dynamicObject.y = row*gameCanvas.blockSize;
385 dynamicObject.spawned = true;
387 board[index(column,row)] = dynamicObject;
389 console.log("error loading block component");
390 console.log(component.errorString());
396 function showPuzzleError(str)
398 //TODO: Nice user visible UI?
402 function loadMap(map)
405 var levelComp = Qt.createComponent(puzzlePath);
406 if (levelComp.status != 1){
407 console.log("Error loading level");
408 showPuzzleError(levelComp.errorString());
411 puzzleLevel = levelComp.createObject();
412 if (puzzleLevel == null || !puzzleLevel.startingGrid instanceof Array) {
413 showPuzzleError("Bugger!");
416 gameCanvas.showPuzzleGoal(puzzleLevel.goalText);
417 //showPuzzleGoal should call finishLoadingMap as the next thing it does, before handling more events
420 function finishLoadingMap()
422 for (var i in puzzleLevel.startingGrid)
423 if (! (puzzleLevel.startingGrid[i] >= 0 && puzzleLevel.startingGrid[i] <= 9) )
424 puzzleLevel.startingGrid[i] = 0;
425 //TODO: Don't allow loading larger levels, leads to cheating
426 while (puzzleLevel.startingGrid.length > maxIndex) puzzleLevel.startingGrid.shift();
427 while (puzzleLevel.startingGrid.length < maxIndex) puzzleLevel.startingGrid.unshift(0);
428 for (var i in puzzleLevel.startingGrid)
429 if (puzzleLevel.startingGrid[i] > 0)
430 createBlock(i % maxColumn, Math.floor(i / maxColumn), puzzleLevel.startingGrid[i] - 1);
432 //### Experimental feature - allow levels to contain arbitrary QML scenes as well!
433 //while (puzzleLevel.children.length)
434 // puzzleLevel.children[0].parent = gameCanvas;
435 gameDuration = new Date(); //Don't start until we finish loading
438 function puzzleVictoryCheck(clearedAll)//gameOver has also been set if no more moves
441 var soFar = new Date() - gameDuration;
442 if (puzzleLevel.scoreTarget != -1 && gameCanvas.score < puzzleLevel.scoreTarget){
444 } if (puzzleLevel.scoreTarget != -1 && gameCanvas.score >= puzzleLevel.scoreTarget && !puzzleLevel.mustClear){
446 } if (puzzleLevel.timeTarget != -1 && soFar/1000.0 > puzzleLevel.timeTarget){
448 } if (puzzleLevel.moveTarget != -1 && gameCanvas.moves >= puzzleLevel.moveTarget){
450 } if (puzzleLevel.mustClear && gameOver && !clearedAll) {
455 gameCanvas.gameOver = true;
456 gameCanvas.showPuzzleEnd(won);
465 function getHighScore()
467 var db = Sql.LocalStorage.openDatabaseSync(
470 "SameGame Local Data",
475 tx.executeSql('CREATE TABLE IF NOT EXISTS Scores(game TEXT, score NUMBER, gridSize TEXT, time NUMBER)');
476 // Only show results for the current grid size
477 var rs = tx.executeSql('SELECT * FROM Scores WHERE gridSize = "'
478 + maxColumn + "x" + maxRow + '" AND game = "' + gameMode + '" ORDER BY score desc');
479 if (rs.rows.length > 0)
480 gameCanvas.highScore = rs.rows.item(0).score;
482 gameCanvas.highScore = 0;
487 function saveHighScore(score)
490 var db = Sql.LocalStorage.openDatabaseSync(
493 "SameGame Local Data",
496 var dataStr = "INSERT INTO Scores VALUES(?, ?, ?, ?)";
500 maxColumn + "x" + maxRow,
501 Math.floor(gameDuration / 1000)
503 if (score >= gameCanvas.highScore)//Update UI field
504 gameCanvas.highScore = score;
508 tx.executeSql('CREATE TABLE IF NOT EXISTS Scores(game TEXT, score NUMBER, gridSize TEXT, time NUMBER)');
509 tx.executeSql(dataStr, data);
514 function getLevelHistory()
516 var db = Sql.LocalStorage.openDatabaseSync(
519 "SameGame Local Data",
524 tx.executeSql('CREATE TABLE IF NOT EXISTS Puzzle(level TEXT, score NUMBER, moves NUMBER, time NUMBER)');
525 var rs = tx.executeSql('SELECT * FROM Puzzle WHERE level = "' + puzzlePath + '" ORDER BY score desc');
526 if (rs.rows.length > 0) {
527 gameCanvas.puzzleWon = true;
528 gameCanvas.highScore = rs.rows.item(0).score;
530 gameCanvas.puzzleWon = false;
531 gameCanvas.highScore = 0;
537 function saveLevelHistory()
539 var db = Sql.LocalStorage.openDatabaseSync(
542 "SameGame Local Data",
545 var dataStr = "INSERT INTO Puzzle VALUES(?, ?, ?, ?)";
550 Math.floor(gameDuration / 1000)
552 gameCanvas.puzzleWon = true;
556 tx.executeSql('CREATE TABLE IF NOT EXISTS Puzzle(level TEXT, score NUMBER, moves NUMBER, time NUMBER)');
557 tx.executeSql(dataStr, data);
562 function nuke() //For "Debug mode"
564 for (var row = 1; row <= 5; row++) {
565 for (var col = 0; col < 5; col++) {
566 if (board[index(col, maxRow - row)] != null) {
567 board[index(col, maxRow - row)].dying = true;
568 board[index(col, maxRow - row)] = null;
572 if (gameMode == "multiplayer" && gameCanvas.curTurn == 2)
576 if (gameMode == "endless")