source: network-game/server/server.cpp@ 85bf1e2

Last change on this file since 85bf1e2 was d05086b, checked in by dportnoy <dmp1488@…>, 11 years ago

Support for logging to a textfile

  • Property mode set to 100644
File size: 35.2 KB
RevLine 
[2488852]1#include <cstdlib>
[371ce29]2#include <cstdio>
[e3535b3]3#include <unistd.h>
[2488852]4#include <string>
[e3535b3]5#include <iostream>
[3b1efcc]6#include <sstream>
[d05086b]7#include <fstream>
[edfd1d0]8#include <cstring>
[60017fc]9#include <cmath>
[371ce29]10
[01d0d00]11#include <vector>
12#include <map>
13
[d05086b]14#include <csignal>
15
[d211210]16#include <sys/time.h>
17
[73f75c1]18#include <sys/socket.h>
[371ce29]19#include <netdb.h>
[73f75c1]20#include <netinet/in.h>
21#include <arpa/inet.h>
22
[b128109]23#include <crypt.h>
24
[edfd1d0]25/*
[e3535b3]26#include <openssl/bio.h>
27#include <openssl/ssl.h>
28#include <openssl/err.h>
[edfd1d0]29*/
[e3535b3]30
[b53c6b3]31#include "../common/Compiler.h"
[3b1efcc]32#include "../common/Common.h"
[9b5d30b]33#include "../common/MessageProcessor.h"
[60017fc]34#include "../common/WorldMap.h"
[edfd1d0]35#include "../common/Player.h"
[8dad966]36#include "../common/Projectile.h"
[b53c6b3]37
[36082e8]38#include "DataAccess.h"
[d2b411a]39
[e3535b3]40using namespace std;
41
[d05086b]42bool done;
43
[d211210]44// from used to be const. Removed that so I could take a reference
45// and use it to send messages
[d05086b]46bool processMessage(const NETWORK_MSG &clientMsg, struct sockaddr_in &from, MessageProcessor &msgProcessor, map<unsigned int, Player>& mapPlayers, WorldMap* gameMap, unsigned int& unusedPlayerId, NETWORK_MSG &serverMsg, int sock, int &scoreBlue, int &scoreRed, ofstream& outputLog);
[01d0d00]47
[8dad966]48void updateUnusedPlayerId(unsigned int& id, map<unsigned int, Player>& mapPlayers);
49void updateUnusedProjectileId(unsigned int& id, map<unsigned int, Projectile>& mapProjectiles);
[c76134b]50void damagePlayer(Player *p, int damage);
[8e540f4]51
[d05086b]52void addObjectToMap(WorldMap::ObjectType objectType, int x, int y, WorldMap* gameMap, map<unsigned int, Player>& mapPlayers, MessageProcessor &msgProcessor, int sock, ofstream& outputLog);
[411c1ae]53
[73f75c1]54// this should probably go somewhere in the common folder
[e3535b3]55void error(const char *msg)
56{
57 perror(msg);
58 exit(0);
59}
60
[01d0d00]61Player *findPlayerByName(map<unsigned int, Player> &m, string name)
[2488852]62{
[01d0d00]63 map<unsigned int, Player>::iterator it;
[2488852]64
[01d0d00]65 for (it = m.begin(); it != m.end(); it++)
[2488852]66 {
[01d0d00]67 if ( it->second.name.compare(name) == 0 )
68 return &(it->second);
[2488852]69 }
70
71 return NULL;
72}
73
[01d0d00]74Player *findPlayerByAddr(map<unsigned int, Player> &m, const sockaddr_in &addr)
[73f75c1]75{
[01d0d00]76 map<unsigned int, Player>::iterator it;
[73f75c1]77
[01d0d00]78 for (it = m.begin(); it != m.end(); it++)
[73f75c1]79 {
[01d0d00]80 if ( it->second.addr.sin_addr.s_addr == addr.sin_addr.s_addr &&
81 it->second.addr.sin_port == addr.sin_port )
82 return &(it->second);
[73f75c1]83 }
84
85 return NULL;
86}
87
[d05086b]88void quit(int sig) {
89 done = true;
90}
91
[e3535b3]92int main(int argc, char *argv[])
93{
94 int sock, length, n;
95 struct sockaddr_in server;
[3b1efcc]96 struct sockaddr_in from; // info of client sending the message
[e084950]97 NETWORK_MSG clientMsg, serverMsg;
[9b5d30b]98 MessageProcessor msgProcessor;
[01d0d00]99 map<unsigned int, Player> mapPlayers;
[8dad966]100 map<unsigned int, Projectile> mapProjectiles;
101 unsigned int unusedPlayerId = 1, unusedProjectileId = 1;
[b8601ee]102 int scoreBlue, scoreRed;
[d05086b]103 ofstream outputLog;
104
105 done = false;
[b8601ee]106
107 scoreBlue = 0;
108 scoreRed = 0;
[e084950]109
[d05086b]110 signal(SIGINT, quit);
111
[edfd1d0]112 //SSL_load_error_strings();
113 //ERR_load_BIO_strings();
114 //OpenSSL_add_all_algorithms();
[e3535b3]115
116 if (argc < 2) {
[73f75c1]117 cerr << "ERROR, no port provided" << endl;
118 exit(1);
[e3535b3]119 }
[60017fc]120
[d05086b]121 outputLog.open("server.log", ios::app);
122 outputLog << "Started server on " << getCurrentDateTimeString() << endl;
123
[7b43385]124 WorldMap* gameMap = WorldMap::loadMapFromFile("../data/map.txt");
[6e66ffd]125
126 // add some items to the map. They will be sent out
127 // to players when they login
[5f868c0]128 for (int y=0; y<gameMap->height; y++) {
129 for (int x=0; x<gameMap->width; x++) {
130 switch (gameMap->getStructure(x, y)) {
131 case WorldMap::STRUCTURE_BLUE_FLAG:
132 gameMap->addObject(WorldMap::OBJECT_BLUE_FLAG, x*25+12, y*25+12);
133 break;
134 case WorldMap::STRUCTURE_RED_FLAG:
135 gameMap->addObject(WorldMap::OBJECT_RED_FLAG, x*25+12, y*25+12);
136 break;
137 }
138 }
139 }
[6e66ffd]140
[371ce29]141 sock = socket(AF_INET, SOCK_DGRAM, 0);
[5b1e31e]142 if (sock < 0)
143 error("Opening socket");
[e3535b3]144 length = sizeof(server);
145 bzero(&server,length);
146 server.sin_family=AF_INET;
147 server.sin_port=htons(atoi(argv[1]));
[2488852]148 server.sin_addr.s_addr=INADDR_ANY;
149 if ( bind(sock, (struct sockaddr *)&server, length) < 0 )
[e084950]150 error("binding");
[73f75c1]151
[371ce29]152 set_nonblock(sock);
153
[da692b9]154 bool broadcastResponse;
[d211210]155 timespec ts;
[430c80e]156 int timeLastUpdated = 0, curTime = 0, timeLastBroadcast = 0;
[d05086b]157 while (!done) {
[371ce29]158
159 usleep(5000);
160
[d211210]161 clock_gettime(CLOCK_REALTIME, &ts);
[430c80e]162 // make the number smaller so millis can fit in an int
[d69eb32]163 ts.tv_sec -= 1368000000;
[430c80e]164 curTime = ts.tv_sec*1000 + ts.tv_nsec/1000000;
[d211210]165
[430c80e]166 if (timeLastUpdated == 0 || (curTime-timeLastUpdated) >= 50) {
[d211210]167 timeLastUpdated = curTime;
168
[d05086b]169 msgProcessor.cleanAckedMessages(&outputLog);
170 msgProcessor.resendUnackedMessages(sock, &outputLog);
[9b5d30b]171
[11d21ee]172 map<unsigned int, Player>::iterator it;
173
174 // set targets for all chasing players (or make them attack if they're close enough)
175 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++) {
[c76134b]176 // check if it's time to revive dead players
177 if (it->second.isDead) {
178 if (getCurrentMillis() - it->second.timeDied >= 10000) {
179 it->second.isDead = false;
180
181 POSITION spawnPos;
182
183 switch (it->second.team) {
184 case 0:// blue team
185 spawnPos = gameMap->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
186 break;
187 case 1:// red team
188 spawnPos = gameMap->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
189 break;
190 default:
191 // should never go here
192 cout << "Error: Invalid team" << endl;
193 break;
194 }
195
196 // spawn the player to the right of their flag location
197 spawnPos.x = (spawnPos.x+1) * 25 + 12;
198 spawnPos.y = spawnPos.y * 25 + 12;
199
200 it->second.pos = spawnPos.toFloat();
[66c4ec4]201 it->second.target = spawnPos;
202 it->second.health = it->second.maxHealth;
[c76134b]203
204 serverMsg.type = MSG_TYPE_PLAYER;
205 it->second.serialize(serverMsg.buffer);
206
207 map<unsigned int, Player>::iterator it2;
208 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
209 {
[d05086b]210 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[c76134b]211 error("sendMessage");
212 }
213 }
214
215 continue;
216 }
217
[5b1e31e]218 if (it->second.updateTarget(mapPlayers)) {
219 serverMsg.type = MSG_TYPE_PLAYER;
220 it->second.serialize(serverMsg.buffer);
[11d21ee]221
[5b1e31e]222 map<unsigned int, Player>::iterator it2;
223 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
224 {
[d05086b]225 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[5b1e31e]226 error("sendMessage");
[11d21ee]227 }
228 }
229 }
230
[8dad966]231 // move all players
[d211210]232 // maybe put this in a separate method
[23559e7]233 FLOAT_POSITION oldPos;
234 bool broadcastMove = false;
[d211210]235 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++) {
[23559e7]236 oldPos = it->second.pos;
237 if (it->second.move(gameMap)) {
238
239 // check if the move needs to be canceled
240 switch(gameMap->getElement(it->second.pos.x/25, it->second.pos.y/25)) {
241 case WorldMap::TERRAIN_NONE:
242 case WorldMap::TERRAIN_OCEAN:
243 case WorldMap::TERRAIN_ROCK:
[e4c60ba]244 {
[23559e7]245 it->second.pos = oldPos;
246 it->second.target.x = it->second.pos.x;
247 it->second.target.y = it->second.pos.y;
[5b1e31e]248 it->second.isChasing = false;
[23559e7]249 broadcastMove = true;
250 break;
[e4c60ba]251 }
[23559e7]252 default:
253 // if there are no obstacles, do nothing
254 break;
255 }
256
[e4c60ba]257 WorldMap::ObjectType flagType;
258 POSITION pos;
[7553db9]259 bool flagTurnedIn = false;
[446dc65]260 bool flagReturned = false;
261 bool ownFlagAtBase = false;
262
[e4c60ba]263 switch(gameMap->getStructure(it->second.pos.x/25, it->second.pos.y/25)) {
264 case WorldMap::STRUCTURE_BLUE_FLAG:
265 {
[7553db9]266 if (it->second.team == 0 && it->second.hasRedFlag)
267 {
[446dc65]268 // check that your flag is at your base
269 pos = gameMap->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
270
271 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
272 vector<WorldMap::Object>::iterator itObjects;
273
274 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
275 if (itObjects->type == WorldMap::OBJECT_BLUE_FLAG) {
276 if (itObjects->pos.x == pos.x*25+12 && itObjects->pos.y == pos.y*25+12) {
277 ownFlagAtBase = true;
278 break;
279 }
280 }
281 }
282
283 if (ownFlagAtBase) {
284 it->second.hasRedFlag = false;
285 flagType = WorldMap::OBJECT_RED_FLAG;
286 pos = gameMap->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
287 flagTurnedIn = true;
288 scoreBlue++;
289 }
[e4c60ba]290 }
[7553db9]291
292 break;
[e4c60ba]293 }
294 case WorldMap::STRUCTURE_RED_FLAG:
295 {
[7553db9]296 if (it->second.team == 1 && it->second.hasBlueFlag)
297 {
[446dc65]298 // check that your flag is at your base
299 pos = gameMap->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
300
301 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
302 vector<WorldMap::Object>::iterator itObjects;
303
304 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
305 if (itObjects->type == WorldMap::OBJECT_RED_FLAG) {
306 if (itObjects->pos.x == pos.x*25+12 && itObjects->pos.y == pos.y*25+12) {
307 ownFlagAtBase = true;
308 break;
309 }
310 }
311 }
312
313 if (ownFlagAtBase) {
314 it->second.hasBlueFlag = false;
315 flagType = WorldMap::OBJECT_BLUE_FLAG;
316 pos = gameMap->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
317 flagTurnedIn = true;
318 scoreRed++;
319 }
[e4c60ba]320 }
321
[7553db9]322 break;
323 }
324 }
[e4c60ba]325
[7553db9]326 if (flagTurnedIn) {
327 // send an OBJECT message to add the flag back to its spawn point
328 pos.x = pos.x*25+12;
329 pos.y = pos.y*25+12;
330 gameMap->addObject(flagType, pos.x, pos.y);
[e4c60ba]331
[7553db9]332 serverMsg.type = MSG_TYPE_OBJECT;
333 gameMap->getObjects()->back().serialize(serverMsg.buffer);
[e4c60ba]334
[7553db9]335 map<unsigned int, Player>::iterator it2;
336 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
337 {
[d05086b]338 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[7553db9]339 error("sendMessage");
[e4c60ba]340 }
[7553db9]341
[b8601ee]342 serverMsg.type = MSG_TYPE_SCORE;
343 memcpy(serverMsg.buffer, &scoreBlue, 4);
344 memcpy(serverMsg.buffer+4, &scoreRed, 4);
345
346 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
347 {
[d05086b]348 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[b8601ee]349 error("sendMessage");
350 }
351
[7553db9]352 // this means a PLAYER message will be sent
353 broadcastMove = true;
[e4c60ba]354 }
355
[446dc65]356 // go through all objects and check if the player is close to one and if its their flag
357 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
358 vector<WorldMap::Object>::iterator itObjects;
359 POSITION structPos;
360
361 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
362 POSITION pos = itObjects->pos;
363
364 if (posDistance(it->second.pos, pos.toFloat()) < 10) {
365 if (it->second.team == 0 &&
366 itObjects->type == WorldMap::OBJECT_BLUE_FLAG) {
367 structPos = gameMap->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
368 flagReturned = true;
369 break;
370 } else if (it->second.team == 1 &&
371 itObjects->type == WorldMap::OBJECT_RED_FLAG) {
372 structPos = gameMap->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
373 flagReturned = true;
374 break;
375 }
376 }
377 }
378
379 if (flagReturned) {
380 itObjects->pos.x = structPos.x*25+12;
381 itObjects->pos.y = structPos.y*25+12;
382
383 serverMsg.type = MSG_TYPE_OBJECT;
384 itObjects->serialize(serverMsg.buffer);
385
386 map<unsigned int, Player>::iterator it2;
387 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
388 {
[d05086b]389 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[446dc65]390 error("sendMessage");
391 }
392 }
393
[23559e7]394 if (broadcastMove) {
395 serverMsg.type = MSG_TYPE_PLAYER;
396 it->second.serialize(serverMsg.buffer);
397
398 cout << "about to broadcast move" << endl;
[b07eeac]399 map<unsigned int, Player>::iterator it2;
[23559e7]400 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
401 {
[d05086b]402 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[23559e7]403 error("sendMessage");
404 }
[d211210]405 }
406 }
[8dad966]407
408 // check if the player's attack animation is complete
409 if (it->second.isAttacking && it->second.timeAttackStarted+it->second.attackCooldown <= getCurrentMillis()) {
410 it->second.isAttacking = false;
[8795a38]411 cout << "Attack animation is complete" << endl;
[8dad966]412
413 //send everyone an ATTACK message
414 cout << "about to broadcast attack" << endl;
415
416 serverMsg.type = MSG_TYPE_ATTACK;
417 memcpy(serverMsg.buffer, &it->second.id, 4);
418 memcpy(serverMsg.buffer+4, &it->second.targetPlayer, 4);
419
420 map<unsigned int, Player>::iterator it2;
421 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
422 {
[d05086b]423 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[8dad966]424 error("sendMessage");
425 }
426
427 if (it->second.attackType == Player::ATTACK_MELEE) {
[ff2133a]428 cout << "Melee attack" << endl;
429
[8dad966]430 Player* target = &mapPlayers[it->second.targetPlayer];
[c76134b]431 damagePlayer(target, it->second.damage);
[8dad966]432
[411c1ae]433 if (target->isDead) {
434 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
435 if (target->hasBlueFlag)
436 flagType = WorldMap::OBJECT_BLUE_FLAG;
437 else if (target->hasRedFlag)
438 flagType = WorldMap::OBJECT_RED_FLAG;
439
440 if (flagType != WorldMap::OBJECT_NONE) {
[d05086b]441 addObjectToMap(flagType, target->pos.x, target->pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
[411c1ae]442 }
443 }
444
[8dad966]445 serverMsg.type = MSG_TYPE_PLAYER;
446 target->serialize(serverMsg.buffer);
447 }else if (it->second.attackType == Player::ATTACK_RANGED) {
[ff2133a]448 cout << "Ranged attack" << endl;
449
[8dad966]450 Projectile proj(it->second.pos.x, it->second.pos.y, it->second.targetPlayer, it->second.damage);
451 proj.id = unusedProjectileId;
452 updateUnusedProjectileId(unusedProjectileId, mapProjectiles);
453 mapProjectiles[proj.id] = proj;
454
[8795a38]455 int x = it->second.pos.x;
456 int y = it->second.pos.y;
457
[8dad966]458 serverMsg.type = MSG_TYPE_PROJECTILE;
[8795a38]459 memcpy(serverMsg.buffer, &proj.id, 4);
460 memcpy(serverMsg.buffer+4, &x, 4);
461 memcpy(serverMsg.buffer+8, &y, 4);
462 memcpy(serverMsg.buffer+12, &it->second.targetPlayer, 4);
[8dad966]463 }else {
464 cout << "Invalid attack type: " << it->second.attackType << endl;
465 }
466
467 // broadcast either a PLAYER or PROJECTILE message
[ff2133a]468 cout << "Broadcasting player or projectile message" << endl;
[8dad966]469 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
470 {
[d05086b]471 if (msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[8dad966]472 error("sendMessage");
473 }
[ff2133a]474 cout << "Done broadcasting" << endl;
[8dad966]475 }
476 }
477
478 // move all projectiles
479 map<unsigned int, Projectile>::iterator itProj;
480 for (itProj = mapProjectiles.begin(); itProj != mapProjectiles.end(); itProj++) {
[c76134b]481 cout << "About to call projectile move" << endl;
[8dad966]482 if (itProj->second.move(mapPlayers)) {
483 // send a REMOVE_PROJECTILE message
[ff2133a]484 cout << "send a REMOVE_PROJECTILE message" << endl;
[8dad966]485 serverMsg.type = MSG_TYPE_REMOVE_PROJECTILE;
486 memcpy(serverMsg.buffer, &itProj->second.id, 4);
487 mapProjectiles.erase(itProj->second.id);
488
489 map<unsigned int, Player>::iterator it2;
[ff2133a]490 cout << "Broadcasting REMOVE_PROJECTILE" << endl;
[8dad966]491 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
492 {
[d05086b]493 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[8dad966]494 error("sendMessage");
495 }
496
[ff2133a]497 cout << "send a PLAYER message after dealing damage" << endl;
[8dad966]498 // send a PLAYER message after dealing damage
[8795a38]499 Player* target = &mapPlayers[itProj->second.target];
[8dad966]500
[c76134b]501 damagePlayer(target, itProj->second.damage);
[8dad966]502
[411c1ae]503 if (target->isDead) {
504 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
505 if (target->hasBlueFlag)
506 flagType = WorldMap::OBJECT_BLUE_FLAG;
507 else if (target->hasRedFlag)
508 flagType = WorldMap::OBJECT_RED_FLAG;
509
510 if (flagType != WorldMap::OBJECT_NONE) {
[d05086b]511 addObjectToMap(flagType, target->pos.x, target->pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
[411c1ae]512 }
513 }
514
[8dad966]515 serverMsg.type = MSG_TYPE_PLAYER;
516 target->serialize(serverMsg.buffer);
517
[ff2133a]518 cout << "Sending a PLAYER message" << endl;
[8dad966]519 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
520 {
[d05086b]521 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second.addr), &outputLog) < 0 )
[8dad966]522 error("sendMessage");
523 }
524 }
[c76134b]525 cout << "Projectile was not moved" << endl;
[d211210]526 }
527 }
528
[d05086b]529 n = msgProcessor.receiveMessage(&clientMsg, sock, &from, &outputLog);
[8e540f4]530
[371ce29]531 if (n >= 0) {
[d05086b]532 broadcastResponse = processMessage(clientMsg, from, msgProcessor, mapPlayers, gameMap, unusedPlayerId, serverMsg, sock, scoreBlue, scoreRed, outputLog);
[371ce29]533
[da692b9]534 if (broadcastResponse)
[3b1efcc]535 {
[da692b9]536 cout << "Should be broadcasting the message" << endl;
537
[01d0d00]538 map<unsigned int, Player>::iterator it;
539 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
[3b1efcc]540 {
[d211210]541 cout << "Sent message back to " << it->second.name << endl;
[d05086b]542 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second.addr), &outputLog) < 0 )
[3b1efcc]543 error("sendMessage");
544 }
545 }
546 else
547 {
[da692b9]548 cout << "Should be sending back the message" << endl;
549
[d05086b]550 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
[3b1efcc]551 error("sendMessage");
552 }
[7b43385]553 }
[8e540f4]554 }
[371ce29]555
[d05086b]556 outputLog << "Stopped server on " << getCurrentDateTimeString() << endl;
557 outputLog.close();
558
[8e540f4]559 return 0;
560}
561
[d05086b]562bool processMessage(const NETWORK_MSG &clientMsg, struct sockaddr_in &from, MessageProcessor &msgProcessor, map<unsigned int, Player>& mapPlayers, WorldMap* gameMap, unsigned int& unusedPlayerId, NETWORK_MSG &serverMsg, int sock, int &scoreBlue, int &scoreRed, ofstream& outputLog)
[8e540f4]563{
[41ad8ed]564 DataAccess da;
565
[9a4fa04]566 cout << "Inside processMessage" << endl;
567
[b8cb03f]568 cout << "Received message" << endl;
[8e540f4]569 cout << "MSG: type: " << clientMsg.type << endl;
570 cout << "MSG contents: " << clientMsg.buffer << endl;
571
[da692b9]572 // maybe we should make a message class and have this be a member
[3b1efcc]573 bool broadcastResponse = false;
574
[8e540f4]575 // Check that if an invalid message is sent, the client will correctly
576 // receive and display the response. Maybe make a special error msg type
577 switch(clientMsg.type)
578 {
579 case MSG_TYPE_REGISTER:
[d2b411a]580 {
[8e540f4]581 string username(clientMsg.buffer);
582 string password(strchr(clientMsg.buffer, '\0')+1);
[521c88b]583 Player::PlayerClass playerClass;
584
585 memcpy(&playerClass, clientMsg.buffer+username.length()+password.length()+2, 4);
[c4c2a3c]586 serverMsg.type = MSG_TYPE_REGISTER;
587
[d2b411a]588
[8e540f4]589 cout << "username: " << username << endl;
590 cout << "password: " << password << endl;
[d2b411a]591
[521c88b]592 if (playerClass == Player::CLASS_WARRIOR)
593 cout << "class: WARRIOR" << endl;
594 else if (playerClass == Player::CLASS_RANGER)
595 cout << "class: RANGER" << endl;
[c4c2a3c]596 else {
[521c88b]597 cout << "Unknown player class detected" << endl;
[c4c2a3c]598 strcpy(serverMsg.buffer, "You didn't select a class");
599 break;
600 }
[521c88b]601
602 int error = da.insertPlayer(username, password, playerClass);
[41ad8ed]603
[c4c2a3c]604 if (error)
[3b1efcc]605 strcpy(serverMsg.buffer, "Registration failed. Please try again.");
[c4c2a3c]606 else
607 strcpy(serverMsg.buffer, "Registration successful.");
[d2b411a]608
[8e540f4]609 break;
610 }
611 case MSG_TYPE_LOGIN:
612 {
[60017fc]613 cout << "Got login message" << endl;
614
[d211210]615 serverMsg.type = MSG_TYPE_LOGIN;
616
[8e540f4]617 string username(clientMsg.buffer);
[41ad8ed]618 string password(strchr(clientMsg.buffer, '\0')+1);
[8e540f4]619
[41ad8ed]620 Player* p = da.getPlayer(username);
[d2b411a]621
[b128109]622 if (p == NULL || !da.verifyPassword(password, p->password))
[41ad8ed]623 {
624 strcpy(serverMsg.buffer, "Incorrect username or password");
625 }
[01d0d00]626 else if(findPlayerByName(mapPlayers, username) != NULL)
[41ad8ed]627 {
628 strcpy(serverMsg.buffer, "Player has already logged in.");
629 }
630 else
[8e540f4]631 {
[d211210]632 serverMsg.type = MSG_TYPE_PLAYER;
633
[8dad966]634 updateUnusedPlayerId(unusedPlayerId, mapPlayers);
635 p->id = unusedPlayerId;
[d211210]636 cout << "new player id: " << p->id << endl;
[df79cfd]637 p->setAddr(from);
638
639 // choose a random team (either 0 or 1)
640 p->team = rand() % 2;
[d211210]641
642 // tell the new player about all the existing players
643 cout << "Sending other players to new player" << endl;
644
645 map<unsigned int, Player>::iterator it;
646 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
647 {
648 it->second.serialize(serverMsg.buffer);
649
650 cout << "sending info about " << it->second.name << endl;
[5f868c0]651 cout << "sending id " << it->second.id << endl;
[d05086b]652 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
[5f868c0]653 error("sendMessage");
654 }
655
656 // tell the new player about all map objects
657 // (currently just the flags)
658 serverMsg.type = MSG_TYPE_OBJECT;
[e487381]659 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
[5f868c0]660 vector<WorldMap::Object>::iterator itObjects;
661 cout << "sending items" << endl;
[e487381]662 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
[5f868c0]663 itObjects->serialize(serverMsg.buffer);
664 cout << "sending item id " << itObjects->id << endl;
[d05086b]665 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
[d211210]666 error("sendMessage");
667 }
[59061f6]668
[b8601ee]669 // send the current score
670 serverMsg.type = MSG_TYPE_SCORE;
671 memcpy(serverMsg.buffer, &scoreBlue, 4);
672 memcpy(serverMsg.buffer+4, &scoreRed, 4);
[d05086b]673 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
[b8601ee]674 error("sendMessage");
675
676 serverMsg.type = MSG_TYPE_PLAYER;
[594d2e9]677 p->serialize(serverMsg.buffer);
[d211210]678 cout << "Should be broadcasting the message" << endl;
679
680 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
681 {
682 cout << "Sent message back to " << it->second.name << endl;
[d05086b]683 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second.addr), &outputLog) < 0 )
[d211210]684 error("sendMessage");
685 }
686
687 serverMsg.type = MSG_TYPE_LOGIN;
[8dad966]688 mapPlayers[unusedPlayerId] = *p;
[07028b9]689 }
690
[41ad8ed]691 delete(p);
[07028b9]692
[8e540f4]693 break;
694 }
695 case MSG_TYPE_LOGOUT:
696 {
697 string name(clientMsg.buffer);
698 cout << "Player logging out: " << name << endl;
699
[01d0d00]700 Player *p = findPlayerByName(mapPlayers, name);
[633f42a]701
[8e540f4]702 if (p == NULL)
703 {
704 strcpy(serverMsg.buffer, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
[8a3ef42]705 cout << "Player not logged in" << endl;
[07028b9]706 }
[01d0d00]707 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
708 p->addr.sin_port != from.sin_port )
[07028b9]709 {
[8e540f4]710 strcpy(serverMsg.buffer, "That player is logged in using a differemt connection. This is either a bug, or you're trying to hack the server.");
[8a3ef42]711 cout << "Player logged in using a different connection" << endl;
[2488852]712 }
[8e540f4]713 else
[2488852]714 {
[411c1ae]715 if (!p->isDead) {
716 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
717 if (p->hasBlueFlag)
718 flagType = WorldMap::OBJECT_BLUE_FLAG;
719 else if (p->hasRedFlag)
720 flagType = WorldMap::OBJECT_RED_FLAG;
721
722 if (flagType != WorldMap::OBJECT_NONE) {
[d05086b]723 addObjectToMap(flagType, p->pos.x, p->pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
[411c1ae]724 }
725 }
726
[8dad966]727 if (p->id < unusedPlayerId)
728 unusedPlayerId = p->id;
[01d0d00]729 mapPlayers.erase(p->id);
[41ad8ed]730 strcpy(serverMsg.buffer, "You have successfully logged out.");
[8e540f4]731 }
[07028b9]732
[d211210]733 serverMsg.type = MSG_TYPE_LOGOUT;
[8a3ef42]734
[8e540f4]735 break;
736 }
737 case MSG_TYPE_CHAT:
738 {
[da692b9]739 cout << "Got a chat message" << endl;
740
[01d0d00]741 Player *p = findPlayerByAddr(mapPlayers, from);
[07028b9]742
[8e540f4]743 if (p == NULL)
744 {
745 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
[2488852]746 }
[8e540f4]747 else
748 {
[3b1efcc]749 broadcastResponse = true;
750
[b128109]751 ostringstream oss;
752 oss << p->name << ": " << clientMsg.buffer;
[3b1efcc]753
[b128109]754 strcpy(serverMsg.buffer, oss.str().c_str());
[8e540f4]755 }
756
757 serverMsg.type = MSG_TYPE_CHAT;
758
759 break;
[e084950]760 }
[b128109]761 case MSG_TYPE_PLAYER_MOVE:
762 {
763 cout << "PLAYER_MOVE" << endl;
764
765 int id, x, y;
766
767 memcpy(&id, clientMsg.buffer, 4);
768 memcpy(&x, clientMsg.buffer+4, 4);
769 memcpy(&y, clientMsg.buffer+8, 4);
[7b43385]770
[b128109]771 cout << "x: " << x << endl;
772 cout << "y: " << y << endl;
773 cout << "id: " << id << endl;
[7b43385]774
[b128109]775 if ( mapPlayers[id].addr.sin_addr.s_addr == from.sin_addr.s_addr &&
776 mapPlayers[id].addr.sin_port == from.sin_port )
777 {
[60017fc]778 // we need to make sure the player can move here
[694c3d2]779 if (0 <= x && x < gameMap->width*25 && 0 <= y && y < gameMap->height*25 &&
[60017fc]780 gameMap->getElement(x/25, y/25) == WorldMap::TERRAIN_GRASS)
781 {
[7b43385]782 cout << "valid terrain" << endl;
783
[60017fc]784 mapPlayers[id].target.x = x;
785 mapPlayers[id].target.y = y;
786
[5b1e31e]787 mapPlayers[id].isChasing = false;
788 mapPlayers[id].isAttacking = false;
789
[60017fc]790 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
791
792 memcpy(serverMsg.buffer, &id, 4);
[d211210]793 memcpy(serverMsg.buffer+4, &mapPlayers[id].target.x, 4);
794 memcpy(serverMsg.buffer+8, &mapPlayers[id].target.y, 4);
[60017fc]795
796 broadcastResponse = true;
797 }
798 else
799 cout << "Bad terrain detected" << endl;
[b128109]800 }
801 else // nned to send back a message indicating failure
802 cout << "Player id (" << id << ") doesn't match sender" << endl;
803
804 break;
805 }
[5299436]806 case MSG_TYPE_PICKUP_FLAG:
807 {
808 // may want to check the id matches the sender, just like for PLAYER_NOVE
809 cout << "PICKUP_FLAG" << endl;
810
811 int id;
812
813 memcpy(&id, clientMsg.buffer, 4);
814 cout << "id: " << id << endl;
815
[5c84d54]816 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
817 vector<WorldMap::Object>::iterator itObjects;
818
819 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end();) {
820 POSITION pos = itObjects->pos;
821 bool gotFlag = false;
822
823 if (posDistance(mapPlayers[id].pos, pos.toFloat()) < 10) {
824 switch (itObjects->type) {
825 case WorldMap::OBJECT_BLUE_FLAG:
826 if (mapPlayers[id].team == 1) {
827 gotFlag = true;
828 mapPlayers[id].hasBlueFlag = true;
829 broadcastResponse = true;
830 }
831 break;
832 case WorldMap::OBJECT_RED_FLAG:
833 if (mapPlayers[id].team == 0) {
834 gotFlag = true;
835 mapPlayers[id].hasRedFlag = true;
836 broadcastResponse = true;
837 }
838 break;
839 }
840
841 if (gotFlag) {
842 serverMsg.type = MSG_TYPE_REMOVE_OBJECT;
843 memcpy(serverMsg.buffer, &itObjects->id, 4);
844
845 map<unsigned int, Player>::iterator it;
846 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
847 {
[d05086b]848 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second.addr), &outputLog) < 0 )
[5c84d54]849 error("sendMessage");
850 }
851
852 // remove the object from the server-side map
853 cout << "size before: " << gameMap->getObjects()->size() << endl;
854 itObjects = vctObjects->erase(itObjects);
855 cout << "size after: " << gameMap->getObjects()->size() << endl;
856 }
857 }
858
859 if (!gotFlag)
860 itObjects++;
861 }
862
863 serverMsg.type = MSG_TYPE_PLAYER;
864 mapPlayers[id].serialize(serverMsg.buffer);
865
[5299436]866 break;
867 }
[e487381]868 case MSG_TYPE_DROP_FLAG:
869 {
870 // may want to check the id matches the sender, just like for PLAYER_NOVE
871 cout << "DROP_FLAG" << endl;
872
873 int id;
874
875 memcpy(&id, clientMsg.buffer, 4);
876 cout << "id: " << id << endl;
877
878 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
879 if (mapPlayers[id].hasBlueFlag)
880 flagType = WorldMap::OBJECT_BLUE_FLAG;
881 else if (mapPlayers[id].hasRedFlag)
882 flagType = WorldMap::OBJECT_RED_FLAG;
883
[d05086b]884 addObjectToMap(flagType, mapPlayers[id].pos.x, mapPlayers[id].pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
[e487381]885
886 mapPlayers[id].hasBlueFlag = false;
887 mapPlayers[id].hasRedFlag = false;
888
889 serverMsg.type = MSG_TYPE_PLAYER;
890 mapPlayers[id].serialize(serverMsg.buffer);
891
892 broadcastResponse = true;
893
894 break;
895 }
[4b4b153]896 case MSG_TYPE_START_ATTACK:
897 {
898 cout << "Received a START_ATTACK message" << endl;
899
[8a4ed74]900 int id, targetId;
901
902 memcpy(&id, clientMsg.buffer, 4);
903 memcpy(&targetId, clientMsg.buffer+4, 4);
904
[8dad966]905 Player* source = &mapPlayers[id];
906 source->targetPlayer = targetId;
[11d21ee]907 source->isChasing = true;
[8dad966]908
[11d21ee]909 // this is irrelevant since the client doesn't even listen for START_ATTACK messages
910 // actually, the client should not ignore this and should instead perform the same movement
911 // algorithm on its end (following the target player until in range) that the server does.
912 // Once the attacker is in range, the client should stop movement and wait for messages
913 // from the server
[4b4b153]914 serverMsg.type = MSG_TYPE_START_ATTACK;
[8dad966]915 memcpy(serverMsg.buffer, &id, 4);
916 memcpy(serverMsg.buffer+4, &targetId, 4);
[4b4b153]917 broadcastResponse = true;
[8a4ed74]918
919 break;
[4b4b153]920 }
921 case MSG_TYPE_ATTACK:
922 {
923 cout << "Received am ATTACK message" << endl;
[8dad966]924 cout << "ERROR: Clients should not send ATTACK messages" << endl;
[8a4ed74]925
926 break;
[4b4b153]927 }
[8e540f4]928 default:
929 {
930 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
[e084950]931
[8e540f4]932 serverMsg.type = MSG_TYPE_CHAT;
[e084950]933
[8e540f4]934 break;
935 }
[e3535b3]936 }
[da692b9]937
938 return broadcastResponse;
[e3535b3]939}
[da692b9]940
[8dad966]941void updateUnusedPlayerId(unsigned int& id, map<unsigned int, Player>& mapPlayers)
[01d0d00]942{
[1106210]943 while (mapPlayers.find(id) != mapPlayers.end())
944 id++;
[01d0d00]945}
[8dad966]946
947void updateUnusedProjectileId(unsigned int& id, map<unsigned int, Projectile>& mapProjectiles)
948{
949 while (mapProjectiles.find(id) != mapProjectiles.end())
950 id++;
951}
[c76134b]952
953void damagePlayer(Player *p, int damage) {
954 p->health -= damage;
955 if (p->health < 0)
956 p->health = 0;
957 if (p->health == 0) {
[66c4ec4]958 cout << "Player died" << endl;
[c76134b]959 p->isDead = true;
960 p->timeDied = getCurrentMillis();
961 }
962}
[411c1ae]963
[d05086b]964void addObjectToMap(WorldMap::ObjectType objectType, int x, int y, WorldMap* gameMap, map<unsigned int, Player>& mapPlayers, MessageProcessor &msgProcessor, int sock, ofstream& outputLog) {
[411c1ae]965 NETWORK_MSG serverMsg;
966
967 gameMap->addObject(objectType, x, y);
968
969 // need to send the OBJECT message too
970 serverMsg.type = MSG_TYPE_OBJECT;
971 gameMap->getObjects()->back().serialize(serverMsg.buffer);
972
973 map<unsigned int, Player>::iterator it;
974 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
975 {
[d05086b]976 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second.addr), &outputLog) < 0 )
[411c1ae]977 error("sendMessage");
978 }
979}
Note: See TracBrowser for help on using the repository browser.