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

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

Removed global score variables from server

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