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);
91 pVibrateAction_ = new QAction(tr("Vibration effects"),this);
92 pVibrateAction_->setCheckable(true);
93 connect(pVibrateAction_,SIGNAL(toggled(bool)),this,SLOT(vibrationActivate(bool)));
95 pVibrateAction_->setChecked(settings.value("vibration",false).toBool());
98 pPauseAction_ = new QAction(tr("Pause"),this);
99 pPauseAction_->setCheckable(true);
100 connect(pPauseAction_,SIGNAL(toggled(bool)),this,SLOT(pause(bool)));
103 autopauseTimer.setSingleShot(true);
104 autopauseTimer.setInterval(15*60*1000);
105 connect(&autopauseTimer,SIGNAL(timeout()),this,SLOT(turnPauseOn()));
107 vibrationAllowed_ = false;
108 pResourceSet_ = new ResourcePolicy::ResourceSet("game",this);
109 ResourcePolicy::VibraResource * pVibraResource = new ResourcePolicy::VibraResource();
110 pVibraResource->setOptional(false); //The only resource of the set, so no sense for it to be optional
111 pResourceSet_->addResourceObject(pVibraResource);
113 connect(pResourceSet_,SIGNAL(resourcesGranted(const QList< ResourcePolicy::ResourceType >)),this,SLOT(resourcesAvailable()));
114 connect(pResourceSet_,SIGNAL(lostResources()),this,SLOT(resourcesLost()));
116 //To test whether resources were succesfully asked but not given
117 connect(pResourceSet_,SIGNAL(resourcesDenied()),this,SLOT(resourcesLost()));
118 pResourceSet_->setAlwaysReply();
120 pResourceSet_->acquire();
124 void SeaScene::setupMap(int ghosts, int rocks, int octopuses, int octopusSpeed)
130 setItemPointersNull();
134 createAboutBoxItems();
135 createVictoryItems();
137 createLevelCompletedItems();
140 //empty the list of moving items
142 movingItems_.clear();
144 //empty the list of free slots
147 //fill the list of free slots
149 int numberOfXTiles = width() / 40;
150 int numberOfYTiles = height() /40;
152 // qDebug() << numberOfXTiles << " slots in x direction";
153 // qDebug() << numberOfYTiles << " slots in y rirection";
155 for (int i = 0; i < numberOfXTiles; i++ )
157 for (int j = 0; j < numberOfYTiles; j++)
159 freeTiles_.append(QPointF(i*40,j*40));
166 for (int i = 0; i < rocks; i++)
168 QPointF * pPosition = findRandomFreeSlot();
170 //If there was no room no point to continue
171 if (pPosition == NULL)
174 QPixmap rockPixmap (":/pix/kari.png");
175 QGraphicsPixmapItem * pRock = addPixmap(rockPixmap);
176 pRock->setData(0,"rock");
177 pRock->setPos(*pPosition);
184 ghostsLeft_ = ghosts;
185 spreadGhosts(ghosts);
189 //spread the octopuses
191 QList <Octopus*> octopusList;
193 for (int i=0; i < octopuses; i++)
195 QPointF * pPosition = findRandomFreeSlot();
197 //If there was no room no point to continue
198 if (pPosition == NULL)
201 QPixmap octopusPixmap (":/pix/tursas.png");
202 Octopus * pOctopus = new Octopus(octopusPixmap,octopusSpeed);
203 pOctopus->setData(0,"octopus");
204 pOctopus->setPos(*pPosition);
206 pOctopus->startMoving();
207 movingItems_.append(pOctopus);
208 connect(this,SIGNAL(pauseOn()),pOctopus,SLOT(stopMoving()));
209 connect(this,SIGNAL(pauseOff()),pOctopus,SLOT(startMoving()));
210 octopusList.append(pOctopus);
218 QPointF * pPosition = findRandomFreeSlot();
219 if (pPosition == NULL)
221 // Game cannot begin without a free position for ship, so give an error message and return
223 QMessageBox::critical(NULL,"Error! Too many objects on screen","No free space to place the ship. The game cannot start. Please choose another level.");
227 QList<QPixmap> shipImages;
228 shipImages.append(QPixmap(":/pix/laiva.png"));
229 shipImages.append(QPixmap(":/pix/laiva_1aave.png"));
230 shipImages.append(QPixmap(":/pix/laiva_2aave.png"));
231 shipImages.append(QPixmap(":/pix/laiva_3aave.png"));
232 shipImages.append(QPixmap(":/pix/laiva_4aave.png"));
233 shipImages.append(QPixmap(":/pix/laiva_5aave.png"));
234 shipImages.append(QPixmap(":/pix/laiva_6aave.png"));
235 shipImages.append(QPixmap(":/pix/laiva_7aave.png"));
236 shipImages.append(QPixmap(":/pix/laiva_8aave.png"));
237 shipImages.append(QPixmap(":/pix/laiva_9aave.png"));
238 shipImages.append(QPixmap(":/pix/laiva_10aave.png"));
240 Ship * pShip = new Ship (shipImages);
241 pShip->setData(0,"ship");
242 pShip->setPos(*pPosition);
244 connect(pShip,SIGNAL(pickingGhost(QGraphicsItem*)),this, SLOT(removeGhost(QGraphicsItem*)) );
245 connect(pShip,SIGNAL(droppingGhosts(int)),this,SLOT(ghostsDropped(int)));
246 connect(this,SIGNAL(vibrationActivated(bool)),pShip,SLOT(setVibrationActivate(bool)));
247 if (vibrationAllowed_)
248 pShip->allowVibration(); //Vibration is disallowed by default so only allowing needs to be done explicitly
249 connect(pResourceSet_,SIGNAL(resourcesGranted(const QList< ResourcePolicy::ResourceType >)),pShip,SLOT(allowVibration()));
250 connect(pResourceSet_,SIGNAL(lostResources()),pShip,SLOT(disallowVibration()));
251 pShip->startMoving();
252 movingItems_.append(pShip);
253 connect(this,SIGNAL(pauseOn()),pShip,SLOT(stopMoving()));
254 connect(this,SIGNAL(pauseOff()),pShip,SLOT(startMoving()));
255 foreach (Octopus* pOctopus, octopusList)
257 connect(pOctopus,SIGNAL(droppingGhosts()),pShip,SLOT(dropAllGhosts()));
262 void SeaScene::setupMap(Level level)
264 setupMap(level.getNumberOfGhosts(),level.getNumberOfRocks(),level.getNumberOfOctopuses(),level.getOctopusSpeed());
267 void SeaScene::spreadGhosts(int ghosts)
271 //the octopuses and the ship may have moved from their original positions,
272 //so the list of free slots must be adjusted to exclude their current positions
274 QList<QPointF> temporarilyReservedSlots;
276 foreach (QGraphicsItem* pItem, movingItems_)
280 // qDebug() << "NULL item in movingItems_";
284 //round x and y down to fit the slot size
294 QPointF position (x,y);
296 //remove the tiles (potentially) occupied by the item from free slots and place in temp list if was in the list before
298 if (freeTiles_.removeOne(position))
299 temporarilyReservedSlots.append(position);
304 if (freeTiles_.removeOne(position))
305 temporarilyReservedSlots.append(position);
309 if (freeTiles_.removeOne(position))
310 temporarilyReservedSlots.append(position);
314 if (freeTiles_.removeOne(position))
315 temporarilyReservedSlots.append(position);
320 //spread ghosts in random free slots
322 for (int i=0; i < ghosts; i++)
324 QPointF * pPosition = findRandomFreeSlot();
326 //If there was no room no point to continue
327 if (pPosition == NULL)
330 QPixmap ghostPixmap(":/pix/aave.png");
331 QGraphicsPixmapItem * pGhost = addPixmap(ghostPixmap);
332 pGhost->setData(0,"ghost");
333 pGhost->setPos(*pPosition);
337 //return the slots occupied by moving items to free slots
338 freeTiles_.append(temporarilyReservedSlots);
340 //clear temp for the next round
341 temporarilyReservedSlots.clear();
344 QPointF* SeaScene::findRandomFreeSlot()
346 if (freeTiles_.isEmpty())
349 int index = qrand()%freeTiles_.size();
351 // qDebug() << index << " index";
352 return new QPointF (freeTiles_.takeAt(index));
356 void SeaScene::removeGhost(QGraphicsItem *pGhost)
358 removeItem(pGhost); //remove the item from scene
359 freeTiles_.append(pGhost->scenePos()); //add the item's position to free slots
362 if (ghostsLeft_ == 0)
364 emit allGhostsPicked();
365 // qDebug() << "All ghosts picked!";
369 void SeaScene::ghostsDropped(int ghosts)
371 ghostsLeft_ += ghosts;
373 spreadGhosts(ghosts);
376 void SeaScene::pause(bool paused)
378 // qDebug() << "pause pressed " << paused;
379 if (paused_ == paused)
386 // qDebug() << "starting to move again";
387 // emit fullscreenRequested(); fremantle specific (since no "show statusbar" action in harmattan version)
389 screenLitKeeper_.keepScreenLit(true);
391 pPausetextItem_->hide();
393 scoreCounter_.start();
395 autopauseTimer.start(); //Start counting towards autopause
400 // qDebug("about to stop movement");
402 screenLitKeeper_.keepScreenLit(false);
403 if (pPausetextItem_ != NULL)
405 // qDebug() << "about to show the pause text";
406 pPausetextItem_->show();
407 // qDebug() << "showing pause text";
409 // else qDebug() << "No pause text available";
411 levelScore_ += scoreCounter_.elapsed();
413 autopauseTimer.stop(); //No need to count toward autopause when already paused
417 void SeaScene::vibrationActivate(bool on)
419 emit vibrationActivated(on);
422 void SeaScene::handleScreenTapped()
425 //If the game is going just pause it
428 pPauseAction_->setChecked(true);
432 //If the game is paused and about box is shown, close it and show the pause text and menu again
436 if(pAboutBoxItem_->isVisible())
438 pAboutBoxItem_->hide();
439 pPausetextItem_->show();
444 //If the game is paused, check if the level completed item is shown
446 if (pLevelCompletedItem_)
448 if (pLevelCompletedItem_->isVisible())
450 pLevelCompletedItem_->hide();
451 restartLevel(); //Current level has already been set to the next one before showing the level completed item
452 pPauseAction_->setChecked(false); //unpause
457 //If the game is paused, check if the victory item is being shown
458 if(pVictoryCongratulationsItem_)
460 if (pVictoryCongratulationsItem_->isVisibleTo(NULL)) //returns visibility to scene
462 pVictoryCongratulationsItem_->hide();
464 pPauseAction_->setChecked(false); // unpause
470 //If the game is paused and no victory or about box, check if menu item was selected
472 QList<QGraphicsItem *> items = selectedItems();
474 //if nothing selected resume play
478 pPauseAction_->setChecked(false);
483 //If something was selected check if it was one of the menu items and act on it
484 //(Nothing else should be made selectable anyway)
488 QGraphicsItem* pItem = items.at(0); //Selecting an item brings here, thus only selecting one item should be possible
489 //... so we can just take the first one
491 //Selection is just used to get notice of a menu item being clicked, removed after use
496 //Act upon the selected item
499 if (pItem == pRestartGameItem_)
501 // qDebug() << "game restart requested";
503 pPauseAction_->setChecked(false); //unpause game
507 else if (pItem == pRestartLevelItem_)
509 // qDebug() << "Level restart requested";
511 pPauseAction_->setChecked(false); //unpause game
515 else if (pItem == pSettingsItem_)
517 pVibrateAction_->toggle();
520 settings.setValue("vibration",pVibrateAction_->isChecked());
522 QString text = pSettingsItem_->toHtml();
523 if (pVibrateAction_->isChecked())
524 text.replace(" on"," off"); //don't remove spaces or you get vibratioff...
526 text.replace(" off"," on");
527 pSettingsItem_->setHtml(text);
530 else if (pItem == pAboutItem_)
535 else if (pItem == pQuitItem_)
544 void SeaScene::createMenuItems()
548 font.setPixelSize(35);
552 pPausetextItem_ = new QGraphicsTextItem;
554 // This is for fremantle
555 // pPausetextItem_->setHtml("<font size = \"5\" color = darkorange> Game paused. Tap to continue.");
557 //Harmattan needs bigger font
558 pPausetextItem_->setHtml("<font size = \"7\" color = darkorange> Game paused. Tap to continue.");
561 pPausetextItem_->setZValue(1000);
562 pPausetextItem_->setPos(200,50);
563 addItem(pPausetextItem_);
564 pPausetextItem_->hide();
568 // This is for fremantle
569 // QString menufonthtml = "<font size = \"4\" color = darkorange>";
572 //Harmattan needs bigger font
573 QString menufonthtml = "<font size = \"6\" color = darkorange>";
576 pRestartGameItem_ = new QGraphicsTextItem;
577 pRestartGameItem_->setHtml(tr("Restart <br> game").prepend(menufonthtml));
578 prepareForMenu(pRestartGameItem_);
580 pRestartLevelItem_ = new QGraphicsTextItem;
581 pRestartLevelItem_->setHtml(tr("Restart <br> level").prepend(menufonthtml));
582 prepareForMenu(pRestartLevelItem_);
584 pSettingsItem_ = new QGraphicsTextItem;
585 QString vibraText(tr("Turn vibration <br> effects "));
587 if (pVibrateAction_->isChecked())
595 vibraText.append(statusText);
596 pSettingsItem_->setHtml(vibraText.prepend(menufonthtml));
597 prepareForMenu(pSettingsItem_);
599 pAboutItem_ = new QGraphicsTextItem;
600 pAboutItem_->setHtml(tr("About <br> game").prepend(menufonthtml));
601 prepareForMenu(pAboutItem_);
603 pQuitItem_ = new QGraphicsTextItem;
604 pQuitItem_->setHtml(tr("Quit <br> game").prepend(menufonthtml));
605 prepareForMenu(pQuitItem_);
609 void SeaScene::prepareForMenu(QGraphicsItem * pItem)
612 //Menu items have pause text item as their parent and are thus added to scene automatically
613 //They are also shown and hidden with it, resulting in the menu being visble when the game is paused
614 //Their coordinates are given relative to the parent.
617 pItem->setParentItem(pPausetextItem_);
618 pItem->setZValue(1000);
619 pItem->setFlag(QGraphicsItem::ItemIsSelectable);
621 pItem->setX(menuItemCount_++*160-150);
625 void SeaScene::about()
627 pPausetextItem_->hide();
628 pAboutBoxItem_->show();
632 void SeaScene::restartLevel()
637 setupMap(levelset_.getLevel(currentLevel_)); //getLevel() returns default constructor Level if index is invalid, so no risk of crash
639 scoreCounter_.start();
641 vibrationActivate(pVibrateAction_->isChecked()); //Vibration effects are lost without this
642 // qDebug() << pVibrateAction_->isChecked();
644 autopauseTimer.start(); //reset counting towards autopause
651 void SeaScene::nextLevel()
654 //get score for previous level
655 levelScore_ += scoreCounter_.elapsed();
656 totalScore_ += levelScore_;
657 int highscore = levelset_.getLevelHighScore(currentLevel_);
659 qDebug() << highscore;
663 if (levelScore_ >= highscore)
665 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);
668 else //New high score!
671 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);
672 levelset_.setLevelHighScore(currentLevel_,levelScore_);
675 //pause to show the highscore or victory screen
678 pPausetextItem_->hide();
681 //Go to the next level if available
684 if ( currentLevel_ < levelset_.numberOfLevels() )
687 pLevelCompletedItem_->setHtml(scoretext);
688 pLevelCompletedItem_->show();
694 int totalHighsore = levelset_.getTotalHighScore();
695 if (totalScore_ >= totalHighsore)
697 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));
699 else //new total high score
701 scoretext.append(tr("<br>Your total time %1.%2 s is<br>the new best time").arg(totalScore_/1000).arg((totalScore_%1000)/100));
702 levelset_.setTotalHighScore(totalScore_);
705 pVictoryScoreItem_->setHtml(scoretext);
706 pVictoryCongratulationsItem_->show();
711 void SeaScene::restartGame()
719 void SeaScene::forcePause()
721 //Pause without setting the pause action state
725 void SeaScene::softContinue()
727 //Continue if not being paused by the user
728 // Reverts forcePause()
730 pause(pPauseAction_->isChecked());
734 void SeaScene::createVictoryItems()
736 pVictoryCongratulationsItem_ = new QGraphicsTextItem;
737 pVictoryCongratulationsItem_->setHtml("<font size=\"7\" color = darkorange> <b> Victory!");
738 pVictoryCongratulationsItem_->hide();
739 pVictoryCongratulationsItem_->setPos(315,30);
740 pVictoryCongratulationsItem_->setZValue(1000);
741 addItem(pVictoryCongratulationsItem_);
744 //coordinates are relative to the parent
746 QGraphicsTextItem * pTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
747 pTextItem->setHtml("<font size=\"7\" color = darkorange> Congratulations!");
748 pTextItem->setPos(-50,80);
749 pTextItem->setZValue(1000);
751 QGraphicsTextItem * pMiddleTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
752 pMiddleTextItem->setHtml("<font size=\"7\" color = darkorange> You have saved all the ghosts.");
753 pMiddleTextItem->setPos(-145,120);
754 pMiddleTextItem->setZValue(1000);
757 pVictoryScoreItem_ = new QGraphicsTextItem(pVictoryCongratulationsItem_);
758 pVictoryScoreItem_->setPos(-50,180);
759 pMiddleTextItem->setZValue(1000);
760 //Text is set at usetime!
762 QGraphicsTextItem * pLowestTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
763 pLowestTextItem->setHtml("<font size=\"7\" color = darkorange> Tap to play again");
764 pLowestTextItem->setPos(-50,360);
765 pLowestTextItem->setZValue(1000);
769 void SeaScene::createAboutBoxItems()
771 pAboutBoxItem_ = new QGraphicsTextItem;
772 addItem(pAboutBoxItem_);
773 pAboutBoxItem_->setPos(25,50);
774 pAboutBoxItem_->setZValue(1000);
775 pAboutBoxItem_->hide();
777 pAboutBoxItem_->setHtml(tr("<font color = darkorange size = \"7\">"
778 "%1 <br> <font size = \"7\"> Version %2"
779 "<p><font size = \"6\"> Copyright 2011 Heli Hyvättinen"
780 "<p><font size = \"6\"> License: General Public License v2"
781 "<p><font size = \"5\"> Web: http://ghostsoverboard.garage.maemo.org/<br>"
782 "Bug Reports: <br> https://bugs.maemo.org/"
783 "enter_bug.cgi?product=Ghosts%20Overboard"
784 ).arg(QApplication::applicationName(),QApplication::applicationVersion()));
788 void SeaScene::setItemPointersNull()
790 pPausetextItem_ = NULL;
791 pRestartLevelItem_ = NULL;
792 pRestartGameItem_ = NULL;
793 pSettingsItem_ = NULL;
796 // pMinimizeItem_ = NULL; //Fremantle spesific
798 pAboutBoxItem_ = NULL;
799 pLevelCompletedItem_ = NULL;
800 pVictoryScoreItem_ = NULL;
804 void SeaScene::turnPauseOn()
806 pPauseAction_->setChecked(true);
811 void SeaScene::createLevelCompletedItems()
813 pLevelCompletedItem_ = new QGraphicsTextItem;
814 addItem(pLevelCompletedItem_);
815 pLevelCompletedItem_->setPos(240,100);
816 pLevelCompletedItem_->setZValue(1000);
817 pLevelCompletedItem_->hide();
818 //The text is set at usetime
820 QGraphicsTextItem * pTapForNextLevelItem = new QGraphicsTextItem(pLevelCompletedItem_);
821 pTapForNextLevelItem->setPos(-60,100);
822 pTapForNextLevelItem->setZValue(1000);
823 pTapForNextLevelItem->setHtml("<font size=\"7\" color = darkorange>Tap to start the next level");
826 void SeaScene::resourcesAvailable()
828 qDebug() << "Resources available";
829 vibrationAllowed_ = true;
832 void SeaScene::resourcesLost()
834 qDebug() << "Resources lost";
835 vibrationAllowed_ = false;