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
65 levelList_.append(level1);
66 Level level2(5,10,2,50);
67 levelList_.append(level2);
68 Level level3(5,15,2,50);
69 levelList_.append(level3);
70 Level level4(5,15,4,50);
71 levelList_.append(level4);
72 Level level5(5,15,5,100);
73 levelList_.append(level5);
78 connect(this,SIGNAL(allGhostsPicked()),this,SLOT(nextLevel()));
81 pVibrateAction_ = new QAction(tr("Vibration effects"),this);
82 pVibrateAction_->setCheckable(true);
83 connect(pVibrateAction_,SIGNAL(toggled(bool)),this,SLOT(vibrationActivate(bool)));
85 pVibrateAction_->setChecked(settings.value("vibration",false).toBool());
88 pPauseAction_ = new QAction(tr("Pause"),this);
89 pPauseAction_->setCheckable(true);
90 connect(pPauseAction_,SIGNAL(toggled(bool)),this,SLOT(pause(bool)));
93 deviceLockPollTimer_.setInterval(20*60);
94 connect(&deviceLockPollTimer_,SIGNAL(timeout()),this,SLOT(pollDeviceLocked()));
95 deviceLockPollTimer_.start();
98 autopauseTimer.setSingleShot(true);
99 autopauseTimer.setInterval(15*60*1000);
100 connect(&autopauseTimer,SIGNAL(timeout()),this,SLOT(turnPauseOn()));
105 void SeaScene::setupMap(int ghosts, int rocks, int octopuses, int octopusSpeed)
111 setItemPointersNull();
115 createAboutBoxItems();
117 createVictoryItems();
120 //empty the list of moving items
122 movingItems_.clear();
124 //empty the list of free slots
127 //fill the list of free slots
129 int numberOfXTiles = width() / 40;
130 int numberOfYTiles = height() /40;
132 // qDebug() << numberOfXTiles << " slots in x direction";
133 // qDebug() << numberOfYTiles << " slots in y rirection";
135 for (int i = 0; i < numberOfXTiles; i++ )
137 for (int j = 0; j < numberOfYTiles; j++)
139 freeTiles_.append(QPointF(i*40,j*40));
146 for (int i = 0; i < rocks; i++)
148 QPointF * pPosition = findRandomFreeSlot();
150 //If there was no room no point to continue
151 if (pPosition == NULL)
154 QPixmap rockPixmap (":/pix/kari.png");
155 QGraphicsPixmapItem * pRock = addPixmap(rockPixmap);
156 pRock->setData(0,"rock");
157 pRock->setPos(*pPosition);
164 ghostsLeft_ = ghosts;
165 spreadGhosts(ghosts);
169 //spread the octopuses
171 QList <Octopus*> octopusList;
173 for (int i=0; i < octopuses; i++)
175 QPointF * pPosition = findRandomFreeSlot();
177 //If there was no room no point to continue
178 if (pPosition == NULL)
181 QPixmap octopusPixmap (":/pix/tursas.png");
182 Octopus * pOctopus = new Octopus(octopusPixmap,octopusSpeed);
183 pOctopus->setData(0,"octopus");
184 pOctopus->setPos(*pPosition);
186 pOctopus->startMoving();
187 movingItems_.append(pOctopus);
188 connect(this,SIGNAL(pauseOn()),pOctopus,SLOT(stopMoving()));
189 connect(this,SIGNAL(pauseOff()),pOctopus,SLOT(startMoving()));
190 octopusList.append(pOctopus);
198 QPointF * pPosition = findRandomFreeSlot();
199 if (pPosition == NULL)
201 // Game cannot begin without a free position for ship, so give an error message and return
203 QMessageBox::critical(NULL,"Error! Too many objects on screen","No free space to place the ship. The game cannot start. Please choose another level.");
207 QList<QPixmap> shipImages;
208 shipImages.append(QPixmap(":/pix/laiva.png"));
209 shipImages.append(QPixmap(":/pix/laiva_1aave.png"));
210 shipImages.append(QPixmap(":/pix/laiva_2aave.png"));
211 shipImages.append(QPixmap(":/pix/laiva_3aave.png"));
212 shipImages.append(QPixmap(":/pix/laiva_4aave.png"));
213 shipImages.append(QPixmap(":/pix/laiva_5aave.png"));
214 shipImages.append(QPixmap(":/pix/laiva_6aave.png"));
215 shipImages.append(QPixmap(":/pix/laiva_7aave.png"));
216 shipImages.append(QPixmap(":/pix/laiva_8aave.png"));
217 shipImages.append(QPixmap(":/pix/laiva_9aave.png"));
218 shipImages.append(QPixmap(":/pix/laiva_10aave.png"));
220 Ship * pShip = new Ship (shipImages);
221 pShip->setData(0,"ship");
222 pShip->setPos(*pPosition);
224 connect(pShip,SIGNAL(pickingGhost(QGraphicsItem*)),this, SLOT(removeGhost(QGraphicsItem*)) );
225 connect(pShip,SIGNAL(droppingGhosts(int)),this,SLOT(ghostsDropped(int)));
226 connect(this,SIGNAL(vibrationActivated(bool)),pShip,SLOT(setVibrationActivate(bool)));
227 pShip->startMoving();
228 movingItems_.append(pShip);
229 connect(this,SIGNAL(pauseOn()),pShip,SLOT(stopMoving()));
230 connect(this,SIGNAL(pauseOff()),pShip,SLOT(startMoving()));
231 foreach (Octopus* pOctopus, octopusList)
233 connect(pOctopus,SIGNAL(droppingGhosts()),pShip,SLOT(dropAllGhosts()));
240 void SeaScene::setupMap(Level level)
242 setupMap(level.getNumberOfGhosts(),level.getNumberOfRocks(),level.getNumberOfOctopuses(),level.getOctopusSpeed());
245 void SeaScene::spreadGhosts(int ghosts)
249 //the octopuses and the ship may have moved from their original positions,
250 //so the list of free slots must be adjusted to exclude their current positions
252 QList<QPointF> temporarilyReservedSlots;
254 foreach (QGraphicsItem* pItem, movingItems_)
258 // qDebug() << "NULL item in movingItems_";
262 //round x and y down to fit the slot size
272 QPointF position (x,y);
274 //remove the tiles (potentially) occupied by the item from free slots and place in temp list if was in the list before
276 if (freeTiles_.removeOne(position))
277 temporarilyReservedSlots.append(position);
282 if (freeTiles_.removeOne(position))
283 temporarilyReservedSlots.append(position);
287 if (freeTiles_.removeOne(position))
288 temporarilyReservedSlots.append(position);
292 if (freeTiles_.removeOne(position))
293 temporarilyReservedSlots.append(position);
298 //spread ghosts in random free slots
300 for (int i=0; i < ghosts; i++)
302 QPointF * pPosition = findRandomFreeSlot();
304 //If there was no room no point to continue
305 if (pPosition == NULL)
308 QPixmap ghostPixmap(":/pix/aave.png");
309 QGraphicsPixmapItem * pGhost = addPixmap(ghostPixmap);
310 pGhost->setData(0,"ghost");
311 pGhost->setPos(*pPosition);
315 //return the slots occupied by moving items to free slots
316 freeTiles_.append(temporarilyReservedSlots);
318 //clear temp for the next round
319 temporarilyReservedSlots.clear();
322 QPointF* SeaScene::findRandomFreeSlot()
324 if (freeTiles_.isEmpty())
327 int index = qrand()%freeTiles_.size();
329 // qDebug() << index << " index";
330 return new QPointF (freeTiles_.takeAt(index));
334 void SeaScene::removeGhost(QGraphicsItem *pGhost)
336 removeItem(pGhost); //remove the item from scene
337 freeTiles_.append(pGhost->scenePos()); //add the item's position to free slots
340 if (ghostsLeft_ == 0)
342 emit allGhostsPicked();
343 // qDebug() << "All ghosts picked!";
347 void SeaScene::ghostsDropped(int ghosts)
349 ghostsLeft_ += ghosts;
351 spreadGhosts(ghosts);
354 void SeaScene::pause(bool paused)
356 // qDebug() << "pause pressed " << paused;
357 if (paused_ == paused)
364 // qDebug() << "starting to move again";
365 emit fullscreenRequested();
367 screenLitKeeper_.keepScreenLit(true);
369 pPausetextItem_->hide();
371 autopauseTimer.start(); //Start counting towards autopause
372 deviceLockPollTimer_.start(); //Start polling whether device is locked
377 // qDebug("about to stop movement");
379 screenLitKeeper_.keepScreenLit(false);
380 if (pPausetextItem_ != NULL)
382 // qDebug() << "about to show the pause text";
383 pPausetextItem_->show();
384 // qDebug() << "showing pause text";
386 // else qDebug() << "No pause text available";
388 autopauseTimer.stop(); //No need to count toward autopause when already paused
389 deviceLockPollTimer_.stop(); //No need to check for unlock as no unpause anyway
393 void SeaScene::vibrationActivate(bool on)
395 emit vibrationActivated(on);
398 void SeaScene::handleScreenTapped()
401 //If the game is going just pause it
404 pPauseAction_->setChecked(true);
408 //If the game is paused and about box is shown, close it and show the pause text and menu again
412 if(pAboutBoxItem_->isVisible())
414 pAboutBoxItem_->hide();
415 pPausetextItem_->show();
420 //If the game is paused, check if the victory item is being shown
421 if(pVictoryCongratulationsItem_)
423 if (pVictoryCongratulationsItem_->isVisibleTo(NULL)) //returns visibility to scene
425 pVictoryCongratulationsItem_->hide();
427 pPauseAction_->setChecked(false); // unpause
432 //If the game is paused and no victory, check if menu item was selected
434 QList<QGraphicsItem *> items = selectedItems();
436 //if nothing selected resume play
440 pPauseAction_->setChecked(false);
445 //If something was selected check if it was one of the menu items and act on it
446 //(Nothing else should be made selectable anyway)
450 QGraphicsItem* pItem = items.at(0); //Selecting an item brings here, thus only selecting one item should be possible
451 //... so we can just take the first one
453 //Selection is just used to get notice of a menu item being clicked, removed after use
458 //Act upon the selected item
461 if (pItem == pRestartGameItem_)
463 // qDebug() << "game restart requested";
465 pPauseAction_->setChecked(false); //unpause game
469 else if (pItem == pRestartLevelItem_)
471 // qDebug() << "Level restart requested";
473 pPauseAction_->setChecked(false); //unpause game
477 else if (pItem == pSettingsItem_)
479 pVibrateAction_->toggle();
482 settings.setValue("vibration",pVibrateAction_->isChecked());
484 QString text = pSettingsItem_->toHtml();
485 if (pVibrateAction_->isChecked())
486 text.replace(" on"," off"); //don't remove spaces or you get vibratioff...
488 text.replace(" off"," on");
489 pSettingsItem_->setHtml(text);
492 else if (pItem == pAboutItem_)
497 else if(pItem == pMinimizeItem_)
499 emit minimizeRequested();
502 else if (pItem == pQuitItem_)
510 void SeaScene::createMenuItems()
514 font.setPixelSize(35);
518 pPausetextItem_ = new QGraphicsTextItem;
519 pPausetextItem_->setHtml("<font size = \"5\" color = darkorange> Game paused. Tap to continue.");
520 pPausetextItem_->setZValue(1000);
521 pPausetextItem_->setPos(165,50);
522 addItem(pPausetextItem_);
523 pPausetextItem_->hide();
527 QString menufonthtml = "<font size = \"4\" color = darkorange>";
529 pRestartGameItem_ = new QGraphicsTextItem;
530 pRestartGameItem_->setHtml(tr("Restart <br> game").prepend(menufonthtml));
531 prepareForMenu(pRestartGameItem_);
533 pRestartLevelItem_ = new QGraphicsTextItem;
534 pRestartLevelItem_->setHtml(tr("Restart <br> level").prepend(menufonthtml));
535 prepareForMenu(pRestartLevelItem_);
537 pSettingsItem_ = new QGraphicsTextItem;
538 QString vibraText(tr("Turn vibration <br> effects "));
540 if (pVibrateAction_->isChecked())
548 vibraText.append(statusText);
549 pSettingsItem_->setHtml(vibraText.prepend(menufonthtml));
550 prepareForMenu(pSettingsItem_);
552 pAboutItem_ = new QGraphicsTextItem;
553 pAboutItem_->setHtml(tr("About <br> game").prepend(menufonthtml));
554 prepareForMenu(pAboutItem_);
556 pMinimizeItem_ = new QGraphicsTextItem;
557 pMinimizeItem_->setHtml(tr("Show <br> status bar").prepend(menufonthtml));
558 prepareForMenu(pMinimizeItem_);
560 pQuitItem_ = new QGraphicsTextItem;
561 pQuitItem_->setHtml(tr("Quit <br> game").prepend(menufonthtml));
562 prepareForMenu(pQuitItem_);
566 void SeaScene::prepareForMenu(QGraphicsItem * pItem)
569 //Menu items have pause text item as their parent and are thus added to scene automatically
570 //They are also shown and hidden with it, resulting in the menu being visble when the game is paused
571 //Their coordinates are given relative to the parent.
578 pItem->setParentItem(pPausetextItem_);
579 pItem->setZValue(1000);
580 pItem->setFlag(QGraphicsItem::ItemIsSelectable);
582 int row = menuItemCount_/(itemsPerRow);
583 pItem->setY(150+row*120);
584 pItem->setX(((menuItemCount_%(itemsPerRow))*180+5));
590 void SeaScene::about()
592 pPausetextItem_->hide();
593 pAboutBoxItem_->show();
597 void SeaScene::restartLevel()
599 setupMap(levelList_.value(currentLevel_)); //value() returns default constructor Level if index is invalid, so no risk of crash
600 vibrationActivate(pVibrateAction_->isChecked()); //Vibration effects are lost without this
601 // qDebug() << pVibrateAction_->isChecked();
602 autopauseTimer.start(); //reset counting towards autopause
607 void SeaScene::nextLevel()
612 if (levelList_.empty())
616 if ( currentLevel_ < levelList_.size() )
624 pPauseAction_->setChecked(true); //Pause the game while showing the victory dialog
626 pPausetextItem_->hide();
628 pVictoryCongratulationsItem_->show();
634 void SeaScene::restartGame()
641 void SeaScene::forcePause()
643 //Pause without setting the pause action state
647 void SeaScene::softContinue()
649 //Continue if not being paused by the user
650 // Reverts forcePause()
652 pause(pPauseAction_->isChecked());
656 void SeaScene::createVictoryItems()
658 pVictoryCongratulationsItem_ = new QGraphicsTextItem;
659 pVictoryCongratulationsItem_->setHtml("<font size=\"6\" color = darkorange> Victory!");
660 pVictoryCongratulationsItem_->hide();
661 pVictoryCongratulationsItem_->setPos(355,50);
662 pVictoryCongratulationsItem_->setZValue(1000);
663 addItem(pVictoryCongratulationsItem_);
666 //coordinates are relative to the parent
668 QGraphicsTextItem * pTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
669 pTextItem->setHtml("<font size=\"5\" color = darkorange> Congratulations!");
670 pTextItem->setPos(-50,100);
671 pTextItem->setZValue(1000);
673 QGraphicsTextItem * pMiddleTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
674 pMiddleTextItem->setHtml("<font size=\"5\" color = darkorange> You have saved all the ghosts.");
675 pMiddleTextItem->setPos(-145,140);
676 pMiddleTextItem->setZValue(1000);
678 QGraphicsTextItem * pLowestTextItem = new QGraphicsTextItem(pVictoryCongratulationsItem_);
679 pLowestTextItem->setHtml("<font size=\"5\" color = darkorange> Tap to play again");
680 pLowestTextItem->setPos(-50,220);
681 pLowestTextItem->setZValue(1000);
684 void SeaScene::createAboutBoxItems()
686 pAboutBoxItem_ = new QGraphicsTextItem;
687 addItem(pAboutBoxItem_);
688 pAboutBoxItem_->setPos(25,50);
689 pAboutBoxItem_->setZValue(1000);
690 pAboutBoxItem_->hide();
692 pAboutBoxItem_->setHtml(tr("<font color = darkorange size = \"7\">"
693 "%1 <br> <font size = \"5\"> Version %2"
694 "<p><font size = \"4\"> Copyright 2011 Heli Hyvättinen"
695 "<p><font size = \"4\"> License: General Public License v2"
696 "<p><font size = \"3\"> Web: http://ghostsoverboard.garage.maemo.org/<br>"
697 "Bug Reports: <br> https://bugs.maemo.org/"
698 "enter_bug.cgi?product=Ghosts%20Overboard"
699 ).arg(QApplication::applicationName(),QApplication::applicationVersion()));
703 void SeaScene::setItemPointersNull()
705 pPausetextItem_ = NULL;
706 pRestartLevelItem_ = NULL;
707 pRestartGameItem_ = NULL;
708 pSettingsItem_ = NULL;
711 pMinimizeItem_ = NULL;
713 pAboutBoxItem_ = NULL;
714 pVictoryCongratulationsItem_ = NULL;
718 void SeaScene::turnPauseOn()
720 pPauseAction_->setChecked(true);
723 void SeaScene::handleDeviceLocked(bool isLocked)
725 //pauses if locked but does not unpause if unlocked
728 pPauseAction_->setChecked(true);
732 void SeaScene::pollDeviceLocked()
735 bool locked = deviceInfo_.isDeviceLocked();
741 pPauseAction_->setChecked(true);
742 alreadyLocked_ = true;
747 alreadyLocked_ = false;