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
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);
84 connect(this,SIGNAL(allGhostsPicked()),this,SLOT(nextLevel()));
87 pVibrateAction_ = new QAction(tr("Vibration effects"),this);
88 pVibrateAction_->setCheckable(true);
89 connect(pVibrateAction_,SIGNAL(toggled(bool)),this,SLOT(vibrationActivate(bool)));
91 pVibrateAction_->setChecked(settings.value("vibration",false).toBool());
94 pPauseAction_ = new QAction(tr("Pause"),this);
95 pPauseAction_->setCheckable(true);
96 connect(pPauseAction_,SIGNAL(toggled(bool)),this,SLOT(pause(bool)));
99 deviceLockPollTimer_.setInterval(20*60);
100 connect(&deviceLockPollTimer_,SIGNAL(timeout()),this,SLOT(pollDeviceLocked()));
101 deviceLockPollTimer_.start();
104 autopauseTimer.setSingleShot(true);
105 autopauseTimer.setInterval(15*60*1000);
106 connect(&autopauseTimer,SIGNAL(timeout()),this,SLOT(turnPauseOn()));
111 void SeaScene::setupMap(int ghosts, int rocks, int octopuses, int octopusSpeed)
117 setItemPointersNull();
121 createAboutBoxItems();
123 createVictoryItems();
125 createLevelCompletedItem();
128 //empty the list of moving items
130 movingItems_.clear();
132 //empty the list of free slots
135 //fill the list of free slots
137 int numberOfXTiles = width() / 40;
138 int numberOfYTiles = height() /40;
140 // qDebug() << numberOfXTiles << " slots in x direction";
141 // qDebug() << numberOfYTiles << " slots in y rirection";
143 for (int i = 0; i < numberOfXTiles; i++ )
145 for (int j = 0; j < numberOfYTiles; j++)
147 freeTiles_.append(QPointF(i*40,j*40));
154 for (int i = 0; i < rocks; i++)
156 QPointF * pPosition = findRandomFreeSlot();
158 //If there was no room no point to continue
159 if (pPosition == NULL)
162 QPixmap rockPixmap (":/pix/kari.png");
163 QGraphicsPixmapItem * pRock = addPixmap(rockPixmap);
164 pRock->setData(0,"rock");
165 pRock->setPos(*pPosition);
172 ghostsLeft_ = ghosts;
173 spreadGhosts(ghosts);
177 //spread the octopuses
179 QList <Octopus*> octopusList;
181 for (int i=0; i < octopuses; i++)
183 QPointF * pPosition = findRandomFreeSlot();
185 //If there was no room no point to continue
186 if (pPosition == NULL)
189 QPixmap octopusPixmap (":/pix/tursas.png");
190 Octopus * pOctopus = new Octopus(octopusPixmap,octopusSpeed);
191 pOctopus->setData(0,"octopus");
192 pOctopus->setPos(*pPosition);
194 pOctopus->startMoving();
195 movingItems_.append(pOctopus);
196 connect(this,SIGNAL(pauseOn()),pOctopus,SLOT(stopMoving()));
197 connect(this,SIGNAL(pauseOff()),pOctopus,SLOT(startMoving()));
198 octopusList.append(pOctopus);
206 QPointF * pPosition = findRandomFreeSlot();
207 if (pPosition == NULL)
209 // Game cannot begin without a free position for ship, so give an error message and return
211 QMessageBox::critical(NULL,"Error! Too many objects on screen","No free space to place the ship. The game cannot start. Please choose another level.");
215 QList<QPixmap> shipImages;
216 shipImages.append(QPixmap(":/pix/laiva.png"));
217 shipImages.append(QPixmap(":/pix/laiva_1aave.png"));
218 shipImages.append(QPixmap(":/pix/laiva_2aave.png"));
219 shipImages.append(QPixmap(":/pix/laiva_3aave.png"));
220 shipImages.append(QPixmap(":/pix/laiva_4aave.png"));
221 shipImages.append(QPixmap(":/pix/laiva_5aave.png"));
222 shipImages.append(QPixmap(":/pix/laiva_6aave.png"));
223 shipImages.append(QPixmap(":/pix/laiva_7aave.png"));
224 shipImages.append(QPixmap(":/pix/laiva_8aave.png"));
225 shipImages.append(QPixmap(":/pix/laiva_9aave.png"));
226 shipImages.append(QPixmap(":/pix/laiva_10aave.png"));
228 Ship * pShip = new Ship (shipImages);
229 pShip->setData(0,"ship");
230 pShip->setPos(*pPosition);
232 connect(pShip,SIGNAL(pickingGhost(QGraphicsItem*)),this, SLOT(removeGhost(QGraphicsItem*)) );
233 connect(pShip,SIGNAL(droppingGhosts(int)),this,SLOT(ghostsDropped(int)));
234 connect(this,SIGNAL(vibrationActivated(bool)),pShip,SLOT(setVibrationActivate(bool)));
235 pShip->startMoving();
236 movingItems_.append(pShip);
237 connect(this,SIGNAL(pauseOn()),pShip,SLOT(stopMoving()));
238 connect(this,SIGNAL(pauseOff()),pShip,SLOT(startMoving()));
239 foreach (Octopus* pOctopus, octopusList)
241 connect(pOctopus,SIGNAL(droppingGhosts()),pShip,SLOT(dropAllGhosts()));
245 scoreCounter_.start();
250 void SeaScene::setupMap(Level level)
252 setupMap(level.getNumberOfGhosts(),level.getNumberOfRocks(),level.getNumberOfOctopuses(),level.getOctopusSpeed());
255 void SeaScene::spreadGhosts(int ghosts)
259 //the octopuses and the ship may have moved from their original positions,
260 //so the list of free slots must be adjusted to exclude their current positions
262 QList<QPointF> temporarilyReservedSlots;
264 foreach (QGraphicsItem* pItem, movingItems_)
268 // qDebug() << "NULL item in movingItems_";
272 //round x and y down to fit the slot size
282 QPointF position (x,y);
284 //remove the tiles (potentially) occupied by the item from free slots and place in temp list if was in the list before
286 if (freeTiles_.removeOne(position))
287 temporarilyReservedSlots.append(position);
292 if (freeTiles_.removeOne(position))
293 temporarilyReservedSlots.append(position);
297 if (freeTiles_.removeOne(position))
298 temporarilyReservedSlots.append(position);
302 if (freeTiles_.removeOne(position))
303 temporarilyReservedSlots.append(position);
308 //spread ghosts in random free slots
310 for (int i=0; i < ghosts; i++)
312 QPointF * pPosition = findRandomFreeSlot();
314 //If there was no room no point to continue
315 if (pPosition == NULL)
318 QPixmap ghostPixmap(":/pix/aave.png");
319 QGraphicsPixmapItem * pGhost = addPixmap(ghostPixmap);
320 pGhost->setData(0,"ghost");
321 pGhost->setPos(*pPosition);
325 //return the slots occupied by moving items to free slots
326 freeTiles_.append(temporarilyReservedSlots);
328 //clear temp for the next round
329 temporarilyReservedSlots.clear();
332 QPointF* SeaScene::findRandomFreeSlot()
334 if (freeTiles_.isEmpty())
337 int index = qrand()%freeTiles_.size();
339 // qDebug() << index << " index";
340 return new QPointF (freeTiles_.takeAt(index));
344 void SeaScene::removeGhost(QGraphicsItem *pGhost)
346 removeItem(pGhost); //remove the item from scene
347 freeTiles_.append(pGhost->scenePos()); //add the item's position to free slots
350 if (ghostsLeft_ == 0)
352 emit allGhostsPicked();
353 // qDebug() << "All ghosts picked!";
357 void SeaScene::ghostsDropped(int ghosts)
359 ghostsLeft_ += ghosts;
361 spreadGhosts(ghosts);
364 void SeaScene::pause(bool paused)
366 // qDebug() << "pause pressed " << paused;
367 if (paused_ == paused)
374 // qDebug() << "starting to move again";
375 emit fullscreenRequested();
377 screenLitKeeper_.keepScreenLit(true);
379 pPausetextItem_->hide();
381 autopauseTimer.start(); //Start counting towards autopause
382 deviceLockPollTimer_.start(); //Start polling whether device is locked
387 // qDebug("about to stop movement");
389 screenLitKeeper_.keepScreenLit(false);
390 if (pPausetextItem_ != NULL)
392 // qDebug() << "about to show the pause text";
393 pPausetextItem_->show();
394 // qDebug() << "showing pause text";
396 // else qDebug() << "No pause text available";
398 autopauseTimer.stop(); //No need to count toward autopause when already paused
399 deviceLockPollTimer_.stop(); //No need to check for unlock as no unpause anyway
403 void SeaScene::vibrationActivate(bool on)
405 emit vibrationActivated(on);
408 void SeaScene::handleScreenTapped()
411 //If the game is going just pause it
414 pPauseAction_->setChecked(true);
418 //If the game is paused and about box is shown, close it and show the pause text and menu again
422 if(pAboutBoxItem_->isVisible())
424 pAboutBoxItem_->hide();
425 pPausetextItem_->show();
430 //If the game is paused, check if the level completed item is shown
432 if (pLevelCompletedItem_)
434 if (pLevelCompletedItem_->isVisible())
436 pLevelCompletedItem_->hide();
437 restartLevel(); //Current level has already been set to the next one before showing the level completed item
438 pPauseAction_->setChecked(false); //unpause
443 //If the game is paused, check if the victory item is being shown
444 if(pVictoryCongratulationsItem_)
446 if (pVictoryCongratulationsItem_->isVisibleTo(NULL)) //returns visibility to scene
448 pVictoryCongratulationsItem_->hide();
450 pPauseAction_->setChecked(false); // unpause
456 //If the game is paused and no victory, check if menu item was selected
458 QList<QGraphicsItem *> items = selectedItems();
460 //if nothing selected resume play
464 pPauseAction_->setChecked(false);
469 //If something was selected check if it was one of the menu items and act on it
470 //(Nothing else should be made selectable anyway)
474 QGraphicsItem* pItem = items.at(0); //Selecting an item brings here, thus only selecting one item should be possible
475 //... so we can just take the first one
477 //Selection is just used to get notice of a menu item being clicked, removed after use
482 //Act upon the selected item
485 if (pItem == pRestartGameItem_)
487 // qDebug() << "game restart requested";
489 pPauseAction_->setChecked(false); //unpause game
493 else if (pItem == pRestartLevelItem_)
495 // qDebug() << "Level restart requested";
497 pPauseAction_->setChecked(false); //unpause game
501 else if (pItem == pSettingsItem_)
503 pVibrateAction_->toggle();
506 settings.setValue("vibration",pVibrateAction_->isChecked());
508 QString text = pSettingsItem_->toHtml();
509 if (pVibrateAction_->isChecked())
510 text.replace(" on"," off"); //don't remove spaces or you get vibratioff...
512 text.replace(" off"," on");
513 pSettingsItem_->setHtml(text);
516 else if (pItem == pAboutItem_)
521 else if(pItem == pMinimizeItem_)
523 emit minimizeRequested();
526 else if (pItem == pQuitItem_)
534 void SeaScene::createMenuItems()
538 font.setPixelSize(35);
542 pPausetextItem_ = new QGraphicsTextItem;
543 pPausetextItem_->setHtml("<font size = \"5\" color = darkorange> Game paused. Tap to continue.");
544 pPausetextItem_->setZValue(1000);
545 pPausetextItem_->setPos(165,50);
546 addItem(pPausetextItem_);
547 pPausetextItem_->hide();
551 QString menufonthtml = "<font size = \"4\" color = darkorange>";
553 pRestartGameItem_ = new QGraphicsTextItem;
554 pRestartGameItem_->setHtml(tr("Restart <br> game").prepend(menufonthtml));
555 prepareForMenu(pRestartGameItem_);
557 pRestartLevelItem_ = new QGraphicsTextItem;
558 pRestartLevelItem_->setHtml(tr("Restart <br> level").prepend(menufonthtml));
559 prepareForMenu(pRestartLevelItem_);
561 pSettingsItem_ = new QGraphicsTextItem;
562 QString vibraText(tr("Turn vibration <br> effects "));
564 if (pVibrateAction_->isChecked())
572 vibraText.append(statusText);
573 pSettingsItem_->setHtml(vibraText.prepend(menufonthtml));
574 prepareForMenu(pSettingsItem_);
576 pAboutItem_ = new QGraphicsTextItem;
577 pAboutItem_->setHtml(tr("About <br> game").prepend(menufonthtml));
578 prepareForMenu(pAboutItem_);
580 pMinimizeItem_ = new QGraphicsTextItem;
581 pMinimizeItem_->setHtml(tr("Show <br> status bar").prepend(menufonthtml));
582 prepareForMenu(pMinimizeItem_);
584 pQuitItem_ = new QGraphicsTextItem;
585 pQuitItem_->setHtml(tr("Quit <br> game").prepend(menufonthtml));
586 prepareForMenu(pQuitItem_);
590 void SeaScene::prepareForMenu(QGraphicsItem * pItem)
593 //Menu items have pause text item as their parent and are thus added to scene automatically
594 //They are also shown and hidden with it, resulting in the menu being visble when the game is paused
595 //Their coordinates are given relative to the parent.
602 pItem->setParentItem(pPausetextItem_);
603 pItem->setZValue(1000);
604 pItem->setFlag(QGraphicsItem::ItemIsSelectable);
606 int row = menuItemCount_/(itemsPerRow);
607 pItem->setY(150+row*120);
608 pItem->setX(((menuItemCount_%(itemsPerRow))*180+5));
614 void SeaScene::about()
616 pPausetextItem_->hide();
617 pAboutBoxItem_->show();
621 void SeaScene::restartLevel()
623 setupMap(levelset_.getLevel(currentLevel_)); //getLevel() returns default constructor Level if index is invalid, so no risk of crash
624 vibrationActivate(pVibrateAction_->isChecked()); //Vibration effects are lost without this
625 // qDebug() << pVibrateAction_->isChecked();
626 autopauseTimer.start(); //reset counting towards autopause
631 void SeaScene::nextLevel()
634 //get score for previous level
635 int score = scoreCounter_.elapsed()/1000;
636 totalScore_ += score;
637 int highscore = levelset_.getLevelHighScore(currentLevel_);
638 qDebug() << highscore;
642 if (score >= highscore)
644 scoretext = tr("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);
647 else //New high score!
650 scoretext = tr("Your time %1 min %2 s is the new best time!").arg(score/60).arg(score%60);
651 levelset_.setLevelHighScore(currentLevel_,score);
654 //pause to show the highscore or victory screen
657 pPausetextItem_->hide();
660 //Go to the next level if available
663 if ( currentLevel_ < levelset_.numberOfLevels() )
665 pLevelCompletedItem_->setHtml(scoretext);
666 pLevelCompletedItem_->show();
672 pVictoryCongratulationsItem_->show();
677 void SeaScene::restartGame()
685 void SeaScene::forcePause()
687 //Pause without setting the pause action state
691 void SeaScene::softContinue()
693 //Continue if not being paused by the user
694 // Reverts forcePause()
696 pause(pPauseAction_->isChecked());
700 void SeaScene::createVictoryItems()
702 pVictoryCongratulationsItem_ = new QGraphicsTextItem;
703 pVictoryCongratulationsItem_->setHtml("<font size=\"6\" color = darkorange> Victory!");
704 pVictoryCongratulationsItem_->hide();
705 pVictoryCongratulationsItem_->setPos(355,50);
706 pVictoryCongratulationsItem_->setZValue(1000);
707 addItem(pVictoryCongratulationsItem_);
710 //coordinates are relative to the parent
712 QGraphicsTextItem * pTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
713 pTextItem->setHtml("<font size=\"5\" color = darkorange> Congratulations!");
714 pTextItem->setPos(-50,100);
715 pTextItem->setZValue(1000);
717 QGraphicsTextItem * pMiddleTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
718 pMiddleTextItem->setHtml("<font size=\"5\" color = darkorange> You have saved all the ghosts.");
719 pMiddleTextItem->setPos(-145,140);
720 pMiddleTextItem->setZValue(1000);
722 QGraphicsTextItem * pLowestTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
723 pLowestTextItem->setHtml("<font size=\"5\" color = darkorange> Tap to play again");
724 pLowestTextItem->setPos(-50,220);
725 pLowestTextItem->setZValue(1000);
728 void SeaScene::createAboutBoxItems()
730 pAboutBoxItem_ = new QGraphicsTextItem;
731 addItem(pAboutBoxItem_);
732 pAboutBoxItem_->setPos(25,50);
733 pAboutBoxItem_->setZValue(1000);
734 pAboutBoxItem_->hide();
736 pAboutBoxItem_->setHtml(tr("<font color = darkorange size = \"7\">"
737 "%1 <br> <font size = \"5\"> Version %2"
738 "<p><font size = \"4\"> Copyright 2011 Heli Hyvättinen"
739 "<p><font size = \"4\"> License: General Public License v2"
740 "<p><font size = \"3\"> Web: http://ghostsoverboard.garage.maemo.org/<br>"
741 "Bug Reports: <br> https://bugs.maemo.org/"
742 "enter_bug.cgi?product=Ghosts%20Overboard"
743 ).arg(QApplication::applicationName(),QApplication::applicationVersion()));
747 void SeaScene::setItemPointersNull()
749 pPausetextItem_ = NULL;
750 pRestartLevelItem_ = NULL;
751 pRestartGameItem_ = NULL;
752 pSettingsItem_ = NULL;
755 pMinimizeItem_ = NULL;
757 pAboutBoxItem_ = NULL;
758 pVictoryCongratulationsItem_ = NULL;
759 pLevelCompletedItem_ = NULL;
764 void SeaScene::turnPauseOn()
766 pPauseAction_->setChecked(true);
769 void SeaScene::handleDeviceLocked(bool isLocked)
771 //pauses if locked but does not unpause if unlocked
774 pPauseAction_->setChecked(true);
778 void SeaScene::pollDeviceLocked()
781 bool locked = deviceInfo_.isDeviceLocked();
787 pPauseAction_->setChecked(true);
788 alreadyLocked_ = true;
793 alreadyLocked_ = false;
798 void SeaScene::createLevelCompletedItem()
800 pLevelCompletedItem_ = new QGraphicsTextItem;
801 addItem(pLevelCompletedItem_);
802 pLevelCompletedItem_->setPos(20,20);
803 pLevelCompletedItem_->setZValue(1000);
804 pLevelCompletedItem_->hide();
805 //The text is set at usetime