source: network-game/server/server.cpp@ 64d22ac

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

MessageProcessor handles receiving multiple ACKs for the same message

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