source: network-game/server/server.cpp@ b73bc28

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

Turning in the opposing team's flag now works in individual games and returning your own should as well, but hasn't been tested

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