1 /**************************************************************************
2 Ghosts Overboard - a game for Maemo 5
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
64 //Setup the level list
66 QList<Level> levelList;
68 levelList.append(level1);
69 Level level2(5,10,2,50);
70 levelList.append(level2);
71 Level level3(5,15,2,50);
72 levelList.append(level3);
73 Level level4(5,15,4,50);
74 levelList.append(level4);
75 Level level5(5,15,5,100);
76 levelList.append(level5);
78 Levelset set ("Original",levelList);
80 availableLevelsets_.append(set);
86 //Create another set of levels and place it in the available levelsets list
88 Level set2level1(8,15,4,50);
89 levelList.append(set2level1);
90 Level set2level2(8,20,4,50);
91 levelList.append(set2level2);
92 Level set2level3(8,15,5,100);
93 levelList.append(set2level3);
94 Level set2level4(8,20,6,100);
95 levelList.append(set2level4);
96 Level set2level5(8,20,6,150);
97 levelList.append(set2level5);
99 Levelset set2("Difficult",levelList);
100 availableLevelsets_.append(set2);
104 connect(this,SIGNAL(allGhostsPicked()),this,SLOT(nextLevel()));
107 pVibrateAction_ = new QAction(tr("Vibration effects"),this);
108 pVibrateAction_->setCheckable(true);
109 connect(pVibrateAction_,SIGNAL(toggled(bool)),this,SLOT(vibrationActivate(bool)));
111 pVibrateAction_->setChecked(settings.value("vibration",false).toBool());
114 pPauseAction_ = new QAction(tr("Pause"),this);
115 pPauseAction_->setCheckable(true);
116 connect(pPauseAction_,SIGNAL(toggled(bool)),this,SLOT(pause(bool)));
119 deviceLockPollTimer_.setInterval(20*60);
120 connect(&deviceLockPollTimer_,SIGNAL(timeout()),this,SLOT(pollDeviceLocked()));
121 deviceLockPollTimer_.start();
124 autopauseTimer.setSingleShot(true);
125 autopauseTimer.setInterval(15*60*1000);
126 connect(&autopauseTimer,SIGNAL(timeout()),this,SLOT(turnPauseOn()));
131 void SeaScene::setupMap(int ghosts, int rocks, int octopuses, int octopusSpeed)
137 setItemPointersNull();
141 createAboutBoxItems();
143 createVictoryItems();
145 createLevelCompletedItems();
148 //empty the list of moving items
150 movingItems_.clear();
152 //empty the list of free slots
155 //fill the list of free slots
157 int numberOfXTiles = width() / 40;
158 int numberOfYTiles = height() /40;
160 // qDebug() << numberOfXTiles << " slots in x direction";
161 // qDebug() << numberOfYTiles << " slots in y rirection";
163 for (int i = 0; i < numberOfXTiles; i++ )
165 for (int j = 0; j < numberOfYTiles; j++)
167 freeTiles_.append(QPointF(i*40,j*40));
174 for (int i = 0; i < rocks; i++)
176 QPointF * pPosition = findRandomFreeSlot();
178 //If there was no room no point to continue
179 if (pPosition == NULL)
182 QPixmap rockPixmap (":/pix/kari.png");
183 QGraphicsPixmapItem * pRock = addPixmap(rockPixmap);
184 pRock->setData(0,"rock");
185 pRock->setPos(*pPosition);
192 ghostsLeft_ = ghosts;
193 spreadGhosts(ghosts);
197 //spread the octopuses
199 QList <Octopus*> octopusList;
201 for (int i=0; i < octopuses; i++)
203 QPointF * pPosition = findRandomFreeSlot();
205 //If there was no room no point to continue
206 if (pPosition == NULL)
209 QPixmap octopusPixmap (":/pix/tursas.png");
210 Octopus * pOctopus = new Octopus(octopusPixmap,octopusSpeed);
211 pOctopus->setData(0,"octopus");
212 pOctopus->setPos(*pPosition);
214 pOctopus->startMoving();
215 movingItems_.append(pOctopus);
216 connect(this,SIGNAL(pauseOn()),pOctopus,SLOT(stopMoving()));
217 connect(this,SIGNAL(pauseOff()),pOctopus,SLOT(startMoving()));
218 octopusList.append(pOctopus);
226 QPointF * pPosition = findRandomFreeSlot();
227 if (pPosition == NULL)
229 // Game cannot begin without a free position for ship, so give an error message and return
231 QMessageBox::critical(NULL,"Error! Too many objects on screen","No free space to place the ship. The game cannot start. Please choose another level.");
235 QList<QPixmap> shipImages;
236 shipImages.append(QPixmap(":/pix/laiva.png"));
237 shipImages.append(QPixmap(":/pix/laiva_1aave.png"));
238 shipImages.append(QPixmap(":/pix/laiva_2aave.png"));
239 shipImages.append(QPixmap(":/pix/laiva_3aave.png"));
240 shipImages.append(QPixmap(":/pix/laiva_4aave.png"));
241 shipImages.append(QPixmap(":/pix/laiva_5aave.png"));
242 shipImages.append(QPixmap(":/pix/laiva_6aave.png"));
243 shipImages.append(QPixmap(":/pix/laiva_7aave.png"));
244 shipImages.append(QPixmap(":/pix/laiva_8aave.png"));
245 shipImages.append(QPixmap(":/pix/laiva_9aave.png"));
246 shipImages.append(QPixmap(":/pix/laiva_10aave.png"));
248 Ship * pShip = new Ship (shipImages);
249 pShip->setData(0,"ship");
250 pShip->setPos(*pPosition);
252 connect(pShip,SIGNAL(pickingGhost(QGraphicsItem*)),this, SLOT(removeGhost(QGraphicsItem*)) );
253 connect(pShip,SIGNAL(droppingGhosts(int)),this,SLOT(ghostsDropped(int)));
254 connect(this,SIGNAL(vibrationActivated(bool)),pShip,SLOT(setVibrationActivate(bool)));
255 pShip->startMoving();
256 movingItems_.append(pShip);
257 connect(this,SIGNAL(pauseOn()),pShip,SLOT(stopMoving()));
258 connect(this,SIGNAL(pauseOff()),pShip,SLOT(startMoving()));
259 foreach (Octopus* pOctopus, octopusList)
261 connect(pOctopus,SIGNAL(droppingGhosts()),pShip,SLOT(dropAllGhosts()));
266 void SeaScene::setupMap(Level level)
268 setupMap(level.getNumberOfGhosts(),level.getNumberOfRocks(),level.getNumberOfOctopuses(),level.getOctopusSpeed());
271 void SeaScene::spreadGhosts(int ghosts)
275 //the octopuses and the ship may have moved from their original positions,
276 //so the list of free slots must be adjusted to exclude their current positions
278 QList<QPointF> temporarilyReservedSlots;
280 foreach (QGraphicsItem* pItem, movingItems_)
284 // qDebug() << "NULL item in movingItems_";
288 //round x and y down to fit the slot size
298 QPointF position (x,y);
300 //remove the tiles (potentially) occupied by the item from free slots and place in temp list if was in the list before
302 if (freeTiles_.removeOne(position))
303 temporarilyReservedSlots.append(position);
308 if (freeTiles_.removeOne(position))
309 temporarilyReservedSlots.append(position);
313 if (freeTiles_.removeOne(position))
314 temporarilyReservedSlots.append(position);
318 if (freeTiles_.removeOne(position))
319 temporarilyReservedSlots.append(position);
324 //spread ghosts in random free slots
326 for (int i=0; i < ghosts; i++)
328 QPointF * pPosition = findRandomFreeSlot();
330 //If there was no room no point to continue
331 if (pPosition == NULL)
334 QPixmap ghostPixmap(":/pix/aave.png");
335 QGraphicsPixmapItem * pGhost = addPixmap(ghostPixmap);
336 pGhost->setData(0,"ghost");
337 pGhost->setPos(*pPosition);
341 //return the slots occupied by moving items to free slots
342 freeTiles_.append(temporarilyReservedSlots);
344 //clear temp for the next round
345 temporarilyReservedSlots.clear();
348 QPointF* SeaScene::findRandomFreeSlot()
350 if (freeTiles_.isEmpty())
353 int index = qrand()%freeTiles_.size();
355 // qDebug() << index << " index";
356 return new QPointF (freeTiles_.takeAt(index));
360 void SeaScene::removeGhost(QGraphicsItem *pGhost)
362 removeItem(pGhost); //remove the item from scene
363 freeTiles_.append(pGhost->scenePos()); //add the item's position to free slots
366 if (ghostsLeft_ == 0)
368 emit allGhostsPicked();
369 // qDebug() << "All ghosts picked!";
373 void SeaScene::ghostsDropped(int ghosts)
375 ghostsLeft_ += ghosts;
377 spreadGhosts(ghosts);
380 void SeaScene::pause(bool paused)
382 // qDebug() << "pause pressed " << paused;
383 if (paused_ == paused)
390 // qDebug() << "starting to move again";
391 emit fullscreenRequested();
393 screenLitKeeper_.keepScreenLit(true);
395 pPausetextItem_->hide();
397 scoreCounter_.start();
399 autopauseTimer.start(); //Start counting towards autopause
400 deviceLockPollTimer_.start(); //Start polling whether device is locked
405 // qDebug("about to stop movement");
407 screenLitKeeper_.keepScreenLit(false);
408 if (pPausetextItem_ != NULL)
410 // qDebug() << "about to show the pause text";
411 pPausetextItem_->show();
412 // qDebug() << "showing pause text";
414 // else qDebug() << "No pause text available";
416 levelScore_ += scoreCounter_.elapsed();
418 autopauseTimer.stop(); //No need to count toward autopause when already paused
419 deviceLockPollTimer_.stop(); //No need to check for unlock as no unpause anyway
423 void SeaScene::vibrationActivate(bool on)
425 emit vibrationActivated(on);
428 void SeaScene::handleScreenTapped()
431 //If the game is going just pause it
434 pPauseAction_->setChecked(true);
438 //If the game is paused and about box is shown, close it and show the pause text and menu again
442 if(pAboutBoxItem_->isVisible())
444 pAboutBoxItem_->hide();
445 pPausetextItem_->show();
450 //If the game is paused, check if the level completed item is shown
452 if (pLevelCompletedItem_)
454 if (pLevelCompletedItem_->isVisible())
456 pLevelCompletedItem_->hide();
457 restartLevel(); //Current level has already been set to the next one before showing the level completed item
458 pPauseAction_->setChecked(false); //unpause
463 //If the game is paused, check if the victory item is being shown
464 if(pVictoryCongratulationsItem_)
466 if (pVictoryCongratulationsItem_->isVisibleTo(NULL)) //returns visibility to scene
468 pVictoryCongratulationsItem_->hide();
470 pPauseAction_->setChecked(false); // unpause
476 //If the game is paused and no victory, check if menu item was selected
478 QList<QGraphicsItem *> items = selectedItems();
480 //if nothing selected resume play
484 pPauseAction_->setChecked(false);
489 //If something was selected check if it was one of the menu items and act on it
490 //(Nothing else should be made selectable anyway)
494 QGraphicsItem* pItem = items.at(0); //Selecting an item brings here, thus only selecting one item should be possible
495 //... so we can just take the first one
497 //Selection is just used to get notice of a menu item being clicked, removed after use
502 //Act upon the selected item
505 if (pItem == pRestartGameItem_)
507 // qDebug() << "game restart requested";
509 pPauseAction_->setChecked(false); //unpause game
513 else if (pItem == pRestartLevelItem_)
515 // qDebug() << "Level restart requested";
517 pPauseAction_->setChecked(false); //unpause game
521 else if (pItem == pSettingsItem_)
523 pVibrateAction_->toggle();
526 settings.setValue("vibration",pVibrateAction_->isChecked());
528 QString text = pSettingsItem_->toHtml();
529 if (pVibrateAction_->isChecked())
530 text.replace(" on"," off"); //don't remove spaces or you get vibratioff...
532 text.replace(" off"," on");
533 pSettingsItem_->setHtml(text);
536 else if (pItem == pAboutItem_)
541 else if(pItem == pMinimizeItem_)
543 emit minimizeRequested();
546 else if (pItem == pQuitItem_)
554 void SeaScene::createMenuItems()
558 font.setPixelSize(35);
562 pPausetextItem_ = new QGraphicsTextItem;
563 pPausetextItem_->setHtml("<font size = \"5\" color = darkorange> Game paused. Tap to continue.");
564 pPausetextItem_->setZValue(1000);
565 pPausetextItem_->setPos(165,50);
566 addItem(pPausetextItem_);
567 pPausetextItem_->hide();
571 QString menufonthtml = "<font size = \"4\" color = darkorange>";
573 pRestartGameItem_ = new QGraphicsTextItem;
574 pRestartGameItem_->setHtml(tr("Restart <br> game").prepend(menufonthtml));
575 prepareForMenu(pRestartGameItem_);
577 pRestartLevelItem_ = new QGraphicsTextItem;
578 pRestartLevelItem_->setHtml(tr("Restart <br> level").prepend(menufonthtml));
579 prepareForMenu(pRestartLevelItem_);
581 pSettingsItem_ = new QGraphicsTextItem;
582 QString vibraText(tr("Turn vibration <br> effects "));
584 if (pVibrateAction_->isChecked())
592 vibraText.append(statusText);
593 pSettingsItem_->setHtml(vibraText.prepend(menufonthtml));
594 prepareForMenu(pSettingsItem_);
596 pAboutItem_ = new QGraphicsTextItem;
597 pAboutItem_->setHtml(tr("About <br> game").prepend(menufonthtml));
598 prepareForMenu(pAboutItem_);
600 pMinimizeItem_ = new QGraphicsTextItem;
601 pMinimizeItem_->setHtml(tr("Show <br> status bar").prepend(menufonthtml));
602 prepareForMenu(pMinimizeItem_);
604 pQuitItem_ = new QGraphicsTextItem;
605 pQuitItem_->setHtml(tr("Quit <br> game").prepend(menufonthtml));
606 prepareForMenu(pQuitItem_);
610 void SeaScene::prepareForMenu(QGraphicsItem * pItem)
613 //Menu items have pause text item as their parent and are thus added to scene automatically
614 //They are also shown and hidden with it, resulting in the menu being visble when the game is paused
615 //Their coordinates are given relative to the parent.
622 pItem->setParentItem(pPausetextItem_);
623 pItem->setZValue(1000);
624 pItem->setFlag(QGraphicsItem::ItemIsSelectable);
626 int row = menuItemCount_/(itemsPerRow);
627 pItem->setY(150+row*120);
628 pItem->setX(((menuItemCount_%(itemsPerRow))*180+5));
634 void SeaScene::about()
636 pPausetextItem_->hide();
637 pAboutBoxItem_->show();
641 void SeaScene::restartLevel()
646 setupMap(levelset_.getLevel(currentLevel_)); //getLevel() returns default constructor Level if index is invalid, so no risk of crash
648 scoreCounter_.start();
650 vibrationActivate(pVibrateAction_->isChecked()); //Vibration effects are lost without this
651 // qDebug() << pVibrateAction_->isChecked();
652 autopauseTimer.start(); //reset counting towards autopause
659 void SeaScene::nextLevel()
662 //get score for previous level
663 levelScore_ += scoreCounter_.elapsed();
664 totalScore_ += levelScore_;
665 int highscore = levelset_.getLevelHighScore(currentLevel_);
667 qDebug() << highscore;
671 if (levelScore_ >= highscore)
673 scoretext = tr("<font size=\"5\" 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);
676 else //New high score!
679 scoretext = tr("<font size=\"5\" color = darkorange>Your time %1.%2 s is<br>the new best time!").arg(levelScore_/1000).arg((levelScore_%1000)/100);
680 levelset_.setLevelHighScore(currentLevel_,levelScore_);
683 //pause to show the highscore or victory screen
686 pPausetextItem_->hide();
689 //Go to the next level if available
692 if ( currentLevel_ < levelset_.numberOfLevels() )
695 pLevelCompletedItem_->setHtml(scoretext);
696 pLevelCompletedItem_->show();
702 int totalHighsore = levelset_.getTotalHighScore();
703 if (totalScore_ >= totalHighsore)
705 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));
707 else //new total high score
709 scoretext.append(tr("<br>Your total time %1.%2 s is<br>the new best time").arg(totalScore_/1000).arg((totalScore_%1000)/100));
710 levelset_.setTotalHighScore(totalScore_);
713 pVictoryScoreItem_->setHtml(scoretext);
714 pVictoryCongratulationsItem_->show();
719 void SeaScene::restartGame()
727 void SeaScene::forcePause()
729 //Pause without setting the pause action state
733 void SeaScene::softContinue()
735 //Continue if not being paused by the user
736 // Reverts forcePause()
738 pause(pPauseAction_->isChecked());
742 void SeaScene::createVictoryItems()
744 pVictoryCongratulationsItem_ = new QGraphicsTextItem;
745 pVictoryCongratulationsItem_->setHtml("<font size=\"6\" color = darkorange> Victory!");
746 pVictoryCongratulationsItem_->hide();
747 pVictoryCongratulationsItem_->setPos(315,30);
748 pVictoryCongratulationsItem_->setZValue(1000);
749 addItem(pVictoryCongratulationsItem_);
752 //coordinates are relative to the parent
754 QGraphicsTextItem * pTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
755 pTextItem->setHtml("<font size=\"5\" color = darkorange> Congratulations!");
756 pTextItem->setPos(-50,80);
757 pTextItem->setZValue(1000);
759 QGraphicsTextItem * pMiddleTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
760 pMiddleTextItem->setHtml("<font size=\"5\" color = darkorange> You have saved all the ghosts.");
761 pMiddleTextItem->setPos(-145,120);
762 pMiddleTextItem->setZValue(1000);
765 pVictoryScoreItem_ = new QGraphicsTextItem(pVictoryCongratulationsItem_);
766 pVictoryScoreItem_->setPos(-50,180);
767 pMiddleTextItem->setZValue(1000);
768 //Text is set at usetime!
770 QGraphicsTextItem * pLowestTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
771 pLowestTextItem->setHtml("<font size=\"5\" color = darkorange> Tap to play again");
772 pLowestTextItem->setPos(-50,360);
773 pLowestTextItem->setZValue(1000);
776 void SeaScene::createAboutBoxItems()
778 pAboutBoxItem_ = new QGraphicsTextItem;
779 addItem(pAboutBoxItem_);
780 pAboutBoxItem_->setPos(25,50);
781 pAboutBoxItem_->setZValue(1000);
782 pAboutBoxItem_->hide();
784 pAboutBoxItem_->setHtml(tr("<font color = darkorange size = \"7\">"
785 "%1 <br> <font size = \"5\"> Version %2"
786 "<p><font size = \"4\"> Copyright 2011 Heli Hyvättinen"
787 "<p><font size = \"4\"> License: General Public License v2"
788 "<p><font size = \"3\"> Web: http://ghostsoverboard.garage.maemo.org/<br>"
789 "Bug Reports: <br> https://bugs.maemo.org/"
790 "enter_bug.cgi?product=Ghosts%20Overboard"
791 ).arg(QApplication::applicationName(),QApplication::applicationVersion()));
795 void SeaScene::setItemPointersNull()
797 pPausetextItem_ = NULL;
798 pRestartLevelItem_ = NULL;
799 pRestartGameItem_ = NULL;
800 pSettingsItem_ = NULL;
803 pMinimizeItem_ = NULL;
805 pAboutBoxItem_ = NULL;
806 pVictoryCongratulationsItem_ = NULL;
807 pLevelCompletedItem_ = NULL;
808 pVictoryScoreItem_ = NULL;
813 void SeaScene::turnPauseOn()
815 pPauseAction_->setChecked(true);
818 void SeaScene::handleDeviceLocked(bool isLocked)
820 //pauses if locked but does not unpause if unlocked
823 pPauseAction_->setChecked(true);
827 void SeaScene::pollDeviceLocked()
830 bool locked = deviceInfo_.isDeviceLocked();
836 pPauseAction_->setChecked(true);
837 alreadyLocked_ = true;
842 alreadyLocked_ = false;
847 void SeaScene::createLevelCompletedItems()
849 pLevelCompletedItem_ = new QGraphicsTextItem;
850 addItem(pLevelCompletedItem_);
851 pLevelCompletedItem_->setPos(240,100);
852 pLevelCompletedItem_->setZValue(1000);
853 pLevelCompletedItem_->hide();
854 //The text is set at usetime
856 QGraphicsTextItem * pTapForNextLevelItem = new QGraphicsTextItem(pLevelCompletedItem_);
857 pTapForNextLevelItem->setPos(-60,100);
858 pTapForNextLevelItem->setZValue(1000);
859 pTapForNextLevelItem->setHtml("<font size=\"5\" color = darkorange>Tap to start the next level");