source: network-game/server/server.cpp@ 204edcf

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

Server uses setters and getters to access id and targetPlayer attributes of the Player class

  • Property mode set to 100644
File size: 26.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#include "../common/GameSummary.h"
39
40#include "DataAccess.h"
41
42using namespace std;
43
44// from used to be const. Removed that so I could take a reference
45// and use it to send messages
46void processMessage(const NETWORK_MSG& clientMsg, struct sockaddr_in& from, MessageProcessor& msgProcessor, map<unsigned int, Player*>& mapPlayers, map<string, Game*>& mapGames, unsigned int& unusedPlayerId);
47
48void updateUnusedPlayerId(unsigned int& id, map<unsigned int, Player*>& mapPlayers);
49Player *findPlayerByName(map<unsigned int, Player*> &m, string name);
50Player *findPlayerByAddr(map<unsigned int, Player*> &m, const sockaddr_in &addr);
51
52void quit(int sig);
53
54bool done;
55
56int main(int argc, char *argv[])
57{
58 int sock, length;
59 struct sockaddr_in server;
60 struct sockaddr_in from; // info of client sending the message
61 NETWORK_MSG clientMsg, serverMsg;
62 MessageProcessor msgProcessor;
63 map<unsigned int, Player*> mapPlayers;
64 map<unsigned int, Projectile> mapProjectiles;
65 map<string, Game*> mapGames;
66 unsigned int unusedPlayerId = 1;
67 ofstream outputLog;
68
69 done = false;
70
71 signal(SIGINT, quit);
72
73 //SSL_load_error_strings();
74 //ERR_load_BIO_strings();
75 //OpenSSL_add_all_algorithms();
76
77 if (argc != 2)
78 {
79 cerr << "ERROR, expected server [domain] [port]" << endl;
80 exit(1);
81 }
82
83 outputLog.open("server.log", ios::app);
84 outputLog << "Started server on " << getCurrentDateTimeString() << endl;
85
86 sock = socket(AF_INET, SOCK_DGRAM, 0);
87 if (sock < 0)
88 error("Opening socket");
89 length = sizeof(server);
90 bzero(&server,length);
91 server.sin_family=AF_INET;
92 server.sin_port=htons(atoi(argv[1]));
93 server.sin_addr.s_addr=INADDR_ANY;
94 if ( bind(sock, (struct sockaddr *)&server, length) < 0 )
95 error("binding");
96
97 set_nonblock(sock);
98
99 msgProcessor = MessageProcessor(sock, &outputLog);
100
101 timespec ts;
102 int timeLastUpdated = 0, curTime = 0;
103 while (!done)
104 {
105 usleep(5000);
106
107 clock_gettime(CLOCK_REALTIME, &ts);
108 // make the number smaller so millis can fit in an int
109 ts.tv_sec -= 1368000000;
110 curTime = ts.tv_sec*1000 + ts.tv_nsec/1000000;
111
112 if (timeLastUpdated == 0 || (curTime-timeLastUpdated) >= 50)
113 {
114 timeLastUpdated = curTime;
115
116 msgProcessor.cleanAckedMessages();
117 msgProcessor.resendUnackedMessages();
118
119 map<unsigned int, Player*>::iterator it;
120
121 cout << "Updating player targets and respawning dead players" << endl;
122
123 // set targets for all chasing players (or make them attack if they're close enough)
124 // this should be moved into the games loop
125 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
126 {
127 Player* p = it->second;
128
129 // check if it's time to revive dead players
130 if (p->isDead)
131 {
132 cout << "Player is dead" << endl;
133
134 if (getCurrentMillis() - p->timeDied >= 10000)
135 {
136 p->isDead = false;
137
138 POSITION spawnPos;
139
140 switch (p->team)
141 {
142 case 0:// blue team
143 spawnPos = p->currentGame->getMap()->getStructureLocation(WorldMap::STRUCTURE_BLUE_FLAG);
144 break;
145 case 1:// red team
146 spawnPos = p->currentGame->getMap()->getStructureLocation(WorldMap::STRUCTURE_RED_FLAG);
147 break;
148 default:
149 // should never go here
150 cout << "Error: Invalid team" << endl;
151 break;
152 }
153
154 // spawn the player to the right of their flag location
155 spawnPos.x = (spawnPos.x+1) * 25 + 12;
156 spawnPos.y = spawnPos.y * 25 + 12;
157
158 p->pos = spawnPos.toFloat();
159 p->target = spawnPos;
160 p->health = p->maxHealth;
161
162 serverMsg.type = MSG_TYPE_PLAYER;
163 p->serialize(serverMsg.buffer);
164
165 msgProcessor.broadcastMessage(serverMsg, p->currentGame->getPlayers());
166 }
167
168 continue;
169 }
170
171 if (p->currentGame != NULL) {
172 map<unsigned int, Player*> playersInGame = p->currentGame->getPlayers();
173 if (p->updateTarget(playersInGame))
174 {
175 serverMsg.type = MSG_TYPE_PLAYER;
176 p->serialize(serverMsg.buffer);
177 msgProcessor.broadcastMessage(serverMsg, playersInGame);
178 }
179 }
180 }
181
182 cout << "Processing players in a game" << endl;
183
184 // process players currently in a game
185 map<string, Game*>::iterator itGames;
186 Game* game = NULL;
187
188 for (itGames = mapGames.begin(); itGames != mapGames.end();) {
189 game = itGames->second;
190 if (game->handleGameEvents()) {
191 // send a GAME_INFO message with 0 players to force clients to delete the game
192 int numPlayers = 0;
193 serverMsg.type = MSG_TYPE_GAME_INFO;
194 memcpy(serverMsg.buffer, &numPlayers, 4);
195 strcpy(serverMsg.buffer+4, game->getName().c_str());
196 msgProcessor.broadcastMessage(serverMsg, mapPlayers);
197
198 delete itGames->second;
199 mapGames.erase(itGames++);
200 }else
201 itGames++;
202 }
203
204 cout << "Processing projectiles" << endl;
205
206 // move all projectiles
207 // see if this can be moved inside the game class
208 // this method can be moved when I add a MessageProcessor to the Game class
209 map<unsigned int, Projectile>::iterator itProj;
210 for (itGames = mapGames.begin(); itGames != mapGames.end(); itGames++) {
211 game = itGames->second;
212 for (itProj = game->getProjectiles().begin(); itProj != game->getProjectiles().end(); itProj++)
213 {
214 cout << "About to call projectile move" << endl;
215 if (itProj->second.move(game->getPlayers()))
216 {
217 // send a REMOVE_PROJECTILE message
218 cout << "send a REMOVE_PROJECTILE message" << endl;
219 serverMsg.type = MSG_TYPE_REMOVE_PROJECTILE;
220 memcpy(serverMsg.buffer, &itProj->second.id, 4);
221 game->removeProjectile(itProj->second.id);
222 msgProcessor.broadcastMessage(serverMsg, game->getPlayers());
223
224 Player* target = game->getPlayers()[itProj->second.target];
225 game->dealDamageToPlayer(target, itProj->second.damage);
226 }
227 }
228 }
229 }
230
231 if (msgProcessor.receiveMessage(&clientMsg, &from) >= 0)
232 {
233 processMessage(clientMsg, from, msgProcessor, mapPlayers, mapGames, unusedPlayerId);
234
235 cout << "Finished processing the message" << endl;
236 }
237 }
238
239 outputLog << "Stopped server on " << getCurrentDateTimeString() << endl;
240 outputLog.close();
241
242 // delete all games
243 map<string, Game*>::iterator itGames;
244 for (itGames = mapGames.begin(); itGames != mapGames.end(); itGames++)
245 {
246 delete itGames->second;
247 }
248
249 map<unsigned int, Player*>::iterator itPlayers;
250 for (itPlayers = mapPlayers.begin(); itPlayers != mapPlayers.end(); itPlayers++)
251 {
252 delete itPlayers->second;
253 }
254
255 return 0;
256}
257
258void processMessage(const NETWORK_MSG &clientMsg, struct sockaddr_in &from, MessageProcessor &msgProcessor, map<unsigned int, Player*>& mapPlayers, map<string, Game*>& mapGames, unsigned int& unusedPlayerId)
259{
260 NETWORK_MSG serverMsg;
261 DataAccess da;
262
263 cout << "Inside processMessage" << endl;
264
265 cout << "Received message" << endl;
266 cout << "MSG: type: " << clientMsg.type << endl;
267 cout << "MSG contents: " << clientMsg.buffer << endl;
268
269 // Check that if an invalid message is sent, the client will correctly
270 // receive and display the response. Maybe make a special error msg type
271 switch(clientMsg.type)
272 {
273 case MSG_TYPE_REGISTER:
274 {
275 string username(clientMsg.buffer);
276 string password(strchr(clientMsg.buffer, '\0')+1);
277 Player::PlayerClass playerClass;
278
279 memcpy(&playerClass, clientMsg.buffer+username.length()+password.length()+2, 4);
280
281 cout << "username: " << username << endl;
282 cout << "password: " << password << endl;
283
284 bool validClass = false;
285
286 switch(playerClass) {
287 case Player::CLASS_WARRIOR:
288 case Player::CLASS_RANGER:
289 validClass = true;
290 break;
291 default:
292 validClass = false;
293 break;
294 }
295
296 serverMsg.type = MSG_TYPE_REGISTER;
297
298 if (validClass) {
299 int error = da.insertPlayer(username, password, playerClass);
300
301 if (error)
302 strcpy(serverMsg.buffer, "Registration failed. Please try again.");
303 else
304 strcpy(serverMsg.buffer, "Registration successful.");
305 }else
306 strcpy(serverMsg.buffer, "You didn't select a class");
307
308 msgProcessor.sendMessage(&serverMsg, &from);
309
310 break;
311 }
312 case MSG_TYPE_LOGIN:
313 {
314 cout << "Got login message" << endl;
315
316 string username(clientMsg.buffer);
317 string password(strchr(clientMsg.buffer, '\0')+1);
318
319 Player* p = da.getPlayer(username);
320
321 if (p == NULL || !da.verifyPassword(password, p->password))
322 {
323 strcpy(serverMsg.buffer, "Incorrect username or password");
324 if (p != NULL)
325 delete(p);
326 }
327 else if(findPlayerByName(mapPlayers, username) != NULL)
328 {
329 strcpy(serverMsg.buffer, "Player has already logged in.");
330 delete(p);
331 }
332 else
333 {
334 updateUnusedPlayerId(unusedPlayerId, mapPlayers);
335 p->setId(unusedPlayerId);
336 cout << "new player id: " << p->getId() << endl;
337 p->setAddr(from);
338 p->currentGame = NULL;
339
340 // choose a random team (either 0 or 1)
341 p->team = rand() % 2;
342
343 serverMsg.type = MSG_TYPE_PLAYER;
344 // tell the new player about all the existing players
345 cout << "Sending other players to new player" << endl;
346
347 map<unsigned int, Player*>::iterator it;
348 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
349 {
350 it->second->serialize(serverMsg.buffer);
351
352 cout << "sending info about " << it->second->name << endl;
353 cout << "sending id " << it->second->getId() << endl;
354 msgProcessor.sendMessage(&serverMsg, &from);
355 }
356
357 // send info about existing games to new player
358 map<string, Game*>::iterator itGames;
359 Game* g;
360 int numPlayers;
361 serverMsg.type = MSG_TYPE_GAME_INFO;
362
363 for (itGames = mapGames.begin(); itGames != mapGames.end(); itGames++)
364 {
365 g = itGames->second;
366 numPlayers = g->getNumPlayers();
367 memcpy(serverMsg.buffer, &numPlayers, 4);
368 strcpy(serverMsg.buffer+4, g->getName().c_str());
369 msgProcessor.sendMessage(&serverMsg, &from);
370 }
371
372 serverMsg.type = MSG_TYPE_PLAYER;
373 p->serialize(serverMsg.buffer);
374 msgProcessor.broadcastMessage(serverMsg, mapPlayers);
375
376 mapPlayers[unusedPlayerId] = p;
377 }
378
379 serverMsg.type = MSG_TYPE_LOGIN;
380 msgProcessor.sendMessage(&serverMsg, &from);
381
382 break;
383 }
384 case MSG_TYPE_LOGOUT:
385 {
386 string name(clientMsg.buffer);
387 cout << "Player logging out: " << name << endl;
388
389 Player *p = findPlayerByName(mapPlayers, name);
390
391 if (p == NULL)
392 {
393 strcpy(serverMsg.buffer+4, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
394 cout << "Player not logged in" << endl;
395 }
396 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
397 p->addr.sin_port != from.sin_port )
398 {
399 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.");
400 cout << "Player logged in using a different connection" << endl;
401 }
402 else
403 {
404 // broadcast to all players before deleting p from the map
405 unsigned int playerId = p->getId();
406 serverMsg.type = MSG_TYPE_LOGOUT;
407 memcpy(serverMsg.buffer, &playerId, 4);
408
409 msgProcessor.broadcastMessage(serverMsg, mapPlayers);
410
411 if (p->getId() < unusedPlayerId)
412 unusedPlayerId = p->getId();
413
414 mapPlayers.erase(p->getId());
415 delete p;
416
417 strcpy(serverMsg.buffer+4, "You have successfully logged out.");
418 }
419
420 serverMsg.type = MSG_TYPE_LOGOUT;
421 msgProcessor.sendMessage(&serverMsg, &from);
422
423 break;
424 }
425 case MSG_TYPE_CHAT:
426 {
427 cout << "Got a chat message" << endl;
428
429 serverMsg.type = MSG_TYPE_CHAT;
430
431 Player *p = findPlayerByAddr(mapPlayers, from);
432
433 if (p == NULL)
434 {
435 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
436 msgProcessor.sendMessage(&serverMsg, &from);
437 }
438 else
439 {
440 ostringstream oss;
441 oss << p->name << ": " << clientMsg.buffer;
442
443 strcpy(serverMsg.buffer, oss.str().c_str());
444 msgProcessor.broadcastMessage(serverMsg, mapPlayers);
445 }
446
447 break;
448 }
449 case MSG_TYPE_PLAYER_MOVE:
450 {
451 cout << "PLAYER_MOVE" << endl;
452
453 unsigned int id;
454 int x, y;
455
456 memcpy(&id, clientMsg.buffer, 4);
457 memcpy(&x, clientMsg.buffer+4, 4);
458 memcpy(&y, clientMsg.buffer+8, 4);
459
460 cout << "x: " << x << endl;
461 cout << "y: " << y << endl;
462 cout << "id: " << id << endl;
463
464 Player* p = mapPlayers[id];
465 bool validMessage = false;
466
467 if ( p->addr.sin_addr.s_addr == from.sin_addr.s_addr &&
468 p->addr.sin_port == from.sin_port )
469 {
470 if (p->currentGame->startPlayerMovement(id, x, y)) {
471 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
472
473 memcpy(serverMsg.buffer, &id, 4);
474 memcpy(serverMsg.buffer+4, &p->target.x, 4);
475 memcpy(serverMsg.buffer+8, &p->target.y, 4);
476
477 msgProcessor.broadcastMessage(serverMsg, mapPlayers);
478
479 validMessage = true;
480 }
481 else
482 cout << "Bad terrain detected" << endl;
483 }
484 else
485 cout << "Player id (" << id << ") doesn't match sender" << endl;
486
487 if (!validMessage)
488 msgProcessor.sendMessage(&serverMsg, &from);
489
490 break;
491 }
492 case MSG_TYPE_PICKUP_FLAG:
493 {
494 // may want to check the id matches the sender, just like for PLAYER_NOVE
495 cout << "PICKUP_FLAG" << endl;
496
497 unsigned int id;
498
499 memcpy(&id, clientMsg.buffer, 4);
500 cout << "id: " << id << endl;
501
502 Player* p = mapPlayers[id];
503 unsigned int objectId = p->currentGame->processFlagPickupRequest(p);
504
505 if (objectId >= 0) {
506 map<unsigned int, Player*> players = p->currentGame->getPlayers();
507
508 serverMsg.type = MSG_TYPE_REMOVE_OBJECT;
509 memcpy(serverMsg.buffer, &objectId, 4);
510 msgProcessor.broadcastMessage(serverMsg, players);
511
512 serverMsg.type = MSG_TYPE_PLAYER;
513 p->serialize(serverMsg.buffer);
514 msgProcessor.broadcastMessage(serverMsg, players);
515 }
516
517 break;
518 }
519 case MSG_TYPE_DROP_FLAG:
520 {
521 // may want to check the id matches the sender, just like for PLAYER_NOVE
522 cout << "DROP_FLAG" << endl;
523
524 unsigned int id;
525
526 memcpy(&id, clientMsg.buffer, 4);
527 cout << "id: " << id << endl;
528
529 Player* p = mapPlayers[id];
530
531 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
532 if (p->hasBlueFlag)
533 flagType = WorldMap::OBJECT_BLUE_FLAG;
534 else if (p->hasRedFlag)
535 flagType = WorldMap::OBJECT_RED_FLAG;
536
537 map<unsigned int, Player*> players = p->currentGame->getPlayers();
538
539 p->currentGame->addObjectToMap(flagType, p->pos.x, p->pos.y);
540
541 p->hasBlueFlag = false;
542 p->hasRedFlag = false;
543
544 serverMsg.type = MSG_TYPE_PLAYER;
545 p->serialize(serverMsg.buffer);
546 msgProcessor.broadcastMessage(serverMsg, players);
547
548 break;
549 }
550 case MSG_TYPE_ATTACK:
551 {
552 cout << "Received a START_ATTACK message" << endl;
553
554 unsigned int id, targetId;
555
556 memcpy(&id, clientMsg.buffer, 4);
557 memcpy(&targetId, clientMsg.buffer+4, 4);
558
559 // need to make sure the target is in the sender's game
560
561 Player* p = mapPlayers[id];
562 p->setTargetPlayer(targetId);
563 p->isChasing = true;
564
565 map<unsigned int, Player*> players = p->currentGame->getPlayers();
566
567 serverMsg.type = MSG_TYPE_ATTACK;
568 memcpy(serverMsg.buffer, &id, 4);
569 memcpy(serverMsg.buffer+4, &targetId, 4);
570 msgProcessor.broadcastMessage(serverMsg, players);
571
572 break;
573 }
574 case MSG_TYPE_CREATE_GAME:
575 {
576 cout << "Received a CREATE_GAME message" << endl;
577
578 string gameName(clientMsg.buffer);
579 cout << "Game name: " << gameName << endl;
580
581 // check if this game already exists
582 if (mapGames.find(gameName) != mapGames.end()) {
583 cout << "Error: Game already exists" << endl;
584 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
585 }else {
586 Game* g = new Game(gameName, "../data/map.txt", &msgProcessor);
587 mapGames[gameName] = g;
588
589 // add flag objects to the map
590 WorldMap* m = g->getMap();
591 for (int y=0; y<m->height; y++) {
592 for (int x=0; x<m->width; x++) {
593 switch (m->getStructure(x, y)) {
594 case WorldMap::STRUCTURE_BLUE_FLAG:
595 m->addObject(WorldMap::OBJECT_BLUE_FLAG, x*25+12, y*25+12);
596 break;
597 case WorldMap::STRUCTURE_RED_FLAG:
598 m->addObject(WorldMap::OBJECT_RED_FLAG, x*25+12, y*25+12);
599 break;
600 case WorldMap::STRUCTURE_NONE:
601 break;
602 }
603 }
604 }
605
606 serverMsg.type = MSG_TYPE_JOIN_GAME_SUCCESS;
607 strcpy(serverMsg.buffer, gameName.c_str());
608 }
609
610 msgProcessor.sendMessage(&serverMsg, &from);
611
612 break;
613 }
614 case MSG_TYPE_JOIN_GAME:
615 {
616 cout << "Received a JOIN_GAME message" << endl;
617
618 string gameName(clientMsg.buffer);
619 cout << "Game name: " << gameName << endl;
620
621 // check if this game already exists
622 if (mapGames.find(gameName) == mapGames.end()) {
623 cout << "Error: Game does not exist" << endl;
624 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
625 }else {
626 Game* g = mapGames[gameName];
627 map<unsigned int, Player*>& players = g->getPlayers();
628 Player* p = findPlayerByAddr(mapPlayers, from);
629
630 if (players.find(p->getId()) != players.end()) {
631 cout << "Player " << p->name << " trying to join a game he's already in" << endl;
632 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
633 }else {
634 serverMsg.type = MSG_TYPE_JOIN_GAME_SUCCESS;
635 strcpy(serverMsg.buffer, gameName.c_str());
636 }
637 }
638
639 msgProcessor.sendMessage(&serverMsg, &from);
640
641 break;
642 }
643 case MSG_TYPE_LEAVE_GAME:
644 {
645 cout << "Received a LEAVE_GAME message" << endl;
646
647 Player* p = findPlayerByAddr(mapPlayers, from);
648 Game* g = p->currentGame;
649
650 if (g == NULL) {
651 cout << "Player " << p->name << " is trying to leave a game, but is not currently in a game." << endl;
652
653 /// should send a response back, maybe a new message type is needed
654 // not sure what to do here
655 }else {
656 cout << "Game name: " << g->getName() << endl;
657
658 if (!p->isDead) {
659 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
660 if (p->hasBlueFlag)
661 flagType = WorldMap::OBJECT_BLUE_FLAG;
662 else if (p->hasRedFlag)
663 flagType = WorldMap::OBJECT_RED_FLAG;
664
665 if (flagType != WorldMap::OBJECT_NONE)
666 g->addObjectToMap(flagType, p->pos.x, p->pos.y);
667 }
668
669 p->currentGame = NULL;
670 g->removePlayer(p->getId());
671
672 unsigned int playerId = p->getId();
673 serverMsg.type = MSG_TYPE_LEAVE_GAME;
674 memcpy(serverMsg.buffer, &playerId, 4);
675 strcpy(serverMsg.buffer+4, g->getName().c_str());
676 msgProcessor.broadcastMessage(serverMsg, g->getPlayers());
677
678 int numPlayers = g->getNumPlayers();
679
680 serverMsg.type = MSG_TYPE_GAME_INFO;
681 memcpy(serverMsg.buffer, &numPlayers, 4);
682 strcpy(serverMsg.buffer+4, g->getName().c_str());
683 msgProcessor.broadcastMessage(serverMsg, mapPlayers);
684
685 // if there are no more players in the game, remove it
686 if (numPlayers == 0) {
687 mapGames.erase(g->getName());
688 delete g;
689 }
690 }
691
692 break;
693 }
694 case MSG_TYPE_JOIN_GAME_ACK:
695 {
696 cout << "Received a JOIN_GAME_ACK message" << endl;
697
698 string gameName(clientMsg.buffer);
699 cout << "Game name: " << gameName << endl;
700
701 // check if this game already exists
702 if (mapGames.find(gameName) == mapGames.end()) {
703 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
704
705 msgProcessor.sendMessage(&serverMsg, &from);
706 }
707
708 Game* g = mapGames[gameName];
709
710 Player* p = findPlayerByAddr(mapPlayers, from);
711 p->team = rand() % 2; // choose a random team (either 0 or 1)
712 p->currentGame = g;
713
714 // tell the new player about all map objects
715 // (currently just the flags)
716
717 serverMsg.type = MSG_TYPE_OBJECT;
718 vector<WorldMap::Object>* vctObjects = g->getMap()->getObjects();
719 vector<WorldMap::Object>::iterator itObjects;
720 cout << "sending items" << endl;
721 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
722 itObjects->serialize(serverMsg.buffer);
723 cout << "sending item id " << itObjects->id << endl;
724 msgProcessor.sendMessage(&serverMsg, &from);
725 }
726
727
728 // send the current score
729 serverMsg.type = MSG_TYPE_SCORE;
730
731 unsigned int blueScore = g->getBlueScore();
732 unsigned int redScore = g->getRedScore();
733 memcpy(serverMsg.buffer, &blueScore, 4);
734 memcpy(serverMsg.buffer+4, &redScore, 4);
735
736 msgProcessor.sendMessage(&serverMsg, &from);
737
738 // send info to other players
739 serverMsg.type = MSG_TYPE_PLAYER_JOIN_GAME;
740 p->serialize(serverMsg.buffer);
741 cout << "Should be broadcasting the message" << endl;
742 msgProcessor.broadcastMessage(serverMsg, g->getPlayers());
743
744 g->addPlayer(p);
745
746
747 // tell the new player about all the players in the game (including himself)
748 cout << "Sending other players to new player" << endl;
749 serverMsg.type = MSG_TYPE_PLAYER_JOIN_GAME;
750
751
752 map<unsigned int, Player*>& allPlayers = g->getPlayers();
753 map<unsigned int, Player*>::iterator it;
754 for (it = allPlayers.begin(); it != allPlayers.end(); it++)
755 {
756 it->second->serialize(serverMsg.buffer);
757
758 cout << "sending info about " << it->second->name << endl;
759 cout << "sending id " << it->second->getId() << endl;
760 msgProcessor.sendMessage(&serverMsg, &from);
761 }
762
763 int numPlayers = g->getNumPlayers();
764
765 serverMsg.type = MSG_TYPE_GAME_INFO;
766 memcpy(serverMsg.buffer, &numPlayers, 4);
767 strcpy(serverMsg.buffer+4, gameName.c_str());
768 msgProcessor.broadcastMessage(serverMsg, mapPlayers);
769
770 break;
771 }
772 default:
773 {
774 // probably want to log the error rather than sending a chat message,
775 // especially since chat isn't currently visible on all screens
776
777 serverMsg.type = MSG_TYPE_CHAT;
778 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
779
780 break;
781 }
782 }
783}
784
785void updateUnusedPlayerId(unsigned int& id, map<unsigned int, Player*>& mapPlayers)
786{
787 while (mapPlayers.find(id) != mapPlayers.end())
788 id++;
789}
790
791Player *findPlayerByName(map<unsigned int, Player*> &m, string name)
792{
793 map<unsigned int, Player*>::iterator it;
794
795 for (it = m.begin(); it != m.end(); it++)
796 {
797 if ( it->second->name.compare(name) == 0 )
798 return it->second;
799 }
800
801 return NULL;
802}
803
804Player *findPlayerByAddr(map<unsigned int, Player*> &m, const sockaddr_in &addr)
805{
806 map<unsigned int, Player*>::iterator it;
807
808 for (it = m.begin(); it != m.end(); it++)
809 {
810 if ( it->second->addr.sin_addr.s_addr == addr.sin_addr.s_addr &&
811 it->second->addr.sin_port == addr.sin_port )
812 return it->second;
813 }
814
815 return NULL;
816}
817
818void quit(int sig) {
819 done = true;
820}
Note: See TracBrowser for help on using the repository browser.