source: network-game/server/server.cpp@ 9a4fa04

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

Debugging

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