Spreading ghosts now handles situations where there is no free slot left
[ghostsoverboard] / seascene.cpp
1 #include "seascene.h"
2 #include <QGraphicsPixmapItem>
3 #include <QDebug>
4
5 const QString ghostImageFilename_ = ":/pix/aave.png";
6 const QString rockImageFilename_ =":/pix/kari.png";
7 const QString octopusImageFilename_= ":/pix/tursas.png";
8
9
10 SeaScene::SeaScene(QObject *parent) :
11     QGraphicsScene(parent)
12 {
13
14
15 }
16
17 void SeaScene::setupMap(int ghosts, int rocks, int octopuses)
18 {
19     //empty the list of free slots
20     freeTiles_.clear();
21
22     //fill the list of free slots
23
24     int numberOfXTiles  = width() / 40;
25     int numberOfYTiles = height() /40;
26
27     qDebug() << numberOfXTiles << " slots in x direction";
28     qDebug() << numberOfYTiles << " slots in y rirection";
29
30     for (int i = 0; i < numberOfXTiles; i++ )
31     {
32         for (int j = 0; j < numberOfYTiles; j++)
33         {
34             freeTiles_.append(QPointF(i*40,j*40));
35         }
36     }
37     spreadGhosts(ghosts);
38 }
39
40 void SeaScene::spreadGhosts(int ghosts)
41 {
42     for (int i=0; i < ghosts; i++)
43     {
44         QPointF * pPosition = findRandomFreeSlot();
45
46         //If there was no room no point to continue
47         if (pPosition == NULL)
48             return;
49
50         QGraphicsPixmapItem * pGhost = addPixmap(QPixmap(":/pix/aave.png"));
51         pGhost->setData(0,"ghost");
52         pGhost->setPos(*pPosition);
53         delete pPosition;
54     }
55 }
56
57 QPointF* SeaScene::findRandomFreeSlot()
58 {
59     if (freeTiles_.isEmpty())
60         return NULL;
61
62     int index = qrand()%freeTiles_.size();
63
64     qDebug()  << index << " index";
65     return new QPointF (freeTiles_.takeAt(index));
66
67 }