source: network-game/server/server.cpp@ 99afbb8

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

The server keeps track of games and adds players to them

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