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