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>
39 const QString ghostImageFilename_ = ":/pix/aave.png";
40 const QString rockImageFilename_ =":/pix/kari.png";
41 const QString octopusImageFilename_= ":/pix/tursas.png";
44 SeaScene::SeaScene(QObject *parent) :
45 QGraphicsScene(parent)
48 setItemPointersNull();
51 screenLitKeeper_.keepScreenLit(true);
55 QPixmap waves (":/pix/meri.png");
57 setBackgroundBrush(QBrush(waves));
61 qsrand(QTime::currentTime().msec()+2); //+2 to avoid setting it to 1
63 //Setup the level list
65 QList<Level> levelList;
67 levelList.append(level1);
68 Level level2(5,10,2,50);
69 levelList.append(level2);
70 Level level3(5,15,2,50);
71 levelList.append(level3);
72 Level level4(5,15,4,50);
73 levelList.append(level4);
74 Level level5(5,15,5,100);
75 levelList.append(level5);
77 Levelset set ("Original",levelList);
84 //This ensures that nextlevel will not be called until its safe to delete the Ship object.
85 //Leaving out Qt::QueuedConnection or calling nextlevel directly instead of emitting the signal will CRASH
86 connect(this,SIGNAL(allGhostsPicked()),this,SLOT(nextLevel()),Qt::QueuedConnection);
89 pVibrateAction_ = new QAction(tr("Vibration effects"),this);
90 pVibrateAction_->setCheckable(true);
91 connect(pVibrateAction_,SIGNAL(toggled(bool)),this,SLOT(vibrationActivate(bool)));
93 pVibrateAction_->setChecked(settings.value("vibration",false).toBool());
96 pPauseAction_ = new QAction(tr("Pause"),this);
97 pPauseAction_->setCheckable(true);
98 connect(pPauseAction_,SIGNAL(toggled(bool)),this,SLOT(pause(bool)));
101 autopauseTimer.setSingleShot(true);
102 autopauseTimer.setInterval(15*60*1000);
103 connect(&autopauseTimer,SIGNAL(timeout()),this,SLOT(turnPauseOn()));
105 pResourceSet_ = new ResourcePolicy::ResourceSet("gaming",this);
106 ResourcePolicy::VibraResource * pVibraResource = new ResourcePolicy::VibraResource();
107 pVibraResource->setOptional(false); //The only resource of the set, so no sense for it to be optional
108 pResourceSet_->addResourceObject(pVibraResource);
110 connect(pResourceSet_,SIGNAL(resourcesGranted(const QList< ResourcePolicy::ResourceType >)),this,SLOT(resourcesAvailable()));
111 connect(pResourceSet_,SIGNAL(lostResources()),this,SLOT(resourcesLost()));
113 //To test whether resources were succesfully asked but not given
114 connect(pResourceSet_,SIGNAL(resourcesDenied()),this,SLOT(resourcesLost()));
115 pResourceSet_->setAlwaysReply();
117 pResourceSet_->acquire();
121 void SeaScene::setupMap(int ghosts, int rocks, int octopuses, int octopusSpeed)
127 setItemPointersNull();
131 createAboutBoxItems();
132 createVictoryItems();
134 createLevelCompletedItems();
137 //empty the list of moving items
139 movingItems_.clear();
141 //empty the list of free slots
144 //fill the list of free slots
146 int numberOfXTiles = width() / 40;
147 int numberOfYTiles = height() /40;
149 // qDebug() << numberOfXTiles << " slots in x direction";
150 // qDebug() << numberOfYTiles << " slots in y rirection";
152 for (int i = 0; i < numberOfXTiles; i++ )
154 for (int j = 0; j < numberOfYTiles; j++)
156 freeTiles_.append(QPointF(i*40,j*40));
163 for (int i = 0; i < rocks; i++)
165 QPointF * pPosition = findRandomFreeSlot();
167 //If there was no room no point to continue
168 if (pPosition == NULL)
171 QPixmap rockPixmap (":/pix/kari.png");
172 QGraphicsPixmapItem * pRock = addPixmap(rockPixmap);
173 pRock->setData(0,"rock");
174 pRock->setPos(*pPosition);
181 ghostsLeft_ = ghosts;
182 spreadGhosts(ghosts);
186 //spread the octopuses
188 QList <Octopus*> octopusList;
190 for (int i=0; i < octopuses; i++)
192 QPointF * pPosition = findRandomFreeSlot();
194 //If there was no room no point to continue
195 if (pPosition == NULL)
198 QPixmap octopusPixmap (":/pix/tursas.png");
199 Octopus * pOctopus = new Octopus(octopusPixmap,octopusSpeed);
200 pOctopus->setData(0,"octopus");
201 pOctopus->setPos(*pPosition);
203 pOctopus->startMoving();
204 movingItems_.append(pOctopus);
205 connect(this,SIGNAL(pauseOn()),pOctopus,SLOT(stopMoving()));
206 connect(this,SIGNAL(pauseOff()),pOctopus,SLOT(startMoving()));
207 octopusList.append(pOctopus);
215 QPointF * pPosition = findRandomFreeSlot();
216 if (pPosition == NULL)
218 // Game cannot begin without a free position for ship, so give an error message and return
220 QMessageBox::critical(NULL,"Error! Too many objects on screen","No free space to place the ship. The game cannot start. Please choose another level.");
224 QList<QPixmap> shipImages;
225 shipImages.append(QPixmap(":/pix/laiva.png"));
226 shipImages.append(QPixmap(":/pix/laiva_1aave.png"));
227 shipImages.append(QPixmap(":/pix/laiva_2aave.png"));
228 shipImages.append(QPixmap(":/pix/laiva_3aave.png"));
229 shipImages.append(QPixmap(":/pix/laiva_4aave.png"));
230 shipImages.append(QPixmap(":/pix/laiva_5aave.png"));
231 shipImages.append(QPixmap(":/pix/laiva_6aave.png"));
232 shipImages.append(QPixmap(":/pix/laiva_7aave.png"));
233 shipImages.append(QPixmap(":/pix/laiva_8aave.png"));
234 shipImages.append(QPixmap(":/pix/laiva_9aave.png"));
235 shipImages.append(QPixmap(":/pix/laiva_10aave.png"));
237 Ship * pShip = new Ship (shipImages);
238 pShip->setData(0,"ship");
239 pShip->setPos(*pPosition);
241 connect(pShip,SIGNAL(pickingGhost(QGraphicsItem*)),this, SLOT(removeGhost(QGraphicsItem*)) );
242 connect(pShip,SIGNAL(droppingGhosts(int)),this,SLOT(ghostsDropped(int)));
243 connect(this,SIGNAL(vibrationActivated(bool)),pShip,SLOT(setVibrationActivate(bool)));
244 pShip->startMoving();
245 movingItems_.append(pShip);
246 connect(this,SIGNAL(pauseOn()),pShip,SLOT(stopMoving()));
247 connect(this,SIGNAL(pauseOff()),pShip,SLOT(startMoving()));
248 foreach (Octopus* pOctopus, octopusList)
250 connect(pOctopus,SIGNAL(droppingGhosts()),pShip,SLOT(dropAllGhosts()));
255 void SeaScene::setupMap(Level level)
257 setupMap(level.getNumberOfGhosts(),level.getNumberOfRocks(),level.getNumberOfOctopuses(),level.getOctopusSpeed());
260 void SeaScene::spreadGhosts(int ghosts)
264 //the octopuses and the ship may have moved from their original positions,
265 //so the list of free slots must be adjusted to exclude their current positions
267 QList<QPointF> temporarilyReservedSlots;
269 foreach (QGraphicsItem* pItem, movingItems_)
273 // qDebug() << "NULL item in movingItems_";
277 //round x and y down to fit the slot size
287 QPointF position (x,y);
289 //remove the tiles (potentially) occupied by the item from free slots and place in temp list if was in the list before
291 if (freeTiles_.removeOne(position))
292 temporarilyReservedSlots.append(position);
297 if (freeTiles_.removeOne(position))
298 temporarilyReservedSlots.append(position);
302 if (freeTiles_.removeOne(position))
303 temporarilyReservedSlots.append(position);
307 if (freeTiles_.removeOne(position))
308 temporarilyReservedSlots.append(position);
313 //spread ghosts in random free slots
315 for (int i=0; i < ghosts; i++)
317 QPointF * pPosition = findRandomFreeSlot();
319 //If there was no room no point to continue
320 if (pPosition == NULL)
323 QPixmap ghostPixmap(":/pix/aave.png");
324 QGraphicsPixmapItem * pGhost = addPixmap(ghostPixmap);
325 pGhost->setData(0,"ghost");
326 pGhost->setPos(*pPosition);
330 //return the slots occupied by moving items to free slots
331 freeTiles_.append(temporarilyReservedSlots);
333 //clear temp for the next round
334 temporarilyReservedSlots.clear();
337 QPointF* SeaScene::findRandomFreeSlot()
339 if (freeTiles_.isEmpty())
342 int index = qrand()%freeTiles_.size();
344 // qDebug() << index << " index";
345 return new QPointF (freeTiles_.takeAt(index));
349 void SeaScene::removeGhost(QGraphicsItem *pGhost)
351 removeItem(pGhost); //remove the item from scene
352 freeTiles_.append(pGhost->scenePos()); //add the item's position to free slots
355 if (ghostsLeft_ == 0)
357 emit allGhostsPicked();
358 // qDebug() << "All ghosts picked!";
362 void SeaScene::ghostsDropped(int ghosts)
364 ghostsLeft_ += ghosts;
366 spreadGhosts(ghosts);
369 void SeaScene::pause(bool paused)
371 // qDebug() << "pause pressed " << paused;
372 if (paused_ == paused)
379 // qDebug() << "starting to move again";
380 // emit fullscreenRequested(); fremantle specific (since no "show statusbar" action in harmattan version)
382 screenLitKeeper_.keepScreenLit(true);
384 pPausetextItem_->hide();
386 scoreCounter_.start();
388 autopauseTimer.start(); //Start counting towards autopause
393 // qDebug("about to stop movement");
395 screenLitKeeper_.keepScreenLit(false);
396 if (pPausetextItem_ != NULL)
398 // qDebug() << "about to show the pause text";
399 pPausetextItem_->show();
400 // qDebug() << "showing pause text";
402 // else qDebug() << "No pause text available";
404 levelScore_ += scoreCounter_.elapsed();
406 autopauseTimer.stop(); //No need to count toward autopause when already paused
410 void SeaScene::vibrationActivate(bool on)
412 emit vibrationActivated(on);
415 void SeaScene::handleScreenTapped()
418 //If the game is going just pause it
421 pPauseAction_->setChecked(true);
425 //If the game is paused and about box is shown, close it and show the pause text and menu again
429 if(pAboutBoxItem_->isVisible())
431 pAboutBoxItem_->hide();
432 pPausetextItem_->show();
437 //If the game is paused, check if the level completed item is shown
439 if (pLevelCompletedItem_)
441 if (pLevelCompletedItem_->isVisible())
443 pLevelCompletedItem_->hide();
444 restartLevel(); //Current level has already been set to the next one before showing the level completed item
445 pPauseAction_->setChecked(false); //unpause
450 //If the game is paused, check if the victory item is being shown
451 if(pVictoryCongratulationsItem_)
453 if (pVictoryCongratulationsItem_->isVisibleTo(NULL)) //returns visibility to scene
455 pVictoryCongratulationsItem_->hide();
457 pPauseAction_->setChecked(false); // unpause
463 //If the game is paused and no victory or about box, check if menu item was selected
465 QList<QGraphicsItem *> items = selectedItems();
467 //if nothing selected resume play
471 pPauseAction_->setChecked(false);
476 //If something was selected check if it was one of the menu items and act on it
477 //(Nothing else should be made selectable anyway)
481 QGraphicsItem* pItem = items.at(0); //Selecting an item brings here, thus only selecting one item should be possible
482 //... so we can just take the first one
484 //Selection is just used to get notice of a menu item being clicked, removed after use
489 //Act upon the selected item
492 if (pItem == pRestartGameItem_)
494 // qDebug() << "game restart requested";
496 pPauseAction_->setChecked(false); //unpause game
500 else if (pItem == pRestartLevelItem_)
502 // qDebug() << "Level restart requested";
504 pPauseAction_->setChecked(false); //unpause game
508 else if (pItem == pSettingsItem_)
510 pVibrateAction_->toggle();
513 settings.setValue("vibration",pVibrateAction_->isChecked());
515 QString text = pSettingsItem_->toHtml();
516 if (pVibrateAction_->isChecked())
517 text.replace(" on"," off"); //don't remove spaces or you get vibratioff...
519 text.replace(" off"," on");
520 pSettingsItem_->setHtml(text);
523 else if (pItem == pAboutItem_)
528 else if (pItem == pQuitItem_)
537 void SeaScene::createMenuItems()
541 font.setPixelSize(35);
545 pPausetextItem_ = new QGraphicsTextItem;
547 // This is for fremantle
548 // pPausetextItem_->setHtml("<font size = \"5\" color = darkorange> Game paused. Tap to continue.");
550 //Harmattan needs bigger font
551 pPausetextItem_->setHtml("<font size = \"7\" color = darkorange> Game paused. Tap to continue.");
554 pPausetextItem_->setZValue(1000);
555 pPausetextItem_->setPos(200,50);
556 addItem(pPausetextItem_);
557 pPausetextItem_->hide();
561 // This is for fremantle
562 // QString menufonthtml = "<font size = \"4\" color = darkorange>";
565 //Harmattan needs bigger font
566 QString menufonthtml = "<font size = \"6\" color = darkorange>";
569 pRestartGameItem_ = new QGraphicsTextItem;
570 pRestartGameItem_->setHtml(tr("Restart <br> game").prepend(menufonthtml));
571 prepareForMenu(pRestartGameItem_);
573 pRestartLevelItem_ = new QGraphicsTextItem;
574 pRestartLevelItem_->setHtml(tr("Restart <br> level").prepend(menufonthtml));
575 prepareForMenu(pRestartLevelItem_);
577 pSettingsItem_ = new QGraphicsTextItem;
578 QString vibraText(tr("Turn vibration <br> effects "));
580 if (pVibrateAction_->isChecked())
588 vibraText.append(statusText);
589 pSettingsItem_->setHtml(vibraText.prepend(menufonthtml));
590 prepareForMenu(pSettingsItem_);
592 pAboutItem_ = new QGraphicsTextItem;
593 pAboutItem_->setHtml(tr("About <br> game").prepend(menufonthtml));
594 prepareForMenu(pAboutItem_);
596 pQuitItem_ = new QGraphicsTextItem;
597 pQuitItem_->setHtml(tr("Quit <br> game").prepend(menufonthtml));
598 prepareForMenu(pQuitItem_);
602 void SeaScene::prepareForMenu(QGraphicsItem * pItem)
605 //Menu items have pause text item as their parent and are thus added to scene automatically
606 //They are also shown and hidden with it, resulting in the menu being visble when the game is paused
607 //Their coordinates are given relative to the parent.
610 pItem->setParentItem(pPausetextItem_);
611 pItem->setZValue(1000);
612 pItem->setFlag(QGraphicsItem::ItemIsSelectable);
614 pItem->setX(menuItemCount_++*160-150);
618 void SeaScene::about()
620 pPausetextItem_->hide();
621 pAboutBoxItem_->show();
625 void SeaScene::restartLevel()
630 setupMap(levelset_.getLevel(currentLevel_)); //getLevel() returns default constructor Level if index is invalid, so no risk of crash
632 scoreCounter_.start();
634 vibrationActivate(pVibrateAction_->isChecked()); //Vibration effects are lost without this
635 // qDebug() << pVibrateAction_->isChecked();
636 autopauseTimer.start(); //reset counting towards autopause
643 void SeaScene::nextLevel()
646 //get score for previous level
647 levelScore_ += scoreCounter_.elapsed();
648 totalScore_ += levelScore_;
649 int highscore = levelset_.getLevelHighScore(currentLevel_);
651 qDebug() << highscore;
655 if (levelScore_ >= highscore)
657 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);
660 else //New high score!
663 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);
664 levelset_.setLevelHighScore(currentLevel_,levelScore_);
667 //pause to show the highscore or victory screen
670 pPausetextItem_->hide();
673 //Go to the next level if available
676 if ( currentLevel_ < levelset_.numberOfLevels() )
679 pLevelCompletedItem_->setHtml(scoretext);
680 pLevelCompletedItem_->show();
686 int totalHighsore = levelset_.getTotalHighScore();
687 if (totalScore_ >= totalHighsore)
689 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));
691 else //new total high score
693 scoretext.append(tr("<br>Your total time %1.%2 s is<br>the new best time").arg(totalScore_/1000).arg((totalScore_%1000)/100));
694 levelset_.setTotalHighScore(totalScore_);
697 pVictoryScoreItem_->setHtml(scoretext);
698 pVictoryCongratulationsItem_->show();
703 void SeaScene::restartGame()
711 void SeaScene::forcePause()
713 //Pause without setting the pause action state
717 void SeaScene::softContinue()
719 //Continue if not being paused by the user
720 // Reverts forcePause()
722 pause(pPauseAction_->isChecked());
726 void SeaScene::createVictoryItems()
728 pVictoryCongratulationsItem_ = new QGraphicsTextItem;
729 pVictoryCongratulationsItem_->setHtml("<font size=\"7\" color = darkorange> <b> Victory!");
730 pVictoryCongratulationsItem_->hide();
731 pVictoryCongratulationsItem_->setPos(315,30);
732 pVictoryCongratulationsItem_->setZValue(1000);
733 addItem(pVictoryCongratulationsItem_);
736 //coordinates are relative to the parent
738 QGraphicsTextItem * pTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
739 pTextItem->setHtml("<font size=\"7\" color = darkorange> Congratulations!");
740 pTextItem->setPos(-50,80);
741 pTextItem->setZValue(1000);
743 QGraphicsTextItem * pMiddleTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
744 pMiddleTextItem->setHtml("<font size=\"7\" color = darkorange> You have saved all the ghosts.");
745 pMiddleTextItem->setPos(-145,120);
746 pMiddleTextItem->setZValue(1000);
749 pVictoryScoreItem_ = new QGraphicsTextItem(pVictoryCongratulationsItem_);
750 pVictoryScoreItem_->setPos(-50,180);
751 pMiddleTextItem->setZValue(1000);
752 //Text is set at usetime!
754 QGraphicsTextItem * pLowestTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
755 pLowestTextItem->setHtml("<font size=\"7\" color = darkorange> Tap to play again");
756 pLowestTextItem->setPos(-50,360);
757 pLowestTextItem->setZValue(1000);
761 void SeaScene::createAboutBoxItems()
763 pAboutBoxItem_ = new QGraphicsTextItem;
764 addItem(pAboutBoxItem_);
765 pAboutBoxItem_->setPos(25,50);
766 pAboutBoxItem_->setZValue(1000);
767 pAboutBoxItem_->hide();
769 pAboutBoxItem_->setHtml(tr("<font color = darkorange size = \"7\">"
770 "%1 <br> <font size = \"7\"> Version %2"
771 "<p><font size = \"6\"> Copyright 2011 Heli Hyvättinen"
772 "<p><font size = \"6\"> License: General Public License v2"
773 "<p><font size = \"5\"> Web: http://ghostsoverboard.garage.maemo.org/<br>"
774 "Bug Reports: <br> https://bugs.maemo.org/"
775 "enter_bug.cgi?product=Ghosts%20Overboard"
776 ).arg(QApplication::applicationName(),QApplication::applicationVersion()));
780 void SeaScene::setItemPointersNull()
782 pPausetextItem_ = NULL;
783 pRestartLevelItem_ = NULL;
784 pRestartGameItem_ = NULL;
785 pSettingsItem_ = NULL;
788 // pMinimizeItem_ = NULL; //Fremantle spesific
790 pAboutBoxItem_ = NULL;
791 pLevelCompletedItem_ = NULL;
792 pVictoryScoreItem_ = NULL;
796 void SeaScene::turnPauseOn()
798 pPauseAction_->setChecked(true);
803 void SeaScene::createLevelCompletedItems()
805 pLevelCompletedItem_ = new QGraphicsTextItem;
806 addItem(pLevelCompletedItem_);
807 pLevelCompletedItem_->setPos(240,100);
808 pLevelCompletedItem_->setZValue(1000);
809 pLevelCompletedItem_->hide();
810 //The text is set at usetime
812 QGraphicsTextItem * pTapForNextLevelItem = new QGraphicsTextItem(pLevelCompletedItem_);
813 pTapForNextLevelItem->setPos(-60,100);
814 pTapForNextLevelItem->setZValue(1000);
815 pTapForNextLevelItem->setHtml("<font size=\"7\" color = darkorange>Tap to start the next level");
818 void SeaScene::resourcesAvailable()
820 qDebug() << "Resources available";
823 void SeaScene::resourcesLost()
825 qDebug() << "Resources lost";