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

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

When the server receives a logout message, it broadcasts it now instead of just responding to the sender

  • Property mode set to 100644
File size: 43.0 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
141 usleep(5000);
142
143 clock_gettime(CLOCK_REALTIME, &ts);
144 // make the number smaller so millis can fit in an int
145 ts.tv_sec -= 1368000000;
146 curTime = ts.tv_sec*1000 + ts.tv_nsec/1000000;
147
148 if (timeLastUpdated == 0 || (curTime-timeLastUpdated) >= 50)
149 {
150 timeLastUpdated = curTime;
151
152 msgProcessor.cleanAckedMessages(&outputLog);
153 msgProcessor.resendUnackedMessages(sock, &outputLog);
154
155 map<unsigned int, Player*>::iterator it;
156
157 // set targets for all chasing players (or make them attack if they're close enough)
158 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
159 {
160 // check if it's time to revive dead players
161 if (it->second->isDead)
162 {
163 if (getCurrentMillis() - it->second->timeDied >= 10000)
164 {
165 it->second->isDead = false;
166
167 POSITION spawnPos;
168
169 switch (it->second->team)
170 {
171 case 0:// blue team
172 spawnPos = gameMap->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
173 break;
174 case 1:// red team
175 spawnPos = gameMap->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
176 break;
177 default:
178 // should never go here
179 cout << "Error: Invalid team" << endl;
180 break;
181 }
182
183 // spawn the player to the right of their flag location
184 spawnPos.x = (spawnPos.x+1) * 25 + 12;
185 spawnPos.y = spawnPos.y * 25 + 12;
186
187 it->second->pos = spawnPos.toFloat();
188 it->second->target = spawnPos;
189 it->second->health = it->second->maxHealth;
190
191 serverMsg.type = MSG_TYPE_PLAYER;
192 it->second->serialize(serverMsg.buffer);
193
194 map<unsigned int, Player*>::iterator it2;
195 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
196 {
197 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
198 error("sendMessage");
199 }
200 }
201
202 continue;
203 }
204
205 if (it->second->updateTarget(mapPlayers))
206 {
207 serverMsg.type = MSG_TYPE_PLAYER;
208 it->second->serialize(serverMsg.buffer);
209
210 map<unsigned int, Player*>::iterator it2;
211 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
212 {
213 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
214 error("sendMessage");
215 }
216 }
217 }
218
219 // move all players
220 // maybe put this in a separate method
221 FLOAT_POSITION oldPos;
222 bool broadcastMove = false;
223 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
224 {
225 oldPos = it->second->pos;
226 if (it->second->move(gameMap)) {
227
228 // check if the move needs to be canceled
229 switch(gameMap->getElement(it->second->pos.x/25, it->second->pos.y/25))
230 {
231 case WorldMap::TERRAIN_NONE:
232 case WorldMap::TERRAIN_OCEAN:
233 case WorldMap::TERRAIN_ROCK:
234 {
235 it->second->pos = oldPos;
236 it->second->target.x = it->second->pos.x;
237 it->second->target.y = it->second->pos.y;
238 it->second->isChasing = false;
239 broadcastMove = true;
240 break;
241 }
242 default:
243 // if there are no obstacles, do nothing
244 break;
245 }
246
247 WorldMap::ObjectType flagType;
248 POSITION pos;
249 bool flagTurnedIn = false;
250 bool flagReturned = false;
251 bool ownFlagAtBase = false;
252
253 switch(gameMap->getStructure(it->second->pos.x/25, it->second->pos.y/25))
254 {
255 case WorldMap::STRUCTURE_BLUE_FLAG:
256 {
257 if (it->second->team == 0 && it->second->hasRedFlag)
258 {
259 // check that your flag is at your base
260 pos = gameMap->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
261
262 vector<WorldMap::Object>* vctObjects = gameMap->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 it->second->hasRedFlag = false;
280 flagType = WorldMap::OBJECT_RED_FLAG;
281 pos = gameMap->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 (it->second->team == 1 && it->second->hasBlueFlag)
292 {
293 // check that your flag is at your base
294 pos = gameMap->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
295
296 vector<WorldMap::Object>* vctObjects = gameMap->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 it->second->hasBlueFlag = false;
314 flagType = WorldMap::OBJECT_BLUE_FLAG;
315 pos = gameMap->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 gameMap->addObject(flagType, pos.x, pos.y);
331
332 serverMsg.type = MSG_TYPE_OBJECT;
333 gameMap->getObjects()->back().serialize(serverMsg.buffer);
334
335 map<unsigned int, Player*>::iterator it2;
336 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
337 {
338 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
339 error("sendMessage");
340 }
341
342 serverMsg.type = MSG_TYPE_SCORE;
343 memcpy(serverMsg.buffer, &scoreBlue, 4);
344 memcpy(serverMsg.buffer+4, &scoreRed, 4);
345
346 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
347 {
348 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
349 error("sendMessage");
350 }
351
352 // this means a PLAYER message will be sent
353 broadcastMove = true;
354 }
355
356 // go through all objects and check if the player is close to one and if its their flag
357 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
358 vector<WorldMap::Object>::iterator itObjects;
359 POSITION structPos;
360
361 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++)
362 {
363 POSITION pos = itObjects->pos;
364
365 if (posDistance(it->second->pos, pos.toFloat()) < 10)
366 {
367 if (it->second->team == 0 &&
368 itObjects->type == WorldMap::OBJECT_BLUE_FLAG)
369 {
370 structPos = gameMap->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
371 flagReturned = true;
372 break;
373 }
374 else if (it->second->team == 1 &&
375 itObjects->type == WorldMap::OBJECT_RED_FLAG)
376 {
377 structPos = gameMap->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
378 flagReturned = true;
379 break;
380 }
381 }
382 }
383
384 if (flagReturned)
385 {
386 itObjects->pos.x = structPos.x*25+12;
387 itObjects->pos.y = structPos.y*25+12;
388
389 serverMsg.type = MSG_TYPE_OBJECT;
390 itObjects->serialize(serverMsg.buffer);
391
392 map<unsigned int, Player*>::iterator it2;
393 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
394 {
395 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
396 error("sendMessage");
397 }
398 }
399
400 if (broadcastMove)
401 {
402 serverMsg.type = MSG_TYPE_PLAYER;
403 it->second->serialize(serverMsg.buffer);
404
405 cout << "about to broadcast move" << endl;
406 map<unsigned int, Player*>::iterator it2;
407 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
408 {
409 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
410 error("sendMessage");
411 }
412 }
413 }
414
415 // check if the player's attack animation is complete
416 if (it->second->isAttacking && it->second->timeAttackStarted+it->second->attackCooldown <= getCurrentMillis())
417 {
418 it->second->isAttacking = false;
419 cout << "Attack animation is complete" << endl;
420
421 //send everyone an ATTACK message
422 cout << "about to broadcast attack" << endl;
423
424 serverMsg.type = MSG_TYPE_ATTACK;
425 memcpy(serverMsg.buffer, &it->second->id, 4);
426 memcpy(serverMsg.buffer+4, &it->second->targetPlayer, 4);
427
428 map<unsigned int, Player*>::iterator it2;
429 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
430 {
431 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
432 error("sendMessage");
433 }
434
435 if (it->second->attackType == Player::ATTACK_MELEE)
436 {
437 cout << "Melee attack" << endl;
438
439 Player* target = mapPlayers[it->second->targetPlayer];
440 damagePlayer(target, it->second->damage);
441
442 if (target->isDead)
443 {
444 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
445 if (target->hasBlueFlag)
446 flagType = WorldMap::OBJECT_BLUE_FLAG;
447 else if (target->hasRedFlag)
448 flagType = WorldMap::OBJECT_RED_FLAG;
449
450 if (flagType != WorldMap::OBJECT_NONE) {
451 addObjectToMap(flagType, target->pos.x, target->pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
452 }
453 }
454
455 serverMsg.type = MSG_TYPE_PLAYER;
456 target->serialize(serverMsg.buffer);
457 }
458 else if (it->second->attackType == Player::ATTACK_RANGED)
459 {
460 cout << "Ranged attack" << endl;
461
462 Projectile proj(it->second->pos.x, it->second->pos.y, it->second->targetPlayer, it->second->damage);
463 proj.id = unusedProjectileId;
464 updateUnusedProjectileId(unusedProjectileId, mapProjectiles);
465 mapProjectiles[proj.id] = proj;
466
467 int x = it->second->pos.x;
468 int y = it->second->pos.y;
469
470 serverMsg.type = MSG_TYPE_PROJECTILE;
471 memcpy(serverMsg.buffer, &proj.id, 4);
472 memcpy(serverMsg.buffer+4, &x, 4);
473 memcpy(serverMsg.buffer+8, &y, 4);
474 memcpy(serverMsg.buffer+12, &it->second->targetPlayer, 4);
475 }
476 else
477 cout << "Invalid attack type: " << it->second->attackType << endl;
478
479 // broadcast either a PLAYER or PROJECTILE message
480 cout << "Broadcasting player or projectile message" << endl;
481 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
482 {
483 if (msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
484 error("sendMessage");
485 }
486 cout << "Done broadcasting" << endl;
487 }
488 }
489
490 // move all projectiles
491 map<unsigned int, Projectile>::iterator itProj;
492 for (itProj = mapProjectiles.begin(); itProj != mapProjectiles.end(); itProj++)
493 {
494 cout << "About to call projectile move" << endl;
495 if (itProj->second.move(mapPlayers))
496 {
497 // send a REMOVE_PROJECTILE message
498 cout << "send a REMOVE_PROJECTILE message" << endl;
499 serverMsg.type = MSG_TYPE_REMOVE_PROJECTILE;
500 memcpy(serverMsg.buffer, &itProj->second.id, 4);
501 mapProjectiles.erase(itProj->second.id);
502
503 map<unsigned int, Player*>::iterator it2;
504 cout << "Broadcasting REMOVE_PROJECTILE" << endl;
505 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
506 {
507 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
508 error("sendMessage");
509 }
510
511 cout << "send a PLAYER message after dealing damage" << endl;
512 // send a PLAYER message after dealing damage
513 Player* target = mapPlayers[itProj->second.target];
514
515 damagePlayer(target, itProj->second.damage);
516
517 if (target->isDead)
518 {
519 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
520 if (target->hasBlueFlag)
521 flagType = WorldMap::OBJECT_BLUE_FLAG;
522 else if (target->hasRedFlag)
523 flagType = WorldMap::OBJECT_RED_FLAG;
524
525 if (flagType != WorldMap::OBJECT_NONE)
526 addObjectToMap(flagType, target->pos.x, target->pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
527 }
528
529 serverMsg.type = MSG_TYPE_PLAYER;
530 target->serialize(serverMsg.buffer);
531
532 cout << "Sending a PLAYER message" << endl;
533 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
534 {
535 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it2->second->addr), &outputLog) < 0 )
536 error("sendMessage");
537 }
538 }
539 cout << "Projectile was not moved" << endl;
540 }
541 }
542
543 n = msgProcessor.receiveMessage(&clientMsg, sock, &from, &outputLog);
544
545 if (n >= 0)
546 {
547 broadcastResponse = processMessage(clientMsg, from, msgProcessor, mapPlayers, mapGames, gameMap, unusedPlayerId, serverMsg, sock, scoreBlue, scoreRed, outputLog);
548
549 if (broadcastResponse)
550 {
551 cout << "Should be broadcasting the message" << endl;
552
553 map<unsigned int, Player*>::iterator it;
554 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
555 {
556 cout << "Sent message back to " << it->second->name << endl;
557 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
558 error("sendMessage");
559 }
560 }
561 else
562 {
563 cout << "Should be sending back the message" << endl;
564
565 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
566 error("sendMessage");
567 }
568 }
569 }
570
571 outputLog << "Stopped server on " << getCurrentDateTimeString() << endl;
572 outputLog.close();
573
574 // delete all games
575 map<string, Game*>::iterator itGames;
576 for (itGames = mapGames.begin(); itGames != mapGames.end(); itGames++)
577 {
578 delete itGames->second;
579 }
580
581 map<unsigned int, Player*>::iterator itPlayers;
582 for (itPlayers = mapPlayers.begin(); itPlayers != mapPlayers.end(); itPlayers++)
583 {
584 delete itPlayers->second;
585 }
586
587 return 0;
588}
589
590bool 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)
591{
592 DataAccess da;
593
594 cout << "Inside processMessage" << endl;
595
596 cout << "Received message" << endl;
597 cout << "MSG: type: " << clientMsg.type << endl;
598 cout << "MSG contents: " << clientMsg.buffer << endl;
599
600 // maybe we should make a message class and have this be a member
601 bool broadcastResponse = false;
602
603 // Check that if an invalid message is sent, the client will correctly
604 // receive and display the response. Maybe make a special error msg type
605 switch(clientMsg.type)
606 {
607 case MSG_TYPE_REGISTER:
608 {
609 string username(clientMsg.buffer);
610 string password(strchr(clientMsg.buffer, '\0')+1);
611 Player::PlayerClass playerClass;
612
613 memcpy(&playerClass, clientMsg.buffer+username.length()+password.length()+2, 4);
614 serverMsg.type = MSG_TYPE_REGISTER;
615
616 cout << "username: " << username << endl;
617 cout << "password: " << password << endl;
618
619 if (playerClass == Player::CLASS_WARRIOR)
620 cout << "class: WARRIOR" << endl;
621 else if (playerClass == Player::CLASS_RANGER)
622 cout << "class: RANGER" << endl;
623 else {
624 cout << "Unknown player class detected" << endl;
625 strcpy(serverMsg.buffer, "You didn't select a class");
626 break;
627 }
628
629 int error = da.insertPlayer(username, password, playerClass);
630
631 if (error)
632 strcpy(serverMsg.buffer, "Registration failed. Please try again.");
633 else
634 strcpy(serverMsg.buffer, "Registration successful.");
635
636 break;
637 }
638 case MSG_TYPE_LOGIN:
639 {
640 cout << "Got login message" << endl;
641
642 string username(clientMsg.buffer);
643 string password(strchr(clientMsg.buffer, '\0')+1);
644
645 Player* p = da.getPlayer(username);
646
647 if (p == NULL || !da.verifyPassword(password, p->password))
648 {
649 strcpy(serverMsg.buffer, "Incorrect username or password");
650 if (p != NULL)
651 delete(p);
652 }
653 else if(findPlayerByName(mapPlayers, username) != NULL)
654 {
655 strcpy(serverMsg.buffer, "Player has already logged in.");
656 delete(p);
657 }
658 else
659 {
660 updateUnusedPlayerId(unusedPlayerId, mapPlayers);
661 p->id = unusedPlayerId;
662 cout << "new player id: " << p->id << endl;
663 p->setAddr(from);
664
665 // choose a random team (either 0 or 1)
666 p->team = rand() % 2;
667
668 serverMsg.type = MSG_TYPE_PLAYER;
669
670 // tell the new player about all the existing players
671 cout << "Sending other players to new player" << endl;
672
673 map<unsigned int, Player*>::iterator it;
674 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
675 {
676 it->second->serialize(serverMsg.buffer);
677
678 cout << "sending info about " << it->second->name << endl;
679 cout << "sending id " << it->second->id << endl;
680 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
681 error("sendMessage");
682 }
683
684 // tell the new player about all map objects
685 // (currently just the flags)
686 serverMsg.type = MSG_TYPE_OBJECT;
687 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
688 vector<WorldMap::Object>::iterator itObjects;
689 cout << "sending items" << endl;
690 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
691 itObjects->serialize(serverMsg.buffer);
692 cout << "sending item id " << itObjects->id << endl;
693 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
694 error("sendMessage");
695 }
696
697 // send the current score
698 serverMsg.type = MSG_TYPE_SCORE;
699 memcpy(serverMsg.buffer, &scoreBlue, 4);
700 memcpy(serverMsg.buffer+4, &scoreRed, 4);
701 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
702 error("sendMessage");
703
704 serverMsg.type = MSG_TYPE_PLAYER;
705 p->serialize(serverMsg.buffer);
706 cout << "Should be broadcasting the message" << endl;
707
708 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
709 {
710 cout << "Sent message back to " << it->second->name << endl;
711 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
712 error("sendMessage");
713 }
714
715 mapPlayers[unusedPlayerId] = p;
716 }
717
718 serverMsg.type = MSG_TYPE_LOGIN;
719
720 break;
721 }
722 case MSG_TYPE_LOGOUT:
723 {
724 string name(clientMsg.buffer);
725 cout << "Player logging out: " << name << endl;
726
727 Player *p = findPlayerByName(mapPlayers, name);
728
729 memcpy(serverMsg.buffer, &p->id, 4);
730
731 if (p == NULL)
732 {
733 strcpy(serverMsg.buffer+4, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
734 cout << "Player not logged in" << endl;
735 }
736 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
737 p->addr.sin_port != from.sin_port )
738 {
739 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.");
740 cout << "Player logged in using a different connection" << endl;
741 }
742 else
743 {
744 if (!p->isDead) {
745 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
746 if (p->hasBlueFlag)
747 flagType = WorldMap::OBJECT_BLUE_FLAG;
748 else if (p->hasRedFlag)
749 flagType = WorldMap::OBJECT_RED_FLAG;
750
751 if (flagType != WorldMap::OBJECT_NONE) {
752 addObjectToMap(flagType, p->pos.x, p->pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
753 }
754 }
755
756 if (p->id < unusedPlayerId)
757 unusedPlayerId = p->id;
758 mapPlayers.erase(p->id);
759 delete p;
760 strcpy(serverMsg.buffer+4, "You have successfully logged out.");
761 broadcastResponse = true;
762 }
763
764 serverMsg.type = MSG_TYPE_LOGOUT;
765
766 break;
767 }
768 case MSG_TYPE_CHAT:
769 {
770 cout << "Got a chat message" << endl;
771
772 Player *p = findPlayerByAddr(mapPlayers, from);
773
774 if (p == NULL)
775 {
776 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
777 }
778 else
779 {
780 broadcastResponse = true;
781
782 ostringstream oss;
783 oss << p->name << ": " << clientMsg.buffer;
784
785 strcpy(serverMsg.buffer, oss.str().c_str());
786 }
787
788 serverMsg.type = MSG_TYPE_CHAT;
789
790 break;
791 }
792 case MSG_TYPE_PLAYER_MOVE:
793 {
794 cout << "PLAYER_MOVE" << endl;
795
796 int id, x, y;
797
798 memcpy(&id, clientMsg.buffer, 4);
799 memcpy(&x, clientMsg.buffer+4, 4);
800 memcpy(&y, clientMsg.buffer+8, 4);
801
802 cout << "x: " << x << endl;
803 cout << "y: " << y << endl;
804 cout << "id: " << id << endl;
805
806 Player* p = mapPlayers[id];
807
808 if ( p->addr.sin_addr.s_addr == from.sin_addr.s_addr &&
809 p->addr.sin_port == from.sin_port )
810 {
811 // we need to make sure the player can move here
812 if (0 <= x && x < gameMap->width*25 && 0 <= y && y < gameMap->height*25 &&
813 gameMap->getElement(x/25, y/25) == WorldMap::TERRAIN_GRASS)
814 {
815 cout << "valid terrain" << endl;
816
817 p->target.x = x;
818 p->target.y = y;
819
820 p->isChasing = false;
821 p->isAttacking = false;
822
823 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
824
825 memcpy(serverMsg.buffer, &id, 4);
826 memcpy(serverMsg.buffer+4, &p->target.x, 4);
827 memcpy(serverMsg.buffer+8, &p->target.y, 4);
828
829 broadcastResponse = true;
830 }
831 else
832 cout << "Bad terrain detected" << endl;
833 }
834 else // nned to send back a message indicating failure
835 cout << "Player id (" << id << ") doesn't match sender" << endl;
836
837 break;
838 }
839 case MSG_TYPE_PICKUP_FLAG:
840 {
841 // may want to check the id matches the sender, just like for PLAYER_NOVE
842 cout << "PICKUP_FLAG" << endl;
843
844 int id;
845
846 memcpy(&id, clientMsg.buffer, 4);
847 cout << "id: " << id << endl;
848
849 Player* p = mapPlayers[id];
850
851 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
852 vector<WorldMap::Object>::iterator itObjects;
853
854 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end();) {
855 POSITION pos = itObjects->pos;
856 bool gotFlag = false;
857
858 if (posDistance(p->pos, pos.toFloat()) < 10) {
859 switch (itObjects->type) {
860 case WorldMap::OBJECT_BLUE_FLAG:
861 if (p->team == 1) {
862 gotFlag = true;
863 p->hasBlueFlag = true;
864 broadcastResponse = true;
865 }
866 break;
867 case WorldMap::OBJECT_RED_FLAG:
868 if (p->team == 0) {
869 gotFlag = true;
870 p->hasRedFlag = true;
871 broadcastResponse = true;
872 }
873 break;
874 }
875
876 if (gotFlag) {
877 serverMsg.type = MSG_TYPE_REMOVE_OBJECT;
878 memcpy(serverMsg.buffer, &itObjects->id, 4);
879
880 map<unsigned int, Player*>::iterator it;
881 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
882 {
883 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
884 error("sendMessage");
885 }
886
887 // remove the object from the server-side map
888 cout << "size before: " << gameMap->getObjects()->size() << endl;
889 itObjects = vctObjects->erase(itObjects);
890 cout << "size after: " << gameMap->getObjects()->size() << endl;
891 }
892 }
893
894 if (!gotFlag)
895 itObjects++;
896 }
897
898 serverMsg.type = MSG_TYPE_PLAYER;
899 p->serialize(serverMsg.buffer);
900
901 break;
902 }
903 case MSG_TYPE_DROP_FLAG:
904 {
905 // may want to check the id matches the sender, just like for PLAYER_NOVE
906 cout << "DROP_FLAG" << endl;
907
908 int id;
909
910 memcpy(&id, clientMsg.buffer, 4);
911 cout << "id: " << id << endl;
912
913 Player* p = mapPlayers[id];
914
915 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
916 if (p->hasBlueFlag)
917 flagType = WorldMap::OBJECT_BLUE_FLAG;
918 else if (p->hasRedFlag)
919 flagType = WorldMap::OBJECT_RED_FLAG;
920
921 addObjectToMap(flagType, p->pos.x, p->pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
922
923 p->hasBlueFlag = false;
924 p->hasRedFlag = false;
925
926 serverMsg.type = MSG_TYPE_PLAYER;
927 p->serialize(serverMsg.buffer);
928
929 broadcastResponse = true;
930
931 break;
932 }
933 case MSG_TYPE_START_ATTACK:
934 {
935 cout << "Received a START_ATTACK message" << endl;
936
937 int id, targetId;
938
939 memcpy(&id, clientMsg.buffer, 4);
940 memcpy(&targetId, clientMsg.buffer+4, 4);
941
942 Player* source = mapPlayers[id];
943 source->targetPlayer = targetId;
944 source->isChasing = true;
945
946 // this is irrelevant since the client doesn't even listen for START_ATTACK messages
947 // actually, the client should not ignore this and should instead perform the same movement
948 // algorithm on its end (following the target player until in range) that the server does.
949 // Once the attacker is in range, the client should stop movement and wait for messages
950 // from the server
951 serverMsg.type = MSG_TYPE_START_ATTACK;
952 memcpy(serverMsg.buffer, &id, 4);
953 memcpy(serverMsg.buffer+4, &targetId, 4);
954 broadcastResponse = true;
955
956 break;
957 }
958 case MSG_TYPE_ATTACK:
959 {
960 cout << "Received am ATTACK message" << endl;
961 cout << "ERROR: Clients should not send ATTACK messages" << endl;
962
963 break;
964 }
965 case MSG_TYPE_CREATE_GAME:
966 {
967 cout << "Received a CREATE_GAME message" << endl;
968
969 string gameName(clientMsg.buffer);
970 cout << "Game name: " << gameName << endl;
971
972 // check if this game already exists
973 if (mapGames.find(gameName) != mapGames.end()) {
974 cout << "Error: Game already exists" << endl;
975 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
976 broadcastResponse = false;
977 return broadcastResponse;
978 }
979
980 Game* g = new Game(gameName, "../data/map.txt");
981 mapGames[gameName] = g;
982
983 Player* p = findPlayerByAddr(mapPlayers, from);
984 p->currentGame = g;
985
986 serverMsg.type = MSG_TYPE_JOIN_GAME_SUCCESS;
987 strcpy(serverMsg.buffer, gameName.c_str());
988 broadcastResponse = false;
989
990 break;
991 }
992 case MSG_TYPE_JOIN_GAME:
993 {
994 cout << "Received a JOIN_GAME message" << endl;
995
996 string gameName(clientMsg.buffer);
997 cout << "Game name: " << gameName << endl;
998
999 // check if this game already exists
1000 if (mapGames.find(gameName) == mapGames.end()) {
1001 cout << "Error: Game does not exist" << endl;
1002 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1003 broadcastResponse = false;
1004 return broadcastResponse;
1005 }
1006
1007 Game* g = mapGames[gameName];
1008 map<unsigned int, Player*>& players = g->getPlayers();
1009 Player* p = findPlayerByAddr(mapPlayers, from);
1010
1011 if (players.find(p->id) != players.end()) {
1012 cout << "Player " << p->name << " trying to join a game he's already in" << endl;
1013 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1014 broadcastResponse = false;
1015 return broadcastResponse;
1016 }
1017
1018 p->currentGame = g;
1019
1020 serverMsg.type = MSG_TYPE_JOIN_GAME_SUCCESS;
1021 strcpy(serverMsg.buffer, gameName.c_str());
1022 broadcastResponse = false;
1023
1024 break;
1025 }
1026 case MSG_TYPE_LEAVE_GAME:
1027 {
1028 cout << "Received a LEAVE_GAME message" << endl;
1029
1030 Player* p = findPlayerByAddr(mapPlayers, from);
1031 Game* g = p->currentGame;
1032
1033 if (g == NULL) {
1034 cout << "Player " << p->name << " is trying to leave a game, but is not currently in a game." << endl;
1035
1036 /// should send a response back, maybe a new message type is needed
1037
1038 break;
1039 }
1040
1041 cout << "Game name: " << g->getName() << endl;
1042 p->currentGame = NULL;
1043
1044 serverMsg.type = MSG_TYPE_LEAVE_GAME;
1045 memcpy(serverMsg.buffer, &p->id, 4);
1046 strcpy(serverMsg.buffer+4, g->getName().c_str());
1047
1048 map<unsigned int, Player*>& players = g->getPlayers();
1049
1050 map<unsigned int, Player*>::iterator it;
1051 for (it = players.begin(); it != players.end(); it++)
1052 {
1053 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
1054 error("sendMessage");
1055 }
1056
1057 g->removePlayer(p->id);
1058
1059 // broadcast a messsage to other players so they know someone left the game
1060 // also, check if the game has any players left. If not, remove it and send everyone a message so the game is gone from their lobby list
1061
1062 int numPlayers = g->getNumPlayers();
1063
1064 serverMsg.type = MSG_TYPE_GAME_INFO;
1065 memcpy(serverMsg.buffer, &numPlayers, 4);
1066 strcpy(serverMsg.buffer+4, g->getName().c_str());
1067 broadcastResponse = true;
1068
1069 break;
1070 }
1071 case MSG_TYPE_JOIN_GAME_ACK:
1072 {
1073 cout << "Received a JOIN_GAME_ACK message" << endl;
1074
1075 string gameName(clientMsg.buffer);
1076 cout << "Game name: " << gameName << endl;
1077
1078 // check if this game already exists
1079 if (mapGames.find(gameName) == mapGames.end()) {
1080 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1081 broadcastResponse = false;
1082 return broadcastResponse;
1083 }
1084
1085 Game* g = mapGames[gameName];
1086
1087 Player* p = findPlayerByAddr(mapPlayers, from);
1088 p->team = rand() % 2; // choose a random team (either 0 or 1)
1089 p->currentGame = g;
1090
1091 map<unsigned int, Player*>& otherPlayers = g->getPlayers();
1092
1093 // tell the new player about all the existing players
1094 cout << "Sending other players to new player" << endl;
1095 serverMsg.type = MSG_TYPE_PLAYER;
1096
1097 map<unsigned int, Player*>::iterator it;
1098 for (it = otherPlayers.begin(); it != otherPlayers.end(); it++)
1099 {
1100 it->second->serialize(serverMsg.buffer);
1101
1102 cout << "sending info about " << it->second->name << endl;
1103 cout << "sending id " << it->second->id << endl;
1104 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1105 error("sendMessage");
1106 }
1107
1108 // tell the new player about all map objects
1109 // (currently just the flags)
1110
1111 serverMsg.type = MSG_TYPE_OBJECT;
1112 vector<WorldMap::Object>* vctObjects = g->getMap()->getObjects();
1113 vector<WorldMap::Object>::iterator itObjects;
1114 cout << "sending items" << endl;
1115 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
1116 itObjects->serialize(serverMsg.buffer);
1117 cout << "sending item id " << itObjects->id << endl;
1118 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1119 error("sendMessage");
1120 }
1121
1122
1123 // send the current score
1124 serverMsg.type = MSG_TYPE_SCORE;
1125
1126 int game_blueScore = g->getBlueScore();
1127 int game_redScore = g->getRedScore();
1128 memcpy(serverMsg.buffer, &game_blueScore, 4);
1129 memcpy(serverMsg.buffer+4, &game_redScore, 4);
1130
1131 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1132 error("sendMessage");
1133
1134 serverMsg.type = MSG_TYPE_PLAYER;
1135 p->serialize(serverMsg.buffer);
1136 cout << "Should be broadcasting the message" << endl;
1137
1138 for (it = otherPlayers.begin(); it != otherPlayers.end(); it++)
1139 {
1140 cout << "Sent message back to " << it->second->name << endl;
1141 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
1142 error("sendMessage");
1143 }
1144
1145 g->addPlayer(p);
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.