forked from SharifAIChallenge/AIC16-Client-Cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Controller.cpp
123 lines (110 loc) · 2.14 KB
/
Controller.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
* Controller.cpp
*
* Created on: Feb 3, 2015
* Author: rmin
*/
#include "Controller.h"
#include "util.h"
#include "Network.h"
#include <chrono>
#include <unistd.h>
int toInt(std::string str) {
int ans=0;
for(int i = 0; i < (int)str.size(); i++) {
ans*=10;
ans+=str[i]-'0';
}
return ans;
}
Controller::Controller(std::string *args)
{
ip = args[0];
port = toInt(args[1]);
token = args[2];
retryDelay = toInt(args[3]);
time = 0;
eventHandler = NULL;
game = NULL;
network = NULL;
client = NULL;
}
Controller::~Controller()
{
if (eventHandler != NULL)
delete eventHandler;
if (game != NULL)
delete game;
if (network != NULL)
delete network;
if (client != NULL)
delete client;
}
void Controller::start()
{
try
{
network = new Network(this);
network->setConnectionData(ip, port, token);
eventHandler = new EventHandler(network);
game = new Game();
client = new AI();
int counter = 0;
while (counter < 10 && network != NULL && !network->getIsConnected())
{
counter++;
std::cerr << "Trying to connect #" << counter << std::endl;
network->connect();
if (network->getIsTerminated() == true)
break;
usleep(retryDelay * 1000);
}
std::cerr << "Connection Terminated" << std::endl;
delete eventHandler;
delete game;
delete client;
delete network;
}
catch (const char* str)
{
std::cerr << str << std::endl;
}
}
void Controller::handleMessage(Message &msg)
{
if (msg.getName() == Constants::MESSAGE_KEY_TURN)
{
handleTurnMessage(msg);
}
else if (msg.getName() == Constants::MESSAGE_KEY_INIT)
{
handleInitMessage(msg);
}
else if (msg.getName() == Constants::MESSAGE_KEY_SHUTDOWN
|| msg.getName() == Constants::MESSAGE_KEY_WRONG_TOKEN)
{
network->terminate();
}
}
void Controller::handleTurnMessage(Message &msg) {
game->handleTurnMessage(msg);
doTurn();
}
void Controller::handleInitMessage(Message &msg) {
game->handleInitMessage(msg);
}
void Controller::run()
{
client->doTurn(game);
}
void Controller::doTurn()
{
try
{
std::thread *thr = new std::thread(&Controller::run, this);
}
catch (...)
{
std::cerr << "Exception in Controller::doTurn" << std::endl;
}
}