source: network-game/server/server.cpp@ 66c4ec4

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

Restore the player's health and move him next to his base when he respawns

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