-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfishmanager.cpp
86 lines (70 loc) · 2.13 KB
/
fishmanager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <QDebug>
#include <QList>
#include <QMap>
#include <QtAlgorithms>
#include <QTimer>
#include "fish.h"
#include "fishmanager.h"
FishManager::FishManager(QObject* parent)
: QObject(parent)
{
}
unsigned int FishManager::registerFish(QObject* internal)
{
qDebug() << QString("registerFish() invoked");
// only Fish* are passed to this method from QML
unsigned int num = getNextNumber(static_cast<Fish*>(internal));
qDebug() << QString("registered fish with id = " + QString::number(num));
return num;
}
void FishManager::chooseWinningFish()
{
qDebug() << QString("FishManager::chooseWinningFish() invoked");
connect(&winningFishTimer_,SIGNAL(timeout()),this,SLOT(killOneFish()));
winningFishTimer_.start(1000);
}
int FishManager::killOneFish()
{
QMap<unsigned int,Fish*> aliveFishes = getAliveFishes();
int aliveFishesCount = aliveFishes.count();
if (aliveFishesCount <= 1)
{
winningFishTimer_.stop();
return aliveFishesCount;
}
qDebug() << QString("Alive fishes before killing: " + QString::number(aliveFishesCount));
boost::random::uniform_int_distribution<> random_distribution(0,aliveFishesCount-1);
int randomized = random_distribution(rng_);
QMap<unsigned int,Fish*>::iterator choosen = aliveFishes.begin() + randomized;
Fish* choosenFish = choosen.value();
choosenFish->die();
return aliveFishesCount-1;
}
QMap<unsigned int,Fish*> FishManager::getAliveFishes() const
{
QMap<unsigned int,Fish*> result;
QMapIterator<unsigned int,Fish*> iter(fishes);
while (iter.hasNext())
{
iter.next();
if (iter.value()->isDying() || !iter.value()->isAlive()) // omit dying or already dead fishes
continue;
result.insert(iter.key(),iter.value());
}
return result;
}
unsigned int FishManager::getNextNumber(Fish* fish)
{
if (fishes.isEmpty())
{
fishes.insert(1,fish);
return 1;
}
QList<unsigned int> numbers = fishes.keys();
qSort(numbers);
QList<unsigned int>::const_iterator last = numbers.constEnd();
--last; // valid, because we checked for empty list at the beginning
unsigned int newNumber = *last + 1;
fishes.insert(newNumber,fish);
return newNumber;
}