source: network-game/server/server.cpp@ 6054f1e

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

Moved damagePlayer to the Player class

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