source: network-game/server/server.cpp@ 10f6fc2

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

Moved server message sending/receiving into MessageProcessor

  • 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.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, 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 << "Received message" << endl;
521 cout << "MSG: type: " << clientMsg.type << endl;
522 cout << "MSG contents: " << clientMsg.buffer << endl;
523
524 // maybe we should make a message class and have this be a member
525 bool broadcastResponse = false;
526
527 // Check that if an invalid message is sent, the client will correctly
528 // receive and display the response. Maybe make a special error msg type
529 switch(clientMsg.type)
530 {
531 case MSG_TYPE_REGISTER:
532 {
533 string username(clientMsg.buffer);
534 string password(strchr(clientMsg.buffer, '\0')+1);
535 Player::PlayerClass playerClass;
536
537 memcpy(&playerClass, clientMsg.buffer+username.length()+password.length()+2, 4);
538
539 cout << "username: " << username << endl;
540 cout << "password: " << password << endl;
541
542 if (playerClass == Player::CLASS_WARRIOR)
543 cout << "class: WARRIOR" << endl;
544 else if (playerClass == Player::CLASS_RANGER)
545 cout << "class: RANGER" << endl;
546 else
547 cout << "Unknown player class detected" << endl;
548
549 int error = da.insertPlayer(username, password, playerClass);
550
551 if (!error)
552 strcpy(serverMsg.buffer, "Registration successful.");
553 else
554 strcpy(serverMsg.buffer, "Registration failed. Please try again.");
555
556 serverMsg.type = MSG_TYPE_REGISTER;
557
558 break;
559 }
560 case MSG_TYPE_LOGIN:
561 {
562 cout << "Got login message" << endl;
563
564 serverMsg.type = MSG_TYPE_LOGIN;
565
566 string username(clientMsg.buffer);
567 string password(strchr(clientMsg.buffer, '\0')+1);
568
569 Player* p = da.getPlayer(username);
570
571 if (p == NULL || !da.verifyPassword(password, p->password))
572 {
573 strcpy(serverMsg.buffer, "Incorrect username or password");
574 }
575 else if(findPlayerByName(mapPlayers, username) != NULL)
576 {
577 strcpy(serverMsg.buffer, "Player has already logged in.");
578 }
579 else
580 {
581 serverMsg.type = MSG_TYPE_PLAYER;
582
583 updateUnusedPlayerId(unusedPlayerId, mapPlayers);
584 p->id = unusedPlayerId;
585 cout << "new player id: " << p->id << endl;
586 p->setAddr(from);
587
588 // choose a random team (either 0 or 1)
589 p->team = rand() % 2;
590
591 // tell the new player about all the existing players
592 cout << "Sending other players to new player" << endl;
593
594 map<unsigned int, Player>::iterator it;
595 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
596 {
597 it->second.serialize(serverMsg.buffer);
598
599 cout << "sending info about " << it->second.name << endl;
600 cout << "sending id " << it->second.id << endl;
601 if ( msgProcessor.sendMessage(&serverMsg, sock, &from) < 0 )
602 error("sendMessage");
603 }
604
605 // tell the new player about all map objects
606 // (currently just the flags)
607 serverMsg.type = MSG_TYPE_OBJECT;
608 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
609 vector<WorldMap::Object>::iterator itObjects;
610 cout << "sending items" << endl;
611 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end(); itObjects++) {
612 itObjects->serialize(serverMsg.buffer);
613 cout << "sending item id " << itObjects->id << endl;
614 if ( msgProcessor.sendMessage(&serverMsg, sock, &from) < 0 )
615 error("sendMessage");
616 }
617
618 // send the current score
619 serverMsg.type = MSG_TYPE_SCORE;
620 memcpy(serverMsg.buffer, &scoreBlue, 4);
621 memcpy(serverMsg.buffer+4, &scoreRed, 4);
622 if ( msgProcessor.sendMessage(&serverMsg, sock, &from) < 0 )
623 error("sendMessage");
624
625 serverMsg.type = MSG_TYPE_PLAYER;
626 p->serialize(serverMsg.buffer);
627 cout << "Should be broadcasting the message" << endl;
628
629 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
630 {
631 cout << "Sent message back to " << it->second.name << endl;
632 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
633 error("sendMessage");
634 }
635
636 serverMsg.type = MSG_TYPE_LOGIN;
637 mapPlayers[unusedPlayerId] = *p;
638 }
639
640 delete(p);
641
642 break;
643 }
644 case MSG_TYPE_LOGOUT:
645 {
646 string name(clientMsg.buffer);
647 cout << "Player logging out: " << name << endl;
648
649 Player *p = findPlayerByName(mapPlayers, name);
650
651 if (p == NULL)
652 {
653 strcpy(serverMsg.buffer, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
654 cout << "Player not logged in" << endl;
655 }
656 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
657 p->addr.sin_port != from.sin_port )
658 {
659 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.");
660 cout << "Player logged in using a different connection" << endl;
661 }
662 else
663 {
664 if (p->id < unusedPlayerId)
665 unusedPlayerId = p->id;
666 mapPlayers.erase(p->id);
667 strcpy(serverMsg.buffer, "You have successfully logged out.");
668 }
669
670 serverMsg.type = MSG_TYPE_LOGOUT;
671
672 break;
673 }
674 case MSG_TYPE_CHAT:
675 {
676 cout << "Got a chat message" << endl;
677
678 Player *p = findPlayerByAddr(mapPlayers, from);
679
680 if (p == NULL)
681 {
682 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
683 }
684 else
685 {
686 broadcastResponse = true;
687
688 ostringstream oss;
689 oss << p->name << ": " << clientMsg.buffer;
690
691 strcpy(serverMsg.buffer, oss.str().c_str());
692 }
693
694 serverMsg.type = MSG_TYPE_CHAT;
695
696 break;
697 }
698 case MSG_TYPE_PLAYER_MOVE:
699 {
700 cout << "PLAYER_MOVE" << endl;
701
702 int id, x, y;
703
704 memcpy(&id, clientMsg.buffer, 4);
705 memcpy(&x, clientMsg.buffer+4, 4);
706 memcpy(&y, clientMsg.buffer+8, 4);
707
708 cout << "x: " << x << endl;
709 cout << "y: " << y << endl;
710 cout << "id: " << id << endl;
711
712 if ( mapPlayers[id].addr.sin_addr.s_addr == from.sin_addr.s_addr &&
713 mapPlayers[id].addr.sin_port == from.sin_port )
714 {
715 // we need to make sure the player can move here
716 if (0 <= x && x < gameMap->width*25 && 0 <= y && y < gameMap->height*25 &&
717 gameMap->getElement(x/25, y/25) == WorldMap::TERRAIN_GRASS)
718 {
719 cout << "valid terrain" << endl;
720
721 mapPlayers[id].target.x = x;
722 mapPlayers[id].target.y = y;
723
724 mapPlayers[id].isChasing = false;
725 mapPlayers[id].isAttacking = false;
726
727 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
728
729 memcpy(serverMsg.buffer, &id, 4);
730 memcpy(serverMsg.buffer+4, &mapPlayers[id].target.x, 4);
731 memcpy(serverMsg.buffer+8, &mapPlayers[id].target.y, 4);
732
733 broadcastResponse = true;
734 }
735 else
736 cout << "Bad terrain detected" << endl;
737 }
738 else // nned to send back a message indicating failure
739 cout << "Player id (" << id << ") doesn't match sender" << endl;
740
741 break;
742 }
743 case MSG_TYPE_PICKUP_FLAG:
744 {
745 // may want to check the id matches the sender, just like for PLAYER_NOVE
746 cout << "PICKUP_FLAG" << endl;
747
748 int id;
749
750 memcpy(&id, clientMsg.buffer, 4);
751 cout << "id: " << id << endl;
752
753 vector<WorldMap::Object>* vctObjects = gameMap->getObjects();
754 vector<WorldMap::Object>::iterator itObjects;
755
756 for (itObjects = vctObjects->begin(); itObjects != vctObjects->end();) {
757 POSITION pos = itObjects->pos;
758 bool gotFlag = false;
759
760 if (posDistance(mapPlayers[id].pos, pos.toFloat()) < 10) {
761 switch (itObjects->type) {
762 case WorldMap::OBJECT_BLUE_FLAG:
763 if (mapPlayers[id].team == 1) {
764 gotFlag = true;
765 mapPlayers[id].hasBlueFlag = true;
766 broadcastResponse = true;
767 }
768 break;
769 case WorldMap::OBJECT_RED_FLAG:
770 if (mapPlayers[id].team == 0) {
771 gotFlag = true;
772 mapPlayers[id].hasRedFlag = true;
773 broadcastResponse = true;
774 }
775 break;
776 }
777
778 if (gotFlag) {
779 serverMsg.type = MSG_TYPE_REMOVE_OBJECT;
780 memcpy(serverMsg.buffer, &itObjects->id, 4);
781
782 map<unsigned int, Player>::iterator it;
783 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
784 {
785 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
786 error("sendMessage");
787 }
788
789 // remove the object from the server-side map
790 cout << "size before: " << gameMap->getObjects()->size() << endl;
791 itObjects = vctObjects->erase(itObjects);
792 cout << "size after: " << gameMap->getObjects()->size() << endl;
793 }
794 }
795
796 if (!gotFlag)
797 itObjects++;
798 }
799
800 serverMsg.type = MSG_TYPE_PLAYER;
801 mapPlayers[id].serialize(serverMsg.buffer);
802
803 break;
804 }
805 case MSG_TYPE_DROP_FLAG:
806 {
807 // may want to check the id matches the sender, just like for PLAYER_NOVE
808 cout << "DROP_FLAG" << endl;
809
810 int id;
811
812 memcpy(&id, clientMsg.buffer, 4);
813 cout << "id: " << id << endl;
814
815 WorldMap::ObjectType flagType = WorldMap::OBJECT_NONE;
816 if (mapPlayers[id].hasBlueFlag)
817 flagType = WorldMap::OBJECT_BLUE_FLAG;
818 else if (mapPlayers[id].hasRedFlag)
819 flagType = WorldMap::OBJECT_RED_FLAG;
820
821 gameMap->addObject(flagType, mapPlayers[id].pos.x, mapPlayers[id].pos.y);
822
823 // need to send the OBJECT message too
824 serverMsg.type = MSG_TYPE_OBJECT;
825 gameMap->getObjects()->back().serialize(serverMsg.buffer);
826
827 map<unsigned int, Player>::iterator it;
828 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
829 {
830 if ( msgProcessor.sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
831 error("sendMessage");
832 }
833
834 mapPlayers[id].hasBlueFlag = false;
835 mapPlayers[id].hasRedFlag = false;
836
837 serverMsg.type = MSG_TYPE_PLAYER;
838 mapPlayers[id].serialize(serverMsg.buffer);
839
840 broadcastResponse = true;
841
842 break;
843 }
844 case MSG_TYPE_START_ATTACK:
845 {
846 cout << "Received a START_ATTACK message" << endl;
847
848 int id, targetId;
849
850 memcpy(&id, clientMsg.buffer, 4);
851 memcpy(&targetId, clientMsg.buffer+4, 4);
852
853 Player* source = &mapPlayers[id];
854 source->targetPlayer = targetId;
855 source->isChasing = true;
856
857 // this is irrelevant since the client doesn't even listen for START_ATTACK messages
858 // actually, the client should not ignore this and should instead perform the same movement
859 // algorithm on its end (following the target player until in range) that the server does.
860 // Once the attacker is in range, the client should stop movement and wait for messages
861 // from the server
862 serverMsg.type = MSG_TYPE_START_ATTACK;
863 memcpy(serverMsg.buffer, &id, 4);
864 memcpy(serverMsg.buffer+4, &targetId, 4);
865 broadcastResponse = true;
866
867 break;
868 }
869 case MSG_TYPE_ATTACK:
870 {
871 cout << "Received am ATTACK message" << endl;
872 cout << "ERROR: Clients should not send ATTACK messages" << endl;
873
874 break;
875 }
876 default:
877 {
878 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
879
880 serverMsg.type = MSG_TYPE_CHAT;
881
882 break;
883 }
884 }
885
886 return broadcastResponse;
887}
888
889void updateUnusedPlayerId(unsigned int& id, map<unsigned int, Player>& mapPlayers)
890{
891 while (mapPlayers.find(id) != mapPlayers.end())
892 id++;
893}
894
895void updateUnusedProjectileId(unsigned int& id, map<unsigned int, Projectile>& mapProjectiles)
896{
897 while (mapProjectiles.find(id) != mapProjectiles.end())
898 id++;
899}
900
901void damagePlayer(Player *p, int damage) {
902 p->health -= damage;
903 if (p->health < 0)
904 p->health = 0;
905 if (p->health == 0) {
906 cout << "Player died" << endl;
907 p->isDead = true;
908 p->timeDied = getCurrentMillis();
909 }
910}
Note: See TracBrowser for help on using the repository browser.