source: network-game/server/server.cpp@ 426fb84

Last change on this file since 426fb84 was 426fb84, checked in by Dmitry Portnoy <dmp1488@…>, 10 years ago

Save the actual time a game ends to the databse and send it to the client as part of a player's game history

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