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

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

A player can pick up an opponent's flag in an individual game

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