source: network-game/server/server.cpp@ 426fb84

Last change on this file since 426fb84 was 426fb84, checked in by Dmitry Portnoy <dmp1488@…>, 10 years ago

Save the actual time a game ends to the databse and send it to the client as part of a player's game history

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