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

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

When a player picks up a flag, the relevant PLAYER message is now broadcast so all players receive it

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