Autopausetimer now singleshot
[ghostsoverboard] / seascene.cpp
1 /**************************************************************************
2         Ghosts Overboard - a game for Maemo 5
3
4         Copyright (C) 2011  Heli Hyvättinen
5
6         This file is part of Ghosts Overboard
7
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.
12
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.
17
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/>.
20
21 **************************************************************************/
22
23 #include "seascene.h"
24 #include "octopus.h"
25 #include "ship.h"
26 #include <QGraphicsPixmapItem>
27 #include <QDebug>
28 #include <QMessageBox>
29 #include <QTime>
30 #include <QApplication>
31 #include <QAction>
32 #include <QPushButton>
33 #include <QLabel>
34 #include <QVBoxLayout>
35
36 const QString ghostImageFilename_ = ":/pix/aave.png";
37 const QString rockImageFilename_ =":/pix/kari.png";
38 const QString octopusImageFilename_= ":/pix/tursas.png";
39
40
41 SeaScene::SeaScene(QObject *parent) :
42     QGraphicsScene(parent)
43 {
44     paused_ = false;
45     screenLitKeeper_.keepScreenLit(true);
46
47     //set background
48
49     QPixmap waves (":/pix/meri.png");
50     waves.scaled(20,20);
51     setBackgroundBrush(QBrush(waves));
52
53     //set random seed
54
55     qsrand(QTime::currentTime().msec()+2);  //+2 to avoid setting it to 1
56
57 //Setup the level list
58
59     Level level1(5,10);
60     levelList_.append(level1);
61     Level level2(5,10,2,50);
62     levelList_.append(level2);
63     Level level3(5,15,2,50);
64     levelList_.append(level3);
65     Level level4(5,15,4,50);
66     levelList_.append(level4);
67     Level level5(5,15,5,100);
68     levelList_.append(level5);
69
70     currentLevel_ = 0;
71
72     connect(this,SIGNAL(allGhostsPicked()),this,SLOT(nextLevel()));
73
74
75     pVibrateAction_ = new QAction(tr("Vibration effects"),this);
76     pVibrateAction_->setCheckable(true);
77     connect(pVibrateAction_,SIGNAL(toggled(bool)),this,SLOT(vibrationActivate(bool)));
78
79
80     pPauseAction_ = new QAction(tr("Pause"),this);
81     pPauseAction_->setCheckable(true);
82     connect(pPauseAction_,SIGNAL(toggled(bool)),this,SLOT(pause(bool)));
83
84
85     autopauseTimer.setSingleShot(true);
86     autopauseTimer.setInterval(15*60*1000);
87     connect(&autopauseTimer,SIGNAL(timeout()),this,SLOT(forcePause()));
88
89
90 }
91
92 void SeaScene::setupMap(int ghosts, int rocks, int octopuses, int octopusSpeed)
93 {
94     //empty the map
95
96     clear();
97
98     createMenuItems();
99
100     //empty the list of moving items
101
102     movingItems_.clear();
103
104     //empty the list of free slots
105     freeTiles_.clear();
106
107     //fill the list of free slots
108
109     int numberOfXTiles  = width() / 40;
110     int numberOfYTiles = height() /40;
111
112 //    qDebug() << numberOfXTiles << " slots in x direction";
113 //    qDebug() << numberOfYTiles << " slots in y rirection";
114
115     for (int i = 0; i < numberOfXTiles; i++ )
116     {
117         for (int j = 0; j < numberOfYTiles; j++)
118         {
119             freeTiles_.append(QPointF(i*40,j*40));
120         }
121     }
122
123
124     //spread the rocks
125
126     for (int i = 0; i < rocks; i++)
127     {
128         QPointF * pPosition = findRandomFreeSlot();
129
130         //If there was no room no point to continue
131         if (pPosition == NULL)
132             break;
133
134         QPixmap rockPixmap (":/pix/kari.png");
135         QGraphicsPixmapItem * pRock = addPixmap(rockPixmap);
136         pRock->setData(0,"rock");
137         pRock->setPos(*pPosition);
138         delete pPosition;
139
140     }
141
142     //spread the ghosts
143
144     ghostsLeft_ = ghosts;
145     spreadGhosts(ghosts);
146
147
148
149     //spread the octopuses
150
151     QList <Octopus*> octopusList;
152
153     for (int i=0; i < octopuses; i++)
154     {
155         QPointF * pPosition = findRandomFreeSlot();
156
157         //If there was no room no point to continue
158         if (pPosition == NULL)
159             break;
160
161     QPixmap octopusPixmap (":/pix/tursas.png");
162     Octopus * pOctopus = new Octopus(octopusPixmap,octopusSpeed);
163     pOctopus->setData(0,"octopus");
164     pOctopus->setPos(*pPosition);
165     addItem(pOctopus);
166     pOctopus->startMoving();
167     movingItems_.append(pOctopus);
168     connect(this,SIGNAL(pauseOn()),pOctopus,SLOT(stopMoving()));
169     connect(this,SIGNAL(pauseOff()),pOctopus,SLOT(startMoving()));
170     octopusList.append(pOctopus);
171     delete pPosition;
172
173     }
174
175
176     //place the ship
177
178     QPointF * pPosition = findRandomFreeSlot();
179     if (pPosition == NULL)
180     {
181         // Game cannot begin without a free position for ship, so give an error message and return
182
183         QMessageBox::critical(NULL,"Error! Too many objects on screen","No free space to place the ship. The game cannot start. Please choose another level.");
184         return;
185     }
186
187     QList<QPixmap> shipImages;
188     shipImages.append(QPixmap(":/pix/laiva.png"));
189     shipImages.append(QPixmap(":/pix/laiva_1aave.png"));
190     shipImages.append(QPixmap(":/pix/laiva_2aave.png"));
191     shipImages.append(QPixmap(":/pix/laiva_3aave.png"));
192     shipImages.append(QPixmap(":/pix/laiva_4aave.png"));
193     shipImages.append(QPixmap(":/pix/laiva_5aave.png"));
194     shipImages.append(QPixmap(":/pix/laiva_6aave.png"));
195     shipImages.append(QPixmap(":/pix/laiva_7aave.png"));
196     shipImages.append(QPixmap(":/pix/laiva_8aave.png"));
197     shipImages.append(QPixmap(":/pix/laiva_9aave.png"));
198     shipImages.append(QPixmap(":/pix/laiva_10aave.png"));
199
200     Ship * pShip = new Ship (shipImages);
201     pShip->setData(0,"ship");
202     pShip->setPos(*pPosition);
203     addItem(pShip);
204     connect(pShip,SIGNAL(pickingGhost(QGraphicsItem*)),this, SLOT(removeGhost(QGraphicsItem*)) );
205     connect(pShip,SIGNAL(droppingGhosts(int)),this,SLOT(ghostsDropped(int)));
206     connect(this,SIGNAL(vibrationActivated(bool)),pShip,SLOT(setVibrationActivate(bool)));
207     pShip->startMoving();
208     movingItems_.append(pShip);
209     connect(this,SIGNAL(pauseOn()),pShip,SLOT(stopMoving()));
210     connect(this,SIGNAL(pauseOff()),pShip,SLOT(startMoving()));
211     foreach (Octopus* pOctopus, octopusList)
212     {
213         connect(pOctopus,SIGNAL(droppingGhosts()),pShip,SLOT(dropAllGhosts()));
214     }
215     delete pPosition;
216
217
218 }
219
220 void SeaScene::setupMap(Level level)
221 {
222     setupMap(level.getNumberOfGhosts(),level.getNumberOfRocks(),level.getNumberOfOctopuses(),level.getOctopusSpeed());
223 }
224
225 void SeaScene::spreadGhosts(int ghosts)
226 {
227
228
229     //the octopuses and the ship may have moved from their original positions,
230     //so the list of free slots must be adjusted to exclude their current positions
231
232     QList<QPointF> temporarilyReservedSlots;
233
234     foreach (QGraphicsItem* pItem, movingItems_)
235     {
236         if (pItem == NULL)
237         {
238  //           qDebug() << "NULL item in movingItems_";
239             continue;
240         }
241
242         //round x and y down to fit the slot size
243         int x = pItem->x();
244         x = x/40;
245         x = x*40;
246
247         int y = pItem->y();
248         y = y/40;
249         y=y*40;
250
251
252         QPointF position (x,y);
253
254         //remove the tiles (potentially) occupied by the item from free slots and place in temp list if was in the list before
255
256         if (freeTiles_.removeOne(position))
257             temporarilyReservedSlots.append(position);
258
259
260         position.setX(x+40);
261
262         if (freeTiles_.removeOne(position))
263             temporarilyReservedSlots.append(position);
264
265         position.setY(y+40);
266
267         if (freeTiles_.removeOne(position))
268             temporarilyReservedSlots.append(position);
269
270         position.setX(x);
271
272         if (freeTiles_.removeOne(position))
273             temporarilyReservedSlots.append(position);
274
275     }
276
277
278     //spread ghosts in random free slots
279
280     for (int i=0; i < ghosts; i++)
281     {
282         QPointF * pPosition = findRandomFreeSlot();
283
284         //If there was no room no point to continue
285         if (pPosition == NULL)
286             return;
287
288         QPixmap ghostPixmap(":/pix/aave.png");
289         QGraphicsPixmapItem * pGhost = addPixmap(ghostPixmap);
290         pGhost->setData(0,"ghost");
291         pGhost->setPos(*pPosition);
292         delete pPosition;
293     }
294
295     //return the slots occupied by moving items to free slots
296     freeTiles_.append(temporarilyReservedSlots);
297
298     //clear temp for the next round
299     temporarilyReservedSlots.clear();
300 }
301
302 QPointF* SeaScene::findRandomFreeSlot()
303 {
304     if (freeTiles_.isEmpty())
305         return NULL;
306
307     int index = qrand()%freeTiles_.size();
308
309 //    qDebug()  << index << " index";
310     return new QPointF (freeTiles_.takeAt(index));
311
312 }
313
314 void SeaScene::removeGhost(QGraphicsItem *pGhost)
315 {
316     removeItem(pGhost);  //remove the item from scene
317     freeTiles_.append(pGhost->scenePos()); //add the item's position to free slots
318     delete pGhost;
319     ghostsLeft_--;
320     if (ghostsLeft_ == 0)
321     {
322         emit allGhostsPicked();
323  //       qDebug() << "All ghosts picked!";
324     }
325 }
326
327 void SeaScene::ghostsDropped(int ghosts)
328 {
329     ghostsLeft_ += ghosts;
330
331     spreadGhosts(ghosts);
332 }
333
334 void SeaScene::pause(bool paused)
335 {
336     //    qDebug() << "pause pressed " << paused;
337         if (paused_ == paused)
338                 return;
339
340         paused_ = paused;
341
342         if (paused == false)
343         {
344      //       qDebug() << "starting to move again";
345             emit pauseOff();
346             screenLitKeeper_.keepScreenLit(true);
347             if (pPausetextItem_)
348                 pPausetextItem_->hide();
349
350             autopauseTimer.start(); //Start counting towards autopause
351         }
352
353         else
354         {
355          qDebug("about to stop movement");
356             emit pauseOn();
357             screenLitKeeper_.keepScreenLit(false);
358             if (pPausetextItem_ != NULL)
359             {
360                 qDebug() << "about to show the pause text";
361                 pPausetextItem_->show();
362                 qDebug() << "showing pause text";
363             }
364                 else qDebug() << "No pause text available";
365
366             autopauseTimer.stop(); //No need to count toward autopause when already paused
367         }
368 }
369
370 void SeaScene::vibrationActivate(bool on)
371 {
372     emit vibrationActivated(on);
373 }
374
375 void SeaScene::handleScreenTapped()
376 {
377
378     //If the game is going just pause it
379     if (!paused_)
380     {
381         pPauseAction_->setChecked(true);
382         return;
383     }
384
385     //If the game is paused, chacl if menu item was selected
386
387     QList<QGraphicsItem *> items = selectedItems();
388
389     //if nothing selected resume play
390
391     if (items.isEmpty())
392     {
393         pPauseAction_->setChecked(false);
394         return;
395
396     }
397
398     //If something was selected check if it was one of the menu items and act on it
399     //(Nothing else should be made selectable anyway)
400
401     //Menu functions
402
403     QGraphicsItem* pItem = items.at(0); //Selecting an item brings here, thus only selecting one item should be possible
404                                        //... so we can just take the first one
405
406
407     if (pItem == pRestartGameItem_)
408     {
409         qDebug() << "game restart requested";
410         restartGame();
411     }
412
413     else if (pItem == pRestartLevelItem_)
414     {
415         qDebug() << "Level restart requested";
416         restartLevel();
417
418     }
419
420     else if (pItem == pSettingsItem_)
421     {
422     //Temporary code for settings, likely to be turned into a QML dialog
423
424           QMessageBox::StandardButton buttonpressed = QMessageBox::question(NULL,"Settings","Do you wish to have vibration effects enabled?", QMessageBox::Yes | QMessageBox::No);
425
426           if (buttonpressed == QMessageBox::Yes)
427               pVibrateAction_->setChecked(true);
428           if (buttonpressed == QMessageBox::No)
429               pVibrateAction_->setChecked(false);
430     }
431
432     else if (pItem == pAboutItem_)
433     {
434         about();
435     }
436
437     else if (pItem == pQuitItem_)
438     {
439         qApp->quit();
440     }
441
442
443     //Selection is just used to get notice of a menu item being clicked, removed after use
444
445     clearSelection();
446
447     //The user propably went to paused state just to access menu, so unpause
448
449     pPauseAction_->setChecked(false);
450
451 }
452
453
454
455 void SeaScene::createMenuItems()
456 {
457
458     QFont font;
459     font.setPixelSize(35);
460
461
462
463     pPausetextItem_ = new QGraphicsTextItem;
464     pPausetextItem_->setHtml("<font size = \"5\" color = darkorange> Game paused. Tap to continue.");
465     pPausetextItem_->setZValue(1000);
466     pPausetextItem_->setPos(200,50);
467     addItem(pPausetextItem_);
468     pPausetextItem_->hide();
469
470     menuItemCount_ = 0;
471
472     QString menufonthtml = "<font size = \"4\" color = darkorange>";
473
474     pRestartGameItem_ = new QGraphicsTextItem;
475     pRestartGameItem_->setHtml(tr("Restart <br> game").prepend(menufonthtml));
476     prepareForMenu(pRestartGameItem_);
477
478     pRestartLevelItem_ = new QGraphicsTextItem;
479     pRestartLevelItem_->setHtml(tr("Restart <br> level").prepend(menufonthtml));
480     prepareForMenu(pRestartLevelItem_);
481
482     pSettingsItem_ = new QGraphicsTextItem;
483     pSettingsItem_->setHtml(tr("Vibration <br> effects").prepend(menufonthtml));
484     prepareForMenu(pSettingsItem_);
485
486     pAboutItem_ = new QGraphicsTextItem;
487     pAboutItem_->setHtml(tr("About <br> game").prepend(menufonthtml));
488     prepareForMenu(pAboutItem_);
489
490     pQuitItem_ = new QGraphicsTextItem;
491     pQuitItem_->setHtml(tr("Quit <br> game").prepend(menufonthtml));
492     prepareForMenu(pQuitItem_);
493
494 }
495
496 void SeaScene::prepareForMenu(QGraphicsItem * pItem)
497 {
498
499     //Menu items have pause text item as their parent and are thus added to scene automatically
500     //They are also shown and hidden with it, resulting in the menu being visble when the game is paused
501     //Their coordinates are given relative to the parent.
502
503
504     pItem->setParentItem(pPausetextItem_);
505     pItem->setZValue(1000);
506     pItem->setFlag(QGraphicsItem::ItemIsSelectable);
507     pItem->setY(150);
508     pItem->setX(menuItemCount_++*160-150);
509  }
510
511
512 void SeaScene::about()
513 {
514     QMessageBox::about(NULL, tr("About %1").arg(QApplication::applicationName()),
515                        tr("Version %1"
516                           "<p>Copyright 2011 Heli Hyv&auml;ttinen"
517                           "<p>License: General Public License v2"
518                           "<p>Bug Reports: https://bugs.maemo.org/ "
519                           "enter_bug.cgi?product=Ghosts%20Overboard"
520                           ).arg(QApplication::applicationVersion()));
521
522
523
524 }
525
526
527 void SeaScene::restartLevel()
528 {
529     setupMap(levelList_.value(currentLevel_));  //value() returns default constructor Level if index is invalid, so no risk of crash
530     vibrationActivate(pVibrateAction_->isChecked());  //Vibration effects are lost without this
531    // qDebug() << pVibrateAction_->isChecked();
532     autopauseTimer.start();  //reset counting towards autopause
533 }
534
535
536
537 void SeaScene::nextLevel()
538 {
539
540     currentLevel_++;
541
542     if (levelList_.empty())
543         setupMap(Level());
544
545
546     if ( currentLevel_ < levelList_.size() )
547     {
548        restartLevel();
549     }
550
551     else //Victory!
552     {
553
554        QDialog* pVictoryDialog = new QDialog();
555        pVictoryDialog->setWindowTitle(tr("You won!"));
556
557
558        QPushButton* pPlayAgainButton = new QPushButton(tr("Play again"));
559 //       QPushButton* pQuitButton = new QPushButton(tr("Quit game"));
560
561        QPixmap victoryIcon (":/pix/aavesaari.png");
562        QLabel* pVictoryLabel = new QLabel();
563        pVictoryLabel->setPixmap(victoryIcon);
564
565        QLabel* pTextLabel = new QLabel(tr("Congratulations! <p>You have saved all the ghosts."));
566
567
568        QVBoxLayout* pMainLayout = new QVBoxLayout;
569
570        QHBoxLayout* pTopLayout = new QHBoxLayout;
571        pMainLayout->addLayout(pTopLayout);
572
573        pTopLayout->addWidget(pVictoryLabel);
574        pTopLayout->addWidget(pTextLabel);
575
576
577
578        QHBoxLayout* pButtonLayout = new QHBoxLayout();
579        pMainLayout->addLayout(pButtonLayout);
580
581  //      pButtonLayout->addWidget(pQuitButton);
582        pButtonLayout->addWidget(pPlayAgainButton);
583
584
585
586        pVictoryDialog->setLayout(pMainLayout);
587
588        connect(pPlayAgainButton, SIGNAL(clicked()),pVictoryDialog,SLOT(accept()));
589
590        pVictoryDialog->exec();
591
592         //Never mind if the user cancels the dialog: restart the game anyway
593
594        restartGame();
595     }
596 }
597
598
599 void SeaScene::restartGame()
600 {
601     currentLevel_ = 0;
602     restartLevel();
603 }
604
605
606 void SeaScene::forcePause()
607 {
608     //Pause without setting the pause action state
609     pause(true);
610 }
611
612 void::SeaScene::softContinue()
613 {
614     //Continue if not being paused by the user
615     // Reverts forcePause()
616
617     pause(pPauseAction_->isChecked());
618 }