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