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 createLevelCompletedItem();
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()));
240 scoreCounter_.start();
245 void SeaScene::setupMap(Level level)
247 setupMap(level.getNumberOfGhosts(),level.getNumberOfRocks(),level.getNumberOfOctopuses(),level.getOctopusSpeed());
250 void SeaScene::spreadGhosts(int ghosts)
254 //the octopuses and the ship may have moved from their original positions,
255 //so the list of free slots must be adjusted to exclude their current positions
257 QList<QPointF> temporarilyReservedSlots;
259 foreach (QGraphicsItem* pItem, movingItems_)
263 // qDebug() << "NULL item in movingItems_";
267 //round x and y down to fit the slot size
277 QPointF position (x,y);
279 //remove the tiles (potentially) occupied by the item from free slots and place in temp list if was in the list before
281 if (freeTiles_.removeOne(position))
282 temporarilyReservedSlots.append(position);
287 if (freeTiles_.removeOne(position))
288 temporarilyReservedSlots.append(position);
292 if (freeTiles_.removeOne(position))
293 temporarilyReservedSlots.append(position);
297 if (freeTiles_.removeOne(position))
298 temporarilyReservedSlots.append(position);
303 //spread ghosts in random free slots
305 for (int i=0; i < ghosts; i++)
307 QPointF * pPosition = findRandomFreeSlot();
309 //If there was no room no point to continue
310 if (pPosition == NULL)
313 QPixmap ghostPixmap(":/pix/aave.png");
314 QGraphicsPixmapItem * pGhost = addPixmap(ghostPixmap);
315 pGhost->setData(0,"ghost");
316 pGhost->setPos(*pPosition);
320 //return the slots occupied by moving items to free slots
321 freeTiles_.append(temporarilyReservedSlots);
323 //clear temp for the next round
324 temporarilyReservedSlots.clear();
327 QPointF* SeaScene::findRandomFreeSlot()
329 if (freeTiles_.isEmpty())
332 int index = qrand()%freeTiles_.size();
334 // qDebug() << index << " index";
335 return new QPointF (freeTiles_.takeAt(index));
339 void SeaScene::removeGhost(QGraphicsItem *pGhost)
341 removeItem(pGhost); //remove the item from scene
342 freeTiles_.append(pGhost->scenePos()); //add the item's position to free slots
345 if (ghostsLeft_ == 0)
347 emit allGhostsPicked();
348 // qDebug() << "All ghosts picked!";
352 void SeaScene::ghostsDropped(int ghosts)
354 ghostsLeft_ += ghosts;
356 spreadGhosts(ghosts);
359 void SeaScene::pause(bool paused)
361 // qDebug() << "pause pressed " << paused;
362 if (paused_ == paused)
369 // qDebug() << "starting to move again";
370 // emit fullscreenRequested(); fremantle specific (since no "show statusbar" action in harmattan version)
372 screenLitKeeper_.keepScreenLit(true);
374 pPausetextItem_->hide();
376 autopauseTimer.start(); //Start counting towards autopause
381 // qDebug("about to stop movement");
383 screenLitKeeper_.keepScreenLit(false);
384 if (pPausetextItem_ != NULL)
386 // qDebug() << "about to show the pause text";
387 pPausetextItem_->show();
388 // qDebug() << "showing pause text";
390 // else qDebug() << "No pause text available";
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()
613 setupMap(levelset_.getLevel(currentLevel_)); //getLevel() returns default constructor Level if index is invalid, so no risk of crash
614 vibrationActivate(pVibrateAction_->isChecked()); //Vibration effects are lost without this
615 // qDebug() << pVibrateAction_->isChecked();
616 autopauseTimer.start(); //reset counting towards autopause
621 void SeaScene::nextLevel()
624 //get score for previous level
625 int score = scoreCounter_.elapsed()/1000;
626 totalScore_ += score;
627 int highscore = levelset_.getLevelHighScore(currentLevel_);
628 qDebug() << highscore;
632 if (score >= highscore)
634 scoretext = tr("<font size=\"5\" color = darkorange>Your time: %1 min %2 s<br>Best time: %3 min %4 sec").arg(score/60).arg(score%60).arg(highscore/60).arg(highscore%60);
637 else //New high score!
640 scoretext = tr("<font size=\"5\" color = darkorange>Your time %1 min %2 s is the new best time!").arg(score/60).arg(score%60);
641 levelset_.setLevelHighScore(currentLevel_,score);
644 //pause to show the highscore or victory screen
647 pPausetextItem_->hide();
650 //Go to the next level if available
653 if ( currentLevel_ < levelset_.numberOfLevels() )
655 pLevelCompletedItem_->setHtml(scoretext);
656 pLevelCompletedItem_->show();
662 pVictoryCongratulationsItem_->show();
667 void SeaScene::restartGame()
675 void SeaScene::forcePause()
677 //Pause without setting the pause action state
681 void SeaScene::softContinue()
683 //Continue if not being paused by the user
684 // Reverts forcePause()
686 pause(pPauseAction_->isChecked());
690 void SeaScene::createVictoryItems()
692 pVictoryCongratulationsItem_ = new QGraphicsTextItem;
693 pVictoryCongratulationsItem_->setHtml("<font size=\"7\" color = darkorange> <b> Victory!");
694 pVictoryCongratulationsItem_->hide();
695 pVictoryCongratulationsItem_->setPos(355,50);
696 pVictoryCongratulationsItem_->setZValue(1000);
697 addItem(pVictoryCongratulationsItem_);
700 //coordinates are relative to the parent
702 QGraphicsTextItem * pTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
703 pTextItem->setHtml("<font size=\"7\" color = darkorange> Congratulations!");
704 pTextItem->setPos(-50,100);
705 pTextItem->setZValue(1000);
707 QGraphicsTextItem * pMiddleTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
708 pMiddleTextItem->setHtml("<font size=\"7\" color = darkorange> You have saved all the ghosts.");
709 pMiddleTextItem->setPos(-145,140);
710 pMiddleTextItem->setZValue(1000);
712 QGraphicsTextItem * pLowestTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
713 pLowestTextItem->setHtml("<font size=\"7\" color = darkorange> Tap to play again");
714 pLowestTextItem->setPos(-50,220);
715 pLowestTextItem->setZValue(1000);
719 void SeaScene::createAboutBoxItems()
721 pAboutBoxItem_ = new QGraphicsTextItem;
722 addItem(pAboutBoxItem_);
723 pAboutBoxItem_->setPos(25,50);
724 pAboutBoxItem_->setZValue(1000);
725 pAboutBoxItem_->hide();
727 pAboutBoxItem_->setHtml(tr("<font color = darkorange size = \"7\">"
728 "%1 <br> <font size = \"7\"> Version %2"
729 "<p><font size = \"6\"> Copyright 2011 Heli Hyvättinen"
730 "<p><font size = \"6\"> License: General Public License v2"
731 "<p><font size = \"5\"> Web: http://ghostsoverboard.garage.maemo.org/<br>"
732 "Bug Reports: <br> https://bugs.maemo.org/"
733 "enter_bug.cgi?product=Ghosts%20Overboard"
734 ).arg(QApplication::applicationName(),QApplication::applicationVersion()));
738 void SeaScene::setItemPointersNull()
740 pPausetextItem_ = NULL;
741 pRestartLevelItem_ = NULL;
742 pRestartGameItem_ = NULL;
743 pSettingsItem_ = NULL;
746 // pMinimizeItem_ = NULL; //Fremantle spesific
748 pAboutBoxItem_ = NULL;
749 pLevelCompletedItem_ = NULL;
753 void SeaScene::turnPauseOn()
755 pPauseAction_->setChecked(true);
760 void SeaScene::createLevelCompletedItem()
762 pLevelCompletedItem_ = new QGraphicsTextItem;
763 addItem(pLevelCompletedItem_);
764 pLevelCompletedItem_->setPos(20,20);
765 pLevelCompletedItem_->setZValue(1000);
766 pLevelCompletedItem_->hide();
767 //The text is set at usetime