1 /**************************************************************************
2 Ghosts Overboard - a game for 'Meego 1.2 Harmattan'
4 Copyright (C) 2011 Heli Hyvättinen
6 This file is part of Ghosts Overboard
8 Ghosts Overboard is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 **************************************************************************/
26 #include <QGraphicsPixmapItem>
28 #include <QMessageBox>
30 #include <QApplication>
32 #include <QPushButton>
34 #include <QVBoxLayout>
38 const QString ghostImageFilename_ = ":/pix/aave.png";
39 const QString rockImageFilename_ =":/pix/kari.png";
40 const QString octopusImageFilename_= ":/pix/tursas.png";
43 SeaScene::SeaScene(QObject *parent) :
44 QGraphicsScene(parent)
47 setItemPointersNull();
50 screenLitKeeper_.keepScreenLit(true);
54 QPixmap waves (":/pix/meri.png");
56 setBackgroundBrush(QBrush(waves));
60 qsrand(QTime::currentTime().msec()+2); //+2 to avoid setting it to 1
62 //Setup the level list
64 QList<Level> levelList;
66 levelList.append(level1);
67 Level level2(5,10,2,50);
68 levelList.append(level2);
69 Level level3(5,15,2,50);
70 levelList.append(level3);
71 Level level4(5,15,4,50);
72 levelList.append(level4);
73 Level level5(5,15,5,100);
74 levelList.append(level5);
76 Levelset set ("Original",levelList);
83 //This ensures that nextlevel will not be called until its safe to delete the Ship object.
84 //Leaving out Qt::QueuedConnection or calling nextlevel directly instead of emitting the signal will CRASH
85 connect(this,SIGNAL(allGhostsPicked()),this,SLOT(nextLevel()),Qt::QueuedConnection);
88 pVibrateAction_ = new QAction(tr("Vibration effects"),this);
89 pVibrateAction_->setCheckable(true);
90 connect(pVibrateAction_,SIGNAL(toggled(bool)),this,SLOT(vibrationActivate(bool)));
92 pVibrateAction_->setChecked(settings.value("vibration",false).toBool());
95 pPauseAction_ = new QAction(tr("Pause"),this);
96 pPauseAction_->setCheckable(true);
97 connect(pPauseAction_,SIGNAL(toggled(bool)),this,SLOT(pause(bool)));
100 autopauseTimer.setSingleShot(true);
101 autopauseTimer.setInterval(15*60*1000);
102 connect(&autopauseTimer,SIGNAL(timeout()),this,SLOT(turnPauseOn()));
107 void SeaScene::setupMap(int ghosts, int rocks, int octopuses, int octopusSpeed)
113 setItemPointersNull();
117 createAboutBoxItems();
118 createVictoryItems();
120 createLevelCompletedItems();
123 //empty the list of moving items
125 movingItems_.clear();
127 //empty the list of free slots
130 //fill the list of free slots
132 int numberOfXTiles = width() / 40;
133 int numberOfYTiles = height() /40;
135 // qDebug() << numberOfXTiles << " slots in x direction";
136 // qDebug() << numberOfYTiles << " slots in y rirection";
138 for (int i = 0; i < numberOfXTiles; i++ )
140 for (int j = 0; j < numberOfYTiles; j++)
142 freeTiles_.append(QPointF(i*40,j*40));
149 for (int i = 0; i < rocks; i++)
151 QPointF * pPosition = findRandomFreeSlot();
153 //If there was no room no point to continue
154 if (pPosition == NULL)
157 QPixmap rockPixmap (":/pix/kari.png");
158 QGraphicsPixmapItem * pRock = addPixmap(rockPixmap);
159 pRock->setData(0,"rock");
160 pRock->setPos(*pPosition);
167 ghostsLeft_ = ghosts;
168 spreadGhosts(ghosts);
172 //spread the octopuses
174 QList <Octopus*> octopusList;
176 for (int i=0; i < octopuses; i++)
178 QPointF * pPosition = findRandomFreeSlot();
180 //If there was no room no point to continue
181 if (pPosition == NULL)
184 QPixmap octopusPixmap (":/pix/tursas.png");
185 Octopus * pOctopus = new Octopus(octopusPixmap,octopusSpeed);
186 pOctopus->setData(0,"octopus");
187 pOctopus->setPos(*pPosition);
189 pOctopus->startMoving();
190 movingItems_.append(pOctopus);
191 connect(this,SIGNAL(pauseOn()),pOctopus,SLOT(stopMoving()));
192 connect(this,SIGNAL(pauseOff()),pOctopus,SLOT(startMoving()));
193 octopusList.append(pOctopus);
201 QPointF * pPosition = findRandomFreeSlot();
202 if (pPosition == NULL)
204 // Game cannot begin without a free position for ship, so give an error message and return
206 QMessageBox::critical(NULL,"Error! Too many objects on screen","No free space to place the ship. The game cannot start. Please choose another level.");
210 QList<QPixmap> shipImages;
211 shipImages.append(QPixmap(":/pix/laiva.png"));
212 shipImages.append(QPixmap(":/pix/laiva_1aave.png"));
213 shipImages.append(QPixmap(":/pix/laiva_2aave.png"));
214 shipImages.append(QPixmap(":/pix/laiva_3aave.png"));
215 shipImages.append(QPixmap(":/pix/laiva_4aave.png"));
216 shipImages.append(QPixmap(":/pix/laiva_5aave.png"));
217 shipImages.append(QPixmap(":/pix/laiva_6aave.png"));
218 shipImages.append(QPixmap(":/pix/laiva_7aave.png"));
219 shipImages.append(QPixmap(":/pix/laiva_8aave.png"));
220 shipImages.append(QPixmap(":/pix/laiva_9aave.png"));
221 shipImages.append(QPixmap(":/pix/laiva_10aave.png"));
223 Ship * pShip = new Ship (shipImages);
224 pShip->setData(0,"ship");
225 pShip->setPos(*pPosition);
227 connect(pShip,SIGNAL(pickingGhost(QGraphicsItem*)),this, SLOT(removeGhost(QGraphicsItem*)) );
228 connect(pShip,SIGNAL(droppingGhosts(int)),this,SLOT(ghostsDropped(int)));
229 connect(this,SIGNAL(vibrationActivated(bool)),pShip,SLOT(setVibrationActivate(bool)));
230 pShip->startMoving();
231 movingItems_.append(pShip);
232 connect(this,SIGNAL(pauseOn()),pShip,SLOT(stopMoving()));
233 connect(this,SIGNAL(pauseOff()),pShip,SLOT(startMoving()));
234 foreach (Octopus* pOctopus, octopusList)
236 connect(pOctopus,SIGNAL(droppingGhosts()),pShip,SLOT(dropAllGhosts()));
241 void SeaScene::setupMap(Level level)
243 setupMap(level.getNumberOfGhosts(),level.getNumberOfRocks(),level.getNumberOfOctopuses(),level.getOctopusSpeed());
246 void SeaScene::spreadGhosts(int ghosts)
250 //the octopuses and the ship may have moved from their original positions,
251 //so the list of free slots must be adjusted to exclude their current positions
253 QList<QPointF> temporarilyReservedSlots;
255 foreach (QGraphicsItem* pItem, movingItems_)
259 // qDebug() << "NULL item in movingItems_";
263 //round x and y down to fit the slot size
273 QPointF position (x,y);
275 //remove the tiles (potentially) occupied by the item from free slots and place in temp list if was in the list before
277 if (freeTiles_.removeOne(position))
278 temporarilyReservedSlots.append(position);
283 if (freeTiles_.removeOne(position))
284 temporarilyReservedSlots.append(position);
288 if (freeTiles_.removeOne(position))
289 temporarilyReservedSlots.append(position);
293 if (freeTiles_.removeOne(position))
294 temporarilyReservedSlots.append(position);
299 //spread ghosts in random free slots
301 for (int i=0; i < ghosts; i++)
303 QPointF * pPosition = findRandomFreeSlot();
305 //If there was no room no point to continue
306 if (pPosition == NULL)
309 QPixmap ghostPixmap(":/pix/aave.png");
310 QGraphicsPixmapItem * pGhost = addPixmap(ghostPixmap);
311 pGhost->setData(0,"ghost");
312 pGhost->setPos(*pPosition);
316 //return the slots occupied by moving items to free slots
317 freeTiles_.append(temporarilyReservedSlots);
319 //clear temp for the next round
320 temporarilyReservedSlots.clear();
323 QPointF* SeaScene::findRandomFreeSlot()
325 if (freeTiles_.isEmpty())
328 int index = qrand()%freeTiles_.size();
330 // qDebug() << index << " index";
331 return new QPointF (freeTiles_.takeAt(index));
335 void SeaScene::removeGhost(QGraphicsItem *pGhost)
337 removeItem(pGhost); //remove the item from scene
338 freeTiles_.append(pGhost->scenePos()); //add the item's position to free slots
341 if (ghostsLeft_ == 0)
343 emit allGhostsPicked();
344 // qDebug() << "All ghosts picked!";
348 void SeaScene::ghostsDropped(int ghosts)
350 ghostsLeft_ += ghosts;
352 spreadGhosts(ghosts);
355 void SeaScene::pause(bool paused)
357 // qDebug() << "pause pressed " << paused;
358 if (paused_ == paused)
365 // qDebug() << "starting to move again";
366 // emit fullscreenRequested(); fremantle specific (since no "show statusbar" action in harmattan version)
368 screenLitKeeper_.keepScreenLit(true);
370 pPausetextItem_->hide();
372 scoreCounter_.start();
374 autopauseTimer.start(); //Start counting towards autopause
379 // qDebug("about to stop movement");
381 screenLitKeeper_.keepScreenLit(false);
382 if (pPausetextItem_ != NULL)
384 // qDebug() << "about to show the pause text";
385 pPausetextItem_->show();
386 // qDebug() << "showing pause text";
388 // else qDebug() << "No pause text available";
390 levelScore_ += scoreCounter_.elapsed();
392 autopauseTimer.stop(); //No need to count toward autopause when already paused
396 void SeaScene::vibrationActivate(bool on)
398 emit vibrationActivated(on);
401 void SeaScene::handleScreenTapped()
404 //If the game is going just pause it
407 pPauseAction_->setChecked(true);
411 //If the game is paused and about box is shown, close it and show the pause text and menu again
415 if(pAboutBoxItem_->isVisible())
417 pAboutBoxItem_->hide();
418 pPausetextItem_->show();
423 //If the game is paused, check if the level completed item is shown
425 if (pLevelCompletedItem_)
427 if (pLevelCompletedItem_->isVisible())
429 pLevelCompletedItem_->hide();
430 restartLevel(); //Current level has already been set to the next one before showing the level completed item
431 pPauseAction_->setChecked(false); //unpause
436 //If the game is paused, check if the victory item is being shown
437 if(pVictoryCongratulationsItem_)
439 if (pVictoryCongratulationsItem_->isVisibleTo(NULL)) //returns visibility to scene
441 pVictoryCongratulationsItem_->hide();
443 pPauseAction_->setChecked(false); // unpause
449 //If the game is paused and no victory or about box, check if menu item was selected
451 QList<QGraphicsItem *> items = selectedItems();
453 //if nothing selected resume play
457 pPauseAction_->setChecked(false);
462 //If something was selected check if it was one of the menu items and act on it
463 //(Nothing else should be made selectable anyway)
467 QGraphicsItem* pItem = items.at(0); //Selecting an item brings here, thus only selecting one item should be possible
468 //... so we can just take the first one
470 //Selection is just used to get notice of a menu item being clicked, removed after use
475 //Act upon the selected item
478 if (pItem == pRestartGameItem_)
480 // qDebug() << "game restart requested";
482 pPauseAction_->setChecked(false); //unpause game
486 else if (pItem == pRestartLevelItem_)
488 // qDebug() << "Level restart requested";
490 pPauseAction_->setChecked(false); //unpause game
494 else if (pItem == pSettingsItem_)
496 pVibrateAction_->toggle();
499 settings.setValue("vibration",pVibrateAction_->isChecked());
501 QString text = pSettingsItem_->toHtml();
502 if (pVibrateAction_->isChecked())
503 text.replace(" on"," off"); //don't remove spaces or you get vibratioff...
505 text.replace(" off"," on");
506 pSettingsItem_->setHtml(text);
509 else if (pItem == pAboutItem_)
514 else if (pItem == pQuitItem_)
523 void SeaScene::createMenuItems()
527 font.setPixelSize(35);
531 pPausetextItem_ = new QGraphicsTextItem;
533 // This is for fremantle
534 // pPausetextItem_->setHtml("<font size = \"5\" color = darkorange> Game paused. Tap to continue.");
536 //Harmattan needs bigger font
537 pPausetextItem_->setHtml("<font size = \"7\" color = darkorange> Game paused. Tap to continue.");
540 pPausetextItem_->setZValue(1000);
541 pPausetextItem_->setPos(200,50);
542 addItem(pPausetextItem_);
543 pPausetextItem_->hide();
547 // This is for fremantle
548 // QString menufonthtml = "<font size = \"4\" color = darkorange>";
551 //Harmattan needs bigger font
552 QString menufonthtml = "<font size = \"6\" color = darkorange>";
555 pRestartGameItem_ = new QGraphicsTextItem;
556 pRestartGameItem_->setHtml(tr("Restart <br> game").prepend(menufonthtml));
557 prepareForMenu(pRestartGameItem_);
559 pRestartLevelItem_ = new QGraphicsTextItem;
560 pRestartLevelItem_->setHtml(tr("Restart <br> level").prepend(menufonthtml));
561 prepareForMenu(pRestartLevelItem_);
563 pSettingsItem_ = new QGraphicsTextItem;
564 QString vibraText(tr("Turn vibration <br> effects "));
566 if (pVibrateAction_->isChecked())
574 vibraText.append(statusText);
575 pSettingsItem_->setHtml(vibraText.prepend(menufonthtml));
576 prepareForMenu(pSettingsItem_);
578 pAboutItem_ = new QGraphicsTextItem;
579 pAboutItem_->setHtml(tr("About <br> game").prepend(menufonthtml));
580 prepareForMenu(pAboutItem_);
582 pQuitItem_ = new QGraphicsTextItem;
583 pQuitItem_->setHtml(tr("Quit <br> game").prepend(menufonthtml));
584 prepareForMenu(pQuitItem_);
588 void SeaScene::prepareForMenu(QGraphicsItem * pItem)
591 //Menu items have pause text item as their parent and are thus added to scene automatically
592 //They are also shown and hidden with it, resulting in the menu being visble when the game is paused
593 //Their coordinates are given relative to the parent.
596 pItem->setParentItem(pPausetextItem_);
597 pItem->setZValue(1000);
598 pItem->setFlag(QGraphicsItem::ItemIsSelectable);
600 pItem->setX(menuItemCount_++*160-150);
604 void SeaScene::about()
606 pPausetextItem_->hide();
607 pAboutBoxItem_->show();
611 void SeaScene::restartLevel()
616 setupMap(levelset_.getLevel(currentLevel_)); //getLevel() returns default constructor Level if index is invalid, so no risk of crash
618 scoreCounter_.start();
620 vibrationActivate(pVibrateAction_->isChecked()); //Vibration effects are lost without this
621 // qDebug() << pVibrateAction_->isChecked();
622 autopauseTimer.start(); //reset counting towards autopause
629 void SeaScene::nextLevel()
632 //get score for previous level
633 levelScore_ += scoreCounter_.elapsed();
634 totalScore_ += levelScore_;
635 int highscore = levelset_.getLevelHighScore(currentLevel_);
637 qDebug() << highscore;
641 if (levelScore_ >= highscore)
643 scoretext = tr("<font size=\"7\" color = darkorange>Your time: %1.%2 s<br>Best time: %3.%4 s").arg(levelScore_/1000).arg((levelScore_%1000)/100).arg(highscore/1000).arg((highscore%1000)/100);
646 else //New high score!
649 scoretext = tr("<font size=\"7\" color = darkorange>Your time %1.%2 s is<br>the new best time!").arg(levelScore_/1000).arg((levelScore_%1000)/100);
650 levelset_.setLevelHighScore(currentLevel_,levelScore_);
653 //pause to show the highscore or victory screen
656 pPausetextItem_->hide();
659 //Go to the next level if available
662 if ( currentLevel_ < levelset_.numberOfLevels() )
665 pLevelCompletedItem_->setHtml(scoretext);
666 pLevelCompletedItem_->show();
672 int totalHighsore = levelset_.getTotalHighScore();
673 if (totalScore_ >= totalHighsore)
675 scoretext.append(tr("<br>Your total time: %1.%2 s<br>Best total time: %3.%4 s").arg(totalScore_/1000).arg((totalScore_%1000)/100).arg(totalHighsore/1000).arg((totalHighsore%1000)/100));
677 else //new total high score
679 scoretext.append(tr("<br>Your total time %1.%2 s is<br>the new best time").arg(totalScore_/1000).arg((totalScore_%1000)/100));
680 levelset_.setTotalHighScore(totalScore_);
683 pVictoryScoreItem_->setHtml(scoretext);
684 pVictoryCongratulationsItem_->show();
689 void SeaScene::restartGame()
697 void SeaScene::forcePause()
699 //Pause without setting the pause action state
703 void SeaScene::softContinue()
705 //Continue if not being paused by the user
706 // Reverts forcePause()
708 pause(pPauseAction_->isChecked());
712 void SeaScene::createVictoryItems()
714 pVictoryCongratulationsItem_ = new QGraphicsTextItem;
715 pVictoryCongratulationsItem_->setHtml("<font size=\"7\" color = darkorange> <b> Victory!");
716 pVictoryCongratulationsItem_->hide();
717 pVictoryCongratulationsItem_->setPos(315,30);
718 pVictoryCongratulationsItem_->setZValue(1000);
719 addItem(pVictoryCongratulationsItem_);
722 //coordinates are relative to the parent
724 QGraphicsTextItem * pTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
725 pTextItem->setHtml("<font size=\"7\" color = darkorange> Congratulations!");
726 pTextItem->setPos(-50,80);
727 pTextItem->setZValue(1000);
729 QGraphicsTextItem * pMiddleTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
730 pMiddleTextItem->setHtml("<font size=\"7\" color = darkorange> You have saved all the ghosts.");
731 pMiddleTextItem->setPos(-145,120);
732 pMiddleTextItem->setZValue(1000);
735 pVictoryScoreItem_ = new QGraphicsTextItem(pVictoryCongratulationsItem_);
736 pVictoryScoreItem_->setPos(-50,180);
737 pMiddleTextItem->setZValue(1000);
738 //Text is set at usetime!
740 QGraphicsTextItem * pLowestTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
741 pLowestTextItem->setHtml("<font size=\"7\" color = darkorange> Tap to play again");
742 pLowestTextItem->setPos(-50,360);
743 pLowestTextItem->setZValue(1000);
747 void SeaScene::createAboutBoxItems()
749 pAboutBoxItem_ = new QGraphicsTextItem;
750 addItem(pAboutBoxItem_);
751 pAboutBoxItem_->setPos(25,50);
752 pAboutBoxItem_->setZValue(1000);
753 pAboutBoxItem_->hide();
755 pAboutBoxItem_->setHtml(tr("<font color = darkorange size = \"7\">"
756 "%1 <br> <font size = \"7\"> Version %2"
757 "<p><font size = \"6\"> Copyright 2011 Heli Hyvättinen"
758 "<p><font size = \"6\"> License: General Public License v2"
759 "<p><font size = \"5\"> Web: http://ghostsoverboard.garage.maemo.org/<br>"
760 "Bug Reports: <br> https://bugs.maemo.org/"
761 "enter_bug.cgi?product=Ghosts%20Overboard"
762 ).arg(QApplication::applicationName(),QApplication::applicationVersion()));
766 void SeaScene::setItemPointersNull()
768 pPausetextItem_ = NULL;
769 pRestartLevelItem_ = NULL;
770 pRestartGameItem_ = NULL;
771 pSettingsItem_ = NULL;
774 // pMinimizeItem_ = NULL; //Fremantle spesific
776 pAboutBoxItem_ = NULL;
777 pLevelCompletedItem_ = NULL;
778 pVictoryScoreItem_ = NULL;
782 void SeaScene::turnPauseOn()
784 pPauseAction_->setChecked(true);
789 void SeaScene::createLevelCompletedItems()
791 pLevelCompletedItem_ = new QGraphicsTextItem;
792 addItem(pLevelCompletedItem_);
793 pLevelCompletedItem_->setPos(240,100);
794 pLevelCompletedItem_->setZValue(1000);
795 pLevelCompletedItem_->hide();
796 //The text is set at usetime
798 QGraphicsTextItem * pTapForNextLevelItem = new QGraphicsTextItem(pLevelCompletedItem_);
799 pTapForNextLevelItem->setPos(-60,100);
800 pTapForNextLevelItem->setZValue(1000);
801 pTapForNextLevelItem->setHtml("<font size=\"7\" color = darkorange>Tap to start the next level");