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

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

Remove the Message.h include from several files

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