source: network-game/server/server.cpp@ 99afbb8

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

The server keeps track of games and adds players to them

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