source: network-game/server/server.cpp@ 686589c

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

A player gets a list of existing games when they login

  • Property mode set to 100644
File size: 43.8 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 info about existing games to new player
711 map<string, Game*>::iterator itGames;
712 Game* g;
713 int numPlayers;
714 serverMsg.type = MSG_TYPE_GAME_INFO;
715
716 for (itGames = mapGames.begin(); itGames != mapGames.end(); itGames++)
717 {
718 g = itGames->second;
719 numPlayers = g->getNumPlayers();
720 memcpy(serverMsg.buffer, &numPlayers, 4);
721 strcpy(serverMsg.buffer+4, g->getName().c_str());
722 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
723 error("sendMessage");
724 }
725
726 // send the current score
727 serverMsg.type = MSG_TYPE_SCORE;
728 memcpy(serverMsg.buffer, &scoreBlue, 4);
729 memcpy(serverMsg.buffer+4, &scoreRed, 4);
730 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
731 error("sendMessage");
732
733 serverMsg.type = MSG_TYPE_PLAYER;
734 p->serialize(serverMsg.buffer);
735 cout << "Should be broadcasting the message" << endl;
736
737 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
738 {
739 cout << "Sent message back to " << it->second->name << endl;
740 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
741 error("sendMessage");
742 }
743
744 mapPlayers[unusedPlayerId] = p;
745 }
746
747 serverMsg.type = MSG_TYPE_LOGIN;
748
749 break;
750 }
751 case MSG_TYPE_LOGOUT:
752 {
753 string name(clientMsg.buffer);
754 cout << "Player logging out: " << name << endl;
755
756 Player *p = findPlayerByName(mapPlayers, name);
757
758 if (p == NULL)
759 {
760 strcpy(serverMsg.buffer+4, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
761 cout << "Player not logged in" << endl;
762 }
763 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
764 p->addr.sin_port != from.sin_port )
765 {
766 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.");
767 cout << "Player logged in using a different connection" << endl;
768 }
769 else
770 {
771 if (!p->isDead) {
772 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
773 if (p->hasBlueFlag)
774 flagType = WorldMap::OBJECT_BLUE_FLAG;
775 else if (p->hasRedFlag)
776 flagType = WorldMap::OBJECT_RED_FLAG;
777
778 if (flagType != WorldMap::OBJECT_NONE) {
779 addObjectToMap(flagType, p->pos.x, p->pos.y, gameMap, mapPlayers, msgProcessor, sock, outputLog);
780 }
781 }
782
783 // broadcast to all players before deleting p from the map
784 serverMsg.type = MSG_TYPE_LOGOUT;
785 memcpy(serverMsg.buffer, &p->id, 4);
786
787 map<unsigned int, Player*>::iterator it;
788 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
789 {
790 cout << "Sent message back to " << it->second->name << endl;
791 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
792 error("sendMessage");
793 }
794
795 if (p->id < unusedPlayerId)
796 unusedPlayerId = p->id;
797 mapPlayers.erase(p->id);
798 delete p;
799 strcpy(serverMsg.buffer+4, "You have successfully logged out.");
800 }
801
802 serverMsg.type = MSG_TYPE_LOGOUT;
803
804 break;
805 }
806 case MSG_TYPE_CHAT:
807 {
808 cout << "Got a chat message" << endl;
809
810 Player *p = findPlayerByAddr(mapPlayers, from);
811
812 if (p == NULL)
813 {
814 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
815 }
816 else
817 {
818 broadcastResponse = true;
819
820 ostringstream oss;
821 oss << p->name << ": " << clientMsg.buffer;
822
823 strcpy(serverMsg.buffer, oss.str().c_str());
824 }
825
826 serverMsg.type = MSG_TYPE_CHAT;
827
828 break;
829 }
830 case MSG_TYPE_PLAYER_MOVE:
831 {
832 cout << "PLAYER_MOVE" << endl;
833
834 int id, x, y;
835
836 memcpy(&id, clientMsg.buffer, 4);
837 memcpy(&x, clientMsg.buffer+4, 4);
838 memcpy(&y, clientMsg.buffer+8, 4);
839
840 cout << "x: " << x << endl;
841 cout << "y: " << y << endl;
842 cout << "id: " << id << endl;
843
844 Player* p = mapPlayers[id];
845
846 if ( p->addr.sin_addr.s_addr == from.sin_addr.s_addr &&
847 p->addr.sin_port == from.sin_port )
848 {
849 if (p->currentGame->startPlayerMovement(id, x, y)) {
850 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
851
852 memcpy(serverMsg.buffer, &id, 4);
853 memcpy(serverMsg.buffer+4, &p->target.x, 4);
854 memcpy(serverMsg.buffer+8, &p->target.y, 4);
855
856 broadcastResponse = true;
857 }
858 else
859 cout << "Bad terrain detected" << endl;
860 }
861 else // nned to send back a message indicating failure
862 cout << "Player id (" << id << ") doesn't match sender" << endl;
863
864 break;
865 }
866 case MSG_TYPE_PICKUP_FLAG:
867 {
868 // may want to check the id matches the sender, just like for PLAYER_NOVE
869 cout << "PICKUP_FLAG" << endl;
870
871 int id;
872
873 memcpy(&id, clientMsg.buffer, 4);
874 cout << "id: " << id << endl;
875
876 Player* p = mapPlayers[id];
877 int objectId = p->currentGame->processFlagPickupRequest(p);
878
879 if (objectId >= 0) {
880 serverMsg.type = MSG_TYPE_REMOVE_OBJECT;
881 memcpy(serverMsg.buffer, &objectId, 4);
882
883 map<unsigned int, Player*> players = p->currentGame->getPlayers();
884 map<unsigned int, Player*>::iterator it;
885 for (it = players.begin(); it != players.end(); it++)
886 {
887 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
888 error("sendMessage");
889 }
890
891 }
892
893 // if there was no flag to pickup, we really don't need to send a message
894 serverMsg.type = MSG_TYPE_PLAYER;
895 p->serialize(serverMsg.buffer);
896
897 break;
898 }
899 case MSG_TYPE_DROP_FLAG:
900 {
901 // may want to check the id matches the sender, just like for PLAYER_NOVE
902 cout << "DROP_FLAG" << endl;
903
904 int id;
905
906 memcpy(&id, clientMsg.buffer, 4);
907 cout << "id: " << id << endl;
908
909 Player* p = mapPlayers[id];
910
911 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
912 if (p->hasBlueFlag)
913 flagType = WorldMap::OBJECT_BLUE_FLAG;
914 else if (p->hasRedFlag)
915 flagType = WorldMap::OBJECT_RED_FLAG;
916
917 addObjectToMap(flagType, p->pos.x, p->pos.y, p->currentGame->getMap(), p->currentGame->getPlayers(), msgProcessor, sock, outputLog);
918
919 p->hasBlueFlag = false;
920 p->hasRedFlag = false;
921
922 serverMsg.type = MSG_TYPE_PLAYER;
923 p->serialize(serverMsg.buffer);
924
925 broadcastResponse = true;
926
927 break;
928 }
929 case MSG_TYPE_START_ATTACK:
930 {
931 cout << "Received a START_ATTACK message" << endl;
932
933 int id, targetId;
934
935 memcpy(&id, clientMsg.buffer, 4);
936 memcpy(&targetId, clientMsg.buffer+4, 4);
937
938 Player* source = mapPlayers[id];
939 source->targetPlayer = targetId;
940 source->isChasing = true;
941
942 // this is irrelevant since the client doesn't even listen for START_ATTACK messages
943 // actually, the client should not ignore this and should instead perform the same movement
944 // algorithm on its end (following the target player until in range) that the server does.
945 // Once the attacker is in range, the client should stop movement and wait for messages
946 // from the server
947 serverMsg.type = MSG_TYPE_START_ATTACK;
948 memcpy(serverMsg.buffer, &id, 4);
949 memcpy(serverMsg.buffer+4, &targetId, 4);
950 broadcastResponse = true;
951
952 break;
953 }
954 case MSG_TYPE_ATTACK:
955 {
956 cout << "Received am ATTACK message" << endl;
957 cout << "ERROR: Clients should not send ATTACK messages" << endl;
958
959 break;
960 }
961 case MSG_TYPE_CREATE_GAME:
962 {
963 cout << "Received a CREATE_GAME message" << endl;
964
965 string gameName(clientMsg.buffer);
966 cout << "Game name: " << gameName << endl;
967
968 // check if this game already exists
969 if (mapGames.find(gameName) != mapGames.end()) {
970 cout << "Error: Game already exists" << endl;
971 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
972 broadcastResponse = false;
973 return broadcastResponse;
974 }
975
976 Game* g = new Game(gameName, "../data/map.txt");
977 mapGames[gameName] = g;
978
979 // add flag objects to the map
980 WorldMap* m = g->getMap();
981 for (int y=0; y<m->height; y++) {
982 for (int x=0; x<m->width; x++) {
983 switch (m->getStructure(x, y)) {
984 case WorldMap::STRUCTURE_BLUE_FLAG:
985 m->addObject(WorldMap::OBJECT_BLUE_FLAG, x*25+12, y*25+12);
986 break;
987 case WorldMap::STRUCTURE_RED_FLAG:
988 m->addObject(WorldMap::OBJECT_RED_FLAG, x*25+12, y*25+12);
989 break;
990 }
991 }
992 }
993
994 Player* p = findPlayerByAddr(mapPlayers, from);
995 p->currentGame = g;
996
997 serverMsg.type = MSG_TYPE_JOIN_GAME_SUCCESS;
998 strcpy(serverMsg.buffer, gameName.c_str());
999 broadcastResponse = false;
1000
1001 break;
1002 }
1003 case MSG_TYPE_JOIN_GAME:
1004 {
1005 cout << "Received a JOIN_GAME message" << endl;
1006
1007 string gameName(clientMsg.buffer);
1008 cout << "Game name: " << gameName << endl;
1009
1010 // check if this game already exists
1011 if (mapGames.find(gameName) == mapGames.end()) {
1012 cout << "Error: Game does not exist" << endl;
1013 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1014 broadcastResponse = false;
1015 return broadcastResponse;
1016 }
1017
1018 Game* g = mapGames[gameName];
1019 map<unsigned int, Player*>& players = g->getPlayers();
1020 Player* p = findPlayerByAddr(mapPlayers, from);
1021
1022 if (players.find(p->id) != players.end()) {
1023 cout << "Player " << p->name << " trying to join a game he's already in" << endl;
1024 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1025 broadcastResponse = false;
1026 return broadcastResponse;
1027 }
1028
1029 p->currentGame = g;
1030
1031 serverMsg.type = MSG_TYPE_JOIN_GAME_SUCCESS;
1032 strcpy(serverMsg.buffer, gameName.c_str());
1033 broadcastResponse = false;
1034
1035 break;
1036 }
1037 case MSG_TYPE_LEAVE_GAME:
1038 {
1039 cout << "Received a LEAVE_GAME message" << endl;
1040
1041 Player* p = findPlayerByAddr(mapPlayers, from);
1042 Game* g = p->currentGame;
1043
1044 if (g == NULL) {
1045 cout << "Player " << p->name << " is trying to leave a game, but is not currently in a game." << endl;
1046
1047 /// should send a response back, maybe a new message type is needed
1048
1049 break;
1050 }
1051
1052 cout << "Game name: " << g->getName() << endl;
1053 p->currentGame = NULL;
1054
1055 serverMsg.type = MSG_TYPE_LEAVE_GAME;
1056 memcpy(serverMsg.buffer, &p->id, 4);
1057 strcpy(serverMsg.buffer+4, g->getName().c_str());
1058
1059 map<unsigned int, Player*>& players = g->getPlayers();
1060
1061 map<unsigned int, Player*>::iterator it;
1062 for (it = players.begin(); it != players.end(); it++)
1063 {
1064 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
1065 error("sendMessage");
1066 }
1067
1068 g->removePlayer(p->id);
1069
1070 int numPlayers = g->getNumPlayers();
1071
1072 serverMsg.type = MSG_TYPE_GAME_INFO;
1073 memcpy(serverMsg.buffer, &numPlayers, 4);
1074 strcpy(serverMsg.buffer+4, g->getName().c_str());
1075 broadcastResponse = true;
1076
1077 // if there are no more players in the game, remove it
1078 if (numPlayers == 0) {
1079 mapGames.erase(g->getName());
1080 delete g;
1081 }
1082
1083 break;
1084 }
1085 case MSG_TYPE_JOIN_GAME_ACK:
1086 {
1087 cout << "Received a JOIN_GAME_ACK message" << endl;
1088
1089 string gameName(clientMsg.buffer);
1090 cout << "Game name: " << gameName << endl;
1091
1092 // check if this game already exists
1093 if (mapGames.find(gameName) == mapGames.end()) {
1094 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1095 broadcastResponse = false;
1096 return broadcastResponse;
1097 }
1098
1099 Game* g = mapGames[gameName];
1100
1101 Player* p = findPlayerByAddr(mapPlayers, from);
1102 p->team = rand() % 2; // choose a random team (either 0 or 1)
1103 p->currentGame = g; // should have been done in JOIN_GAME, so not necessary
1104
1105 // tell the new player about all map objects
1106 // (currently just the flags)
1107
1108 serverMsg.type = MSG_TYPE_OBJECT;
1109 vector<WorldMap::Object>* vctObjects = g->getMap()->getObjects();
1110 vector<WorldMap::Object>::iterator itObjects;
1111 cout << "sending items" << endl;
1112 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
1113 itObjects->serialize(serverMsg.buffer);
1114 cout << "sending item id " << itObjects->id << endl;
1115 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1116 error("sendMessage");
1117 }
1118
1119
1120 // send the current score
1121 serverMsg.type = MSG_TYPE_SCORE;
1122
1123 int game_blueScore = g->getBlueScore();
1124 int game_redScore = g->getRedScore();
1125 memcpy(serverMsg.buffer, &game_blueScore, 4);
1126 memcpy(serverMsg.buffer+4, &game_redScore, 4);
1127
1128 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1129 error("sendMessage");
1130
1131 serverMsg.type = MSG_TYPE_PLAYER_JOIN_GAME;
1132 p->serialize(serverMsg.buffer);
1133 cout << "Should be broadcasting the message" << endl;
1134
1135 map<unsigned int, Player*>& otherPlayers = g->getPlayers();
1136 map<unsigned int, Player*>::iterator it;
1137 for (it = otherPlayers.begin(); it != otherPlayers.end(); it++)
1138 {
1139 cout << "Sent message back to " << it->second->name << endl;
1140 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
1141 error("sendMessage");
1142 }
1143
1144 g->addPlayer(p);
1145
1146 map<unsigned int, Player*>& allPlayers = g->getPlayers();
1147
1148 // tell the new player about all the players in the game (including himself)
1149 cout << "Sending other players to new player" << endl;
1150 serverMsg.type = MSG_TYPE_PLAYER_JOIN_GAME;
1151
1152 for (it = allPlayers.begin(); it != allPlayers.end(); it++)
1153 {
1154 it->second->serialize(serverMsg.buffer);
1155
1156 cout << "sending info about " << it->second->name << endl;
1157 cout << "sending id " << it->second->id << endl;
1158 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1159 error("sendMessage");
1160 }
1161
1162 int numPlayers = g->getNumPlayers();
1163
1164 serverMsg.type = MSG_TYPE_GAME_INFO;
1165 memcpy(serverMsg.buffer, &numPlayers, 4);
1166 strcpy(serverMsg.buffer+4, gameName.c_str());
1167 broadcastResponse = true;
1168
1169 break;
1170 }
1171 default:
1172 {
1173 serverMsg.type = MSG_TYPE_CHAT;
1174 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
1175
1176 break;
1177 }
1178 }
1179
1180 return broadcastResponse;
1181}
1182
1183void updateUnusedPlayerId(unsigned int& id, map<unsigned int, Player*>& mapPlayers)
1184{
1185 while (mapPlayers.find(id) != mapPlayers.end())
1186 id++;
1187}
1188
1189void updateUnusedProjectileId(unsigned int& id, map<unsigned int, Projectile>& mapProjectiles)
1190{
1191 while (mapProjectiles.find(id) != mapProjectiles.end())
1192 id++;
1193}
1194
1195Player *findPlayerByName(map<unsigned int, Player*> &m, string name)
1196{
1197 map<unsigned int, Player*>::iterator it;
1198
1199 for (it = m.begin(); it != m.end(); it++)
1200 {
1201 if ( it->second->name.compare(name) == 0 )
1202 return it->second;
1203 }
1204
1205 return NULL;
1206}
1207
1208Player *findPlayerByAddr(map<unsigned int, Player*> &m, const sockaddr_in &addr)
1209{
1210 map<unsigned int, Player*>::iterator it;
1211
1212 for (it = m.begin(); it != m.end(); it++)
1213 {
1214 if ( it->second->addr.sin_addr.s_addr == addr.sin_addr.s_addr &&
1215 it->second->addr.sin_port == addr.sin_port )
1216 return it->second;
1217 }
1218
1219 return NULL;
1220}
1221
1222void damagePlayer(Player *p, int damage) {
1223 p->health -= damage;
1224 if (p->health < 0)
1225 p->health = 0;
1226 if (p->health == 0) {
1227 cout << "Player died" << endl;
1228 p->isDead = true;
1229 p->timeDied = getCurrentMillis();
1230 }
1231}
1232
1233void addObjectToMap(WorldMap::ObjectType objectType, int x, int y, WorldMap* gameMap, map<unsigned int, Player*>& mapPlayers, MessageProcessor &msgProcessor, int sock, ofstream& outputLog) {
1234 NETWORK_MSG serverMsg;
1235
1236 gameMap->addObject(objectType, x, y);
1237
1238 // need to send the OBJECT message too
1239 serverMsg.type = MSG_TYPE_OBJECT;
1240 gameMap->getObjects()->back().serialize(serverMsg.buffer);
1241
1242 map<unsigned int, Player*>::iterator it;
1243 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
1244 {
1245 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
1246 error("sendMessage");
1247 }
1248}
Note: See TracBrowser for help on using the repository browser.