source: network-game/server/server.cpp@ 6c9bcdd

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

The server checks player movement in individual games and stops players who hit obstacles

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