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

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

The Game class now has a WorldMap. When a client creates or joins a game, the server sends out all the basic game info (the map and info about all players in the game)

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