source: network-game/server/server.cpp@ 6054f1e

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

Moved damagePlayer to the Player class

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