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

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

The code that processes player movement, attacks, and flag captures has been restructured to work on a per-game basis

  • 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 break;
949 }
950 case MSG_TYPE_DROP_FLAG:
951 {
952 // may want to check the id matches the sender, just like for PLAYER_NOVE
953 cout << "DROP_FLAG" << endl;
954
955 int id;
956
957 memcpy(&id, clientMsg.buffer, 4);
958 cout << "id: " << id << endl;
959
960 Player* p = mapPlayers[id];
961
962 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
963 if (p->hasBlueFlag)
964 flagType = WorldMap::OBJECT_BLUE_FLAG;
965 else if (p->hasRedFlag)
966 flagType = WorldMap::OBJECT_RED_FLAG;
967
968 addObjectToMap(flagType, p->pos.x, p->pos.y, p->currentGame->getMap(), p->currentGame->getPlayers(), msgProcessor, sock, outputLog);
969
970 p->hasBlueFlag = false;
971 p->hasRedFlag = false;
972
973 serverMsg.type = MSG_TYPE_PLAYER;
974 p->serialize(serverMsg.buffer);
975
976 broadcastResponse = true;
977
978 break;
979 }
980 case MSG_TYPE_START_ATTACK:
981 {
982 cout << "Received a START_ATTACK message" << endl;
983
984 int id, targetId;
985
986 memcpy(&id, clientMsg.buffer, 4);
987 memcpy(&targetId, clientMsg.buffer+4, 4);
988
989 // need to make sure the target is in the sender's game
990
991 Player* source = mapPlayers[id];
992 source->targetPlayer = targetId;
993 source->isChasing = true;
994
995 // this is irrelevant since the client doesn't even listen for START_ATTACK messages
996 // actually, the client should not ignore this and should instead perform the same movement
997 // algorithm on its end (following the target player until in range) that the server does.
998 // Once the attacker is in range, the client should stop movement and wait for messages
999 // from the server
1000 serverMsg.type = MSG_TYPE_START_ATTACK;
1001 memcpy(serverMsg.buffer, &id, 4);
1002 memcpy(serverMsg.buffer+4, &targetId, 4);
1003 broadcastResponse = true;
1004
1005 break;
1006 }
1007 case MSG_TYPE_ATTACK:
1008 {
1009 cout << "Received am ATTACK message" << endl;
1010 cout << "ERROR: Clients should not send ATTACK messages" << endl;
1011
1012 break;
1013 }
1014 case MSG_TYPE_CREATE_GAME:
1015 {
1016 cout << "Received a CREATE_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 already exists" << endl;
1024 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1025 broadcastResponse = false;
1026 return broadcastResponse;
1027 }
1028
1029 Game* g = new Game(gameName, "../data/map.txt");
1030 mapGames[gameName] = g;
1031
1032 // add flag objects to the map
1033 WorldMap* m = g->getMap();
1034 for (int y=0; y<m->height; y++) {
1035 for (int x=0; x<m->width; x++) {
1036 switch (m->getStructure(x, y)) {
1037 case WorldMap::STRUCTURE_BLUE_FLAG:
1038 m->addObject(WorldMap::OBJECT_BLUE_FLAG, x*25+12, y*25+12);
1039 break;
1040 case WorldMap::STRUCTURE_RED_FLAG:
1041 m->addObject(WorldMap::OBJECT_RED_FLAG, x*25+12, y*25+12);
1042 break;
1043 }
1044 }
1045 }
1046
1047 serverMsg.type = MSG_TYPE_JOIN_GAME_SUCCESS;
1048 strcpy(serverMsg.buffer, gameName.c_str());
1049 broadcastResponse = false;
1050
1051 break;
1052 }
1053 case MSG_TYPE_JOIN_GAME:
1054 {
1055 cout << "Received a JOIN_GAME message" << endl;
1056
1057 string gameName(clientMsg.buffer);
1058 cout << "Game name: " << gameName << endl;
1059
1060 // check if this game already exists
1061 if (mapGames.find(gameName) == mapGames.end()) {
1062 cout << "Error: Game does not exist" << endl;
1063 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1064 broadcastResponse = false;
1065 return broadcastResponse;
1066 }
1067
1068 Game* g = mapGames[gameName];
1069 map<unsigned int, Player*>& players = g->getPlayers();
1070 Player* p = findPlayerByAddr(mapPlayers, from);
1071
1072 if (players.find(p->id) != players.end()) {
1073 cout << "Player " << p->name << " trying to join a game he's already in" << endl;
1074 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1075 broadcastResponse = false;
1076 return broadcastResponse;
1077 }
1078
1079 serverMsg.type = MSG_TYPE_JOIN_GAME_SUCCESS;
1080 strcpy(serverMsg.buffer, gameName.c_str());
1081 broadcastResponse = false;
1082
1083 break;
1084 }
1085 case MSG_TYPE_LEAVE_GAME:
1086 {
1087 cout << "Received a LEAVE_GAME message" << endl;
1088
1089 Player* p = findPlayerByAddr(mapPlayers, from);
1090 Game* g = p->currentGame;
1091
1092 if (g == NULL) {
1093 cout << "Player " << p->name << " is trying to leave a game, but is not currently in a game." << endl;
1094
1095 /// should send a response back, maybe a new message type is needed
1096
1097 break;
1098 }
1099
1100 cout << "Game name: " << g->getName() << endl;
1101 p->currentGame = NULL;
1102
1103 serverMsg.type = MSG_TYPE_LEAVE_GAME;
1104 memcpy(serverMsg.buffer, &p->id, 4);
1105 strcpy(serverMsg.buffer+4, g->getName().c_str());
1106
1107 map<unsigned int, Player*>& players = g->getPlayers();
1108
1109 map<unsigned int, Player*>::iterator it;
1110 for (it = players.begin(); it != players.end(); it++)
1111 {
1112 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
1113 error("sendMessage");
1114 }
1115
1116 g->removePlayer(p->id);
1117
1118 int numPlayers = g->getNumPlayers();
1119
1120 serverMsg.type = MSG_TYPE_GAME_INFO;
1121 memcpy(serverMsg.buffer, &numPlayers, 4);
1122 strcpy(serverMsg.buffer+4, g->getName().c_str());
1123 broadcastResponse = true;
1124
1125 // if there are no more players in the game, remove it
1126 if (numPlayers == 0) {
1127 mapGames.erase(g->getName());
1128 delete g;
1129 }
1130
1131 break;
1132 }
1133 case MSG_TYPE_JOIN_GAME_ACK:
1134 {
1135 cout << "Received a JOIN_GAME_ACK message" << endl;
1136
1137 string gameName(clientMsg.buffer);
1138 cout << "Game name: " << gameName << endl;
1139
1140 // check if this game already exists
1141 if (mapGames.find(gameName) == mapGames.end()) {
1142 serverMsg.type = MSG_TYPE_JOIN_GAME_FAILURE;
1143 broadcastResponse = false;
1144 return broadcastResponse;
1145 }
1146
1147 Game* g = mapGames[gameName];
1148
1149 Player* p = findPlayerByAddr(mapPlayers, from);
1150 p->team = rand() % 2; // choose a random team (either 0 or 1)
1151 p->currentGame = g;
1152
1153 // tell the new player about all map objects
1154 // (currently just the flags)
1155
1156 serverMsg.type = MSG_TYPE_OBJECT;
1157 vector<WorldMap::Object>* vctObjects = g->getMap()->getObjects();
1158 vector<WorldMap::Object>::iterator itObjects;
1159 cout << "sending items" << endl;
1160 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
1161 itObjects->serialize(serverMsg.buffer);
1162 cout << "sending item id " << itObjects->id << endl;
1163 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1164 error("sendMessage");
1165 }
1166
1167
1168 // send the current score
1169 serverMsg.type = MSG_TYPE_SCORE;
1170
1171 int game_blueScore = g->getBlueScore();
1172 int game_redScore = g->getRedScore();
1173 memcpy(serverMsg.buffer, &game_blueScore, 4);
1174 memcpy(serverMsg.buffer+4, &game_redScore, 4);
1175
1176 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1177 error("sendMessage");
1178
1179 serverMsg.type = MSG_TYPE_PLAYER_JOIN_GAME;
1180 p->serialize(serverMsg.buffer);
1181 cout << "Should be broadcasting the message" << endl;
1182
1183 map<unsigned int, Player*>& otherPlayers = g->getPlayers();
1184 map<unsigned int, Player*>::iterator it;
1185 for (it = otherPlayers.begin(); it != otherPlayers.end(); it++)
1186 {
1187 cout << "Sent message back to " << it->second->name << endl;
1188 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
1189 error("sendMessage");
1190 }
1191
1192 g->addPlayer(p);
1193
1194 map<unsigned int, Player*>& allPlayers = g->getPlayers();
1195
1196 // tell the new player about all the players in the game (including himself)
1197 cout << "Sending other players to new player" << endl;
1198 serverMsg.type = MSG_TYPE_PLAYER_JOIN_GAME;
1199
1200 for (it = allPlayers.begin(); it != allPlayers.end(); it++)
1201 {
1202 it->second->serialize(serverMsg.buffer);
1203
1204 cout << "sending info about " << it->second->name << endl;
1205 cout << "sending id " << it->second->id << endl;
1206 if ( msgProcessor.sendMessage(&serverMsg, sock, &from, &outputLog) < 0 )
1207 error("sendMessage");
1208 }
1209
1210 int numPlayers = g->getNumPlayers();
1211
1212 serverMsg.type = MSG_TYPE_GAME_INFO;
1213 memcpy(serverMsg.buffer, &numPlayers, 4);
1214 strcpy(serverMsg.buffer+4, gameName.c_str());
1215 broadcastResponse = true;
1216
1217 break;
1218 }
1219 default:
1220 {
1221 serverMsg.type = MSG_TYPE_CHAT;
1222 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
1223
1224 break;
1225 }
1226 }
1227
1228 return broadcastResponse;
1229}
1230
1231void updateUnusedPlayerId(unsigned int& id, map<unsigned int, Player*>& mapPlayers)
1232{
1233 while (mapPlayers.find(id) != mapPlayers.end())
1234 id++;
1235}
1236
1237Player *findPlayerByName(map<unsigned int, Player*> &m, string name)
1238{
1239 map<unsigned int, Player*>::iterator it;
1240
1241 for (it = m.begin(); it != m.end(); it++)
1242 {
1243 if ( it->second->name.compare(name) == 0 )
1244 return it->second;
1245 }
1246
1247 return NULL;
1248}
1249
1250Player *findPlayerByAddr(map<unsigned int, Player*> &m, const sockaddr_in &addr)
1251{
1252 map<unsigned int, Player*>::iterator it;
1253
1254 for (it = m.begin(); it != m.end(); it++)
1255 {
1256 if ( it->second->addr.sin_addr.s_addr == addr.sin_addr.s_addr &&
1257 it->second->addr.sin_port == addr.sin_port )
1258 return it->second;
1259 }
1260
1261 return NULL;
1262}
1263
1264void damagePlayer(Player *p, int damage) {
1265 p->health -= damage;
1266 if (p->health < 0)
1267 p->health = 0;
1268 if (p->health == 0) {
1269 cout << "Player died" << endl;
1270 p->isDead = true;
1271 p->timeDied = getCurrentMillis();
1272 }
1273}
1274
1275void addObjectToMap(WorldMap::ObjectType objectType, int x, int y, WorldMap* gameMap, map<unsigned int, Player*>& mapPlayers, MessageProcessor &msgProcessor, int sock, ofstream& outputLog) {
1276 NETWORK_MSG serverMsg;
1277
1278 gameMap->addObject(objectType, x, y);
1279
1280 // need to send the OBJECT message too
1281 serverMsg.type = MSG_TYPE_OBJECT;
1282 gameMap->getObjects()->back().serialize(serverMsg.buffer);
1283
1284 map<unsigned int, Player*>::iterator it;
1285 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
1286 {
1287 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second->addr), &outputLog) < 0 )
1288 error("sendMessage");
1289 }
1290}
Note: See TracBrowser for help on using the repository browser.