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

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

Upon player registration, the server stores the selected player class and no longer generates a random player class every time the player logs in

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