source: network-game/server/server.cpp@ 45734ff

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

The Game class stores a list of projectiles present in that game

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