source: network-game/client/Client/main.cpp@ ffadc8e

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

The old game screen is no longer accessible by clicking anywhere on the lobby screen

  • Property mode set to 100644
File size: 38.7 KB
Line 
1#include "../../common/Compiler.h"
2
3#if defined WINDOWS
4 #include <winsock2.h>
5 #include <ws2tcpip.h>
6#elif defined LINUX
7 #include <sys/types.h>
8 #include <unistd.h>
9 #include <sys/socket.h>
10 #include <netinet/in.h>
11 #include <netdb.h>
12 #include <cstring>
13#endif
14
15#include <cstdio>
16#include <cstdlib>
17#include <cmath>
18#include <sys/types.h>
19#include <string>
20#include <iostream>
21#include <sstream>
22#include <fstream>
23#include <map>
24
25#include <allegro5/allegro.h>
26#include <allegro5/allegro_font.h>
27#include <allegro5/allegro_ttf.h>
28#include <allegro5/allegro_primitives.h>
29
30#include "../../common/Common.h"
31#include "../../common/MessageContainer.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
38#include "Window.h"
39#include "TextLabel.h"
40#include "Button.h"
41#include "Textbox.h"
42#include "RadioButtonList.h"
43
44#include "GameRender.h"
45
46#include "chat.h"
47
48#ifdef WINDOWS
49 #pragma comment(lib, "ws2_32.lib")
50#endif
51
52using namespace std;
53
54void initWinSock();
55void shutdownWinSock();
56void processMessage(NETWORK_MSG &msg, int &state, chat &chatConsole, WorldMap *gameMap, map<unsigned int, Player*>& mapPlayers, map<unsigned int, Projectile>& mapProjectiles, unsigned int& curPlayerId, int &scoreBlue, int &scoreRed);
57int getRefreshRate(int width, int height);
58void drawMessageStatus(ALLEGRO_FONT* font);
59
60// Callback declarations
61void goToLoginScreen();
62void goToRegisterScreen();
63void registerAccount();
64void login();
65void logout();
66void quit();
67void sendChatMessage();
68void toggleDebugging();
69void joinGame();
70void createGame();
71void leaveGame();
72
73void error(const char *);
74
75const float FPS = 60;
76const int SCREEN_W = 1024;
77const int SCREEN_H = 768;
78
79enum STATE {
80 STATE_START,
81 STATE_LOBBY,
82 STATE_GAME,
83 STATE_NEW_GAME
84};
85
86int state;
87
88bool doexit;
89
90Window* wndLogin;
91Window* wndRegister;
92Window* wndLobby;
93Window* wndGame;
94Window* wndNewGame;
95Window* wndGameDebug;
96Window* wndCurrent;
97
98// wndLogin
99Textbox* txtUsername;
100Textbox* txtPassword;
101TextLabel* lblLoginStatus;
102
103// wndRegister
104Textbox* txtUsernameRegister;
105Textbox* txtPasswordRegister;
106RadioButtonList* rblClasses;
107TextLabel* lblRegisterStatus;
108
109// wndLobby
110Textbox* txtJoinGame;
111Textbox* txtCreateGame;
112
113// wndGame
114Textbox* txtChat;
115
116int sock;
117struct sockaddr_in server, from;
118struct hostent *hp;
119NETWORK_MSG msgTo, msgFrom;
120string username;
121chat chatConsole, debugConsole;
122bool debugging;
123map<string, int> mapGames;
124Game* game;
125
126MessageProcessor msgProcessor;
127ofstream outputLog;
128
129int main(int argc, char **argv)
130{
131 ALLEGRO_DISPLAY *display = NULL;
132 ALLEGRO_EVENT_QUEUE *event_queue = NULL;
133 ALLEGRO_TIMER *timer = NULL;
134 bool key[4] = { false, false, false, false };
135 map<unsigned int, Player*> mapPlayers;
136 map<unsigned int, Projectile> mapProjectiles;
137 unsigned int curPlayerId = -1;
138 int scoreBlue, scoreRed;
139
140 doexit = false;
141 debugging = false;
142 bool redraw = true;
143 bool fullscreen = false;
144 game = NULL;
145
146 scoreBlue = 0;
147 scoreRed = 0;
148
149 state = STATE_START;
150
151 if(!al_init()) {
152 fprintf(stderr, "failed to initialize allegro!\n");
153 return -1;
154 }
155
156 outputLog.open("client.log", ios::app);
157 outputLog << "Started client on " << getCurrentDateTimeString() << endl;
158
159 if (al_init_primitives_addon())
160 cout << "Primitives initialized" << endl;
161 else
162 cout << "Primitives not initialized" << endl;
163
164 al_init_font_addon();
165 al_init_ttf_addon();
166
167 #if defined WINDOWS
168 ALLEGRO_FONT *font = al_load_ttf_font("../pirulen.ttf", 12, 0);
169 #elif defined LINUX
170 ALLEGRO_FONT *font = al_load_ttf_font("pirulen.ttf", 12, 0);
171 #endif
172
173 if (!font) {
174 fprintf(stderr, "Could not load 'pirulen.ttf'.\n");
175 getchar();
176 return -1;
177 }
178
179 if(!al_install_keyboard()) {
180 fprintf(stderr, "failed to initialize the keyboard!\n");
181 return -1;
182 }
183
184 if(!al_install_mouse()) {
185 fprintf(stderr, "failed to initialize the mouse!\n");
186 return -1;
187 }
188
189 timer = al_create_timer(1.0 / FPS);
190 if(!timer) {
191 fprintf(stderr, "failed to create timer!\n");
192 return -1;
193 }
194
195 int refreshRate = getRefreshRate(SCREEN_W, SCREEN_H);
196 // if the computer doesn't support this resolution, just use windowed mode
197 if (refreshRate > 0 && fullscreen) {
198 al_set_new_display_flags(ALLEGRO_FULLSCREEN);
199 al_set_new_display_refresh_rate(refreshRate);
200 }
201 display = al_create_display(SCREEN_W, SCREEN_H);
202 if(!display) {
203 fprintf(stderr, "failed to create display!\n");
204 al_destroy_timer(timer);
205 return -1;
206 }
207
208 WorldMap* gameMap = WorldMap::loadMapFromFile("../../data/map.txt");
209
210 cout << "Loaded map" << endl;
211
212 debugConsole.addLine("Debug console:");
213 debugConsole.addLine("");
214
215 wndLogin = new Window(0, 0, SCREEN_W, SCREEN_H);
216 wndLogin->addComponent(new Textbox(516, 40, 100, 20, font));
217 wndLogin->addComponent(new Textbox(516, 70, 100, 20, font));
218 wndLogin->addComponent(new TextLabel(410, 40, 100, 20, font, "Username:", ALLEGRO_ALIGN_RIGHT));
219 wndLogin->addComponent(new TextLabel(410, 70, 100, 20, font, "Password:", ALLEGRO_ALIGN_RIGHT));
220 wndLogin->addComponent(new TextLabel((SCREEN_W-600)/2, 100, 600, 20, font, "", ALLEGRO_ALIGN_CENTRE));
221 wndLogin->addComponent(new Button(SCREEN_W/2-100, 130, 90, 20, font, "Register", goToRegisterScreen));
222 wndLogin->addComponent(new Button(SCREEN_W/2+10, 130, 90, 20, font, "Login", login));
223 wndLogin->addComponent(new Button(920, 10, 80, 20, font, "Quit", quit));
224 wndLogin->addComponent(new Button(20, 10, 160, 20, font, "Toggle Debugging", toggleDebugging));
225
226 txtUsername = (Textbox*)wndLogin->getComponent(0);
227 txtPassword = (Textbox*)wndLogin->getComponent(1);
228 lblLoginStatus = (TextLabel*)wndLogin->getComponent(4);
229
230 cout << "Created login screen" << endl;
231
232 wndRegister = new Window(0, 0, SCREEN_W, SCREEN_H);
233 wndRegister->addComponent(new Textbox(516, 40, 100, 20, font));
234 wndRegister->addComponent(new Textbox(516, 70, 100, 20, font));
235 wndRegister->addComponent(new TextLabel(410, 40, 100, 20, font, "Username:", ALLEGRO_ALIGN_RIGHT));
236 wndRegister->addComponent(new TextLabel(410, 70, 100, 20, font, "Password:", ALLEGRO_ALIGN_RIGHT));
237 wndRegister->addComponent(new RadioButtonList(432, 100, "Pick a class", font));
238 wndRegister->addComponent(new TextLabel((SCREEN_W-600)/2, 190, 600, 20, font, "", ALLEGRO_ALIGN_CENTRE));
239 wndRegister->addComponent(new Button(SCREEN_W/2-100, 220, 90, 20, font, "Back", goToLoginScreen));
240 wndRegister->addComponent(new Button(SCREEN_W/2+10, 220, 90, 20, font, "Submit", registerAccount));
241 wndRegister->addComponent(new Button(920, 10, 80, 20, font, "Quit", quit));
242 wndRegister->addComponent(new Button(20, 10, 160, 20, font, "Toggle Debugging", toggleDebugging));
243
244 txtUsernameRegister = (Textbox*)wndRegister->getComponent(0);
245 txtPasswordRegister = (Textbox*)wndRegister->getComponent(1);
246
247 rblClasses = (RadioButtonList*)wndRegister->getComponent(4);
248 rblClasses->addRadioButton("Warrior");
249 rblClasses->addRadioButton("Ranger");
250
251 lblRegisterStatus = (TextLabel*)wndRegister->getComponent(5);
252
253 cout << "Created register screen" << endl;
254
255 wndLobby = new Window(0, 0, SCREEN_W, SCREEN_H);
256 wndLobby->addComponent(new Button(920, 10, 80, 20, font, "Logout", logout));
257 wndLobby->addComponent(new TextLabel(SCREEN_W*1/2+15-112, 40, 110, 20, font, "Game Name:", ALLEGRO_ALIGN_RIGHT));
258 wndLobby->addComponent(new Textbox(SCREEN_W*1/2+15+4, 40, 100, 20, font));
259 wndLobby->addComponent(new Button(SCREEN_W*1/2+15-100, 80, 200, 20, font, "Join Existing Game", joinGame));
260 wndLobby->addComponent(new TextLabel(SCREEN_W*3/4-112, 40, 110, 20, font, "Game Name:", ALLEGRO_ALIGN_RIGHT));
261 wndLobby->addComponent(new Textbox(SCREEN_W*3/4+4, 40, 100, 20, font));
262 wndLobby->addComponent(new Button(SCREEN_W*3/4-100, 80, 200, 20, font, "Create New Game", createGame));
263 wndLobby->addComponent(new Textbox(95, 40, 300, 20, font));
264 wndLobby->addComponent(new Button(95, 70, 60, 20, font, "Send", sendChatMessage));
265
266 txtJoinGame = (Textbox*)wndLobby->getComponent(2);
267 txtCreateGame = (Textbox*)wndLobby->getComponent(5);
268 txtChat = (Textbox*)wndLobby->getComponent(7);
269
270 cout << "Created lobby screen" << endl;
271
272 // this is the old game screen
273 wndGame = new Window(0, 0, SCREEN_W, SCREEN_H);
274 wndGame->addComponent(new Textbox(95, 40, 300, 20, font));
275 wndGame->addComponent(new Button(95, 70, 60, 20, font, "Send", sendChatMessage));
276 wndGame->addComponent(new Button(20, 10, 160, 20, font, "Toggle Debugging", toggleDebugging));
277 wndGame->addComponent(new Button(920, 10, 80, 20, font, "Logout", logout));
278
279 wndGameDebug = new Window(0, 0, SCREEN_W, SCREEN_H);
280 wndGameDebug->addComponent(new Button(20, 10, 160, 20, font, "Toggle Debugging", toggleDebugging));
281 wndGameDebug->addComponent(new Button(920, 10, 80, 20, font, "Logout", logout));
282
283 cout << "Created game screen" << endl;
284
285 // this is the new game screen, without a debug console
286 wndNewGame = new Window(0, 0, SCREEN_W, SCREEN_H);
287 wndNewGame->addComponent(new Button(880, 10, 120, 20, font, "Leave Game", leaveGame));
288
289 cout << "Created new game screen" << endl;
290
291 goToLoginScreen();
292
293 event_queue = al_create_event_queue();
294 if(!event_queue) {
295 fprintf(stderr, "failed to create event_queue!\n");
296 al_destroy_display(display);
297 al_destroy_timer(timer);
298 return -1;
299 }
300
301 al_set_target_bitmap(al_get_backbuffer(display));
302
303 al_register_event_source(event_queue, al_get_display_event_source(display));
304 al_register_event_source(event_queue, al_get_timer_event_source(timer));
305 al_register_event_source(event_queue, al_get_keyboard_event_source());
306 al_register_event_source(event_queue, al_get_mouse_event_source());
307
308 al_clear_to_color(al_map_rgb(0,0,0));
309
310 al_flip_display();
311
312 if (argc != 3) {
313 cout << "Usage: server port" << endl;
314 exit(1);
315 }
316
317 initWinSock();
318
319 sock = socket(AF_INET, SOCK_DGRAM, 0);
320 if (sock < 0)
321 error("socket");
322
323 set_nonblock(sock);
324
325 server.sin_family = AF_INET;
326 hp = gethostbyname(argv[1]);
327 if (hp==0)
328 error("Unknown host");
329
330 memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);
331 server.sin_port = htons(atoi(argv[2]));
332
333 al_start_timer(timer);
334
335 while(!doexit)
336 {
337 ALLEGRO_EVENT ev;
338
339 al_wait_for_event(event_queue, &ev);
340
341 if(wndCurrent->handleEvent(ev)) {
342 // do nothing
343 }
344 else if(ev.type == ALLEGRO_EVENT_TIMER) {
345 redraw = true; // seems like we should just call a draw function here instead
346 }
347 else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
348 doexit = true;
349 }
350 else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
351 }
352 else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
353 switch(ev.keyboard.keycode) {
354 case ALLEGRO_KEY_ESCAPE:
355 doexit = true;
356 break;
357 case ALLEGRO_KEY_S: // pickup an item next to you
358 if (state == STATE_GAME || state == STATE_NEW_GAME) {
359 msgTo.type = MSG_TYPE_PICKUP_FLAG;
360 memcpy(msgTo.buffer, &curPlayerId, 4);
361 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
362 }
363 break;
364 case ALLEGRO_KEY_D: // drop the current item
365 if (state == STATE_GAME || state == STATE_NEW_GAME) {
366 Player* p = NULL;
367 try {
368 p = mapPlayers.at(curPlayerId);
369 } catch (const out_of_range& ex) {}
370
371 if (p != NULL) {
372 int flagType = WorldMap::OBJECT_NONE;
373
374 if (p->hasBlueFlag)
375 flagType = WorldMap::OBJECT_BLUE_FLAG;
376 else if (p->hasRedFlag)
377 flagType = WorldMap::OBJECT_RED_FLAG;
378
379 if (flagType != WorldMap::OBJECT_NONE) {
380 msgTo.type = MSG_TYPE_DROP_FLAG;
381 memcpy(msgTo.buffer, &curPlayerId, 4);
382 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
383 }
384 }
385 }
386 break;
387 }
388 }
389 else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
390 if(wndCurrent == wndLobby) {
391 /*
392 if (ev.mouse.button == 1) { // left click
393 txtJoinGame->clear();
394 txtCreateGame->clear();
395 state = STATE_GAME;
396 wndCurrent = wndGame;
397 }
398 */
399 }else if(wndCurrent == wndGame || wndCurrent == wndNewGame) {
400 if (ev.mouse.button == 1) { // left click
401 msgTo.type = MSG_TYPE_PLAYER_MOVE;
402
403 POSITION pos;
404 pos.x = ev.mouse.x;
405 pos.y = ev.mouse.y;
406 pos = screenToMap(pos);
407
408 if (pos.x != -1)
409 {
410 memcpy(msgTo.buffer, &curPlayerId, 4);
411 memcpy(msgTo.buffer+4, &pos.x, 4);
412 memcpy(msgTo.buffer+8, &pos.y, 4);
413
414 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
415 }
416 else
417 cout << "Invalid point: User did not click on the map" << endl;
418 }else if (ev.mouse.button == 2) { // right click
419 map<unsigned int, Player*>::iterator it;
420
421 cout << "Detected a right-click" << endl;
422
423 Player* curPlayer;
424 for(it = mapPlayers.begin(); it != mapPlayers.end(); it++)
425 {
426 if (it->second->id == curPlayerId)
427 curPlayer = it->second;
428 }
429
430 Player* target;
431 for(it = mapPlayers.begin(); it != mapPlayers.end(); it++)
432 {
433 // need to check if the right-click was actually on this player
434 // right now, this code will target all players other than the current one
435 target = it->second;
436 if (target->id != curPlayerId && target->team != curPlayer->team)
437 {
438 msgTo.type = MSG_TYPE_START_ATTACK;
439 memcpy(msgTo.buffer, &curPlayerId, 4);
440 memcpy(msgTo.buffer+4, &target->id, 4);
441
442 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
443 }
444 }
445 }
446 }
447 }
448
449 if (msgProcessor.receiveMessage(&msgFrom, sock, &from, &outputLog) >= 0)
450 processMessage(msgFrom, state, chatConsole, gameMap, mapPlayers, mapProjectiles, curPlayerId, scoreBlue, scoreRed);
451
452 if (redraw)
453 {
454 redraw = false;
455
456 msgProcessor.resendUnackedMessages(sock, &outputLog);
457 //msgProcessor.cleanAckedMessages(&outputLog);
458
459 if (debugging && wndCurrent == wndGame)
460 wndGameDebug->draw(display);
461 else
462 wndCurrent->draw(display);
463
464 if (wndCurrent == wndLobby) {
465 chatConsole.draw(font, al_map_rgb(255,255,255));
466
467 map<string, int>::iterator it;
468 int i=0;
469 ostringstream ossGame;
470 for (it = mapGames.begin(); it != mapGames.end(); it++) {
471 ossGame << it->first << " (" << it->second << " players)" << endl;
472 al_draw_text(font, al_map_rgb(0, 255, 0), SCREEN_W*1/2-100, 120+i*15, ALLEGRO_ALIGN_LEFT, ossGame.str().c_str());
473 ossGame.clear();
474 ossGame.str("");
475 i++;
476 }
477 }
478 else if (wndCurrent == wndNewGame)
479 {
480 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 4, ALLEGRO_ALIGN_LEFT, "Players");
481
482 map<unsigned int, Player*>& gamePlayers = game->getPlayers();
483 map<unsigned int, Player*>::iterator it;
484
485 int playerCount = 0;
486 for (it = gamePlayers.begin(); it != gamePlayers.end(); it++)
487 {
488 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 19+(playerCount+1)*15, ALLEGRO_ALIGN_LEFT, it->second->name.c_str());
489 playerCount++;
490 }
491
492 ostringstream ossScoreBlue, ossScoreRed;
493
494 ossScoreBlue << "Blue: " << game->getBlueScore() << endl;
495 ossScoreRed << "Red: " << game->getRedScore() << endl;
496
497 al_draw_text(font, al_map_rgb(0, 255, 0), 330, 80, ALLEGRO_ALIGN_LEFT, ossScoreBlue.str().c_str());
498 al_draw_text(font, al_map_rgb(0, 255, 0), 515, 80, ALLEGRO_ALIGN_LEFT, ossScoreRed.str().c_str());
499
500 // update players
501 for (it = game->getPlayers().begin(); it != game->getPlayers().end(); it++)
502 {
503 it->second->updateTarget(game->getPlayers());
504 }
505
506 for (it = game->getPlayers().begin(); it != game->getPlayers().end(); it++)
507 {
508 it->second->move(game->getMap()); // ignore return value
509 }
510
511 GameRender::drawMap(game->getMap());
512 GameRender::drawPlayers(game->getPlayers(), font, curPlayerId);
513 }
514 else if (wndCurrent == wndGame)
515 {
516 if (!debugging)
517 chatConsole.draw(font, al_map_rgb(255,255,255));
518
519 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 43, ALLEGRO_ALIGN_LEFT, "Message:");
520
521 ostringstream ossScoreBlue, ossScoreRed;
522
523 ossScoreBlue << "Blue: " << scoreBlue << endl;
524 ossScoreRed << "Red: " << scoreRed << endl;
525
526 al_draw_text(font, al_map_rgb(0, 255, 0), 330, 80, ALLEGRO_ALIGN_LEFT, ossScoreBlue.str().c_str());
527 al_draw_text(font, al_map_rgb(0, 255, 0), 515, 80, ALLEGRO_ALIGN_LEFT, ossScoreRed.str().c_str());
528
529 // update players
530 map<unsigned int, Player*>::iterator it;
531 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
532 {
533 it->second->updateTarget(mapPlayers);
534 }
535
536 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
537 {
538 it->second->move(gameMap); // ignore return value
539 }
540
541 // update projectile positions
542 map<unsigned int, Projectile>::iterator it2;
543 for (it2 = mapProjectiles.begin(); it2 != mapProjectiles.end(); it2++)
544 {
545 it2->second.move(mapPlayers);
546 }
547
548 GameRender::drawMap(gameMap);
549 GameRender::drawPlayers(mapPlayers, font, curPlayerId);
550
551 // draw projectiles
552 for (it2 = mapProjectiles.begin(); it2 != mapProjectiles.end(); it2++)
553 {
554 Projectile proj = it2->second;
555
556 FLOAT_POSITION target = mapPlayers[proj.target]->pos;
557 float angle = atan2(target.y-proj.pos.toFloat().y, target.x-proj.pos.toFloat().x);
558
559 POSITION start, end;
560 start.x = cos(angle)*15+proj.pos.x;
561 start.y = sin(angle)*15+proj.pos.y;
562 end.x = proj.pos.x;
563 end.y = proj.pos.y;
564
565 start = mapToScreen(start);
566 end = mapToScreen(end);
567
568 al_draw_line(start.x, start.y, end.x, end.y, al_map_rgb(0, 0, 0), 4);
569 }
570 }
571
572 if (debugging) {
573 //debugConsole.draw(font, al_map_rgb(255,255,255));
574 drawMessageStatus(font);
575 }
576
577 al_flip_display();
578 }
579 }
580
581 #if defined WINDOWS
582 closesocket(sock);
583 #elif defined LINUX
584 close(sock);
585 #endif
586
587 shutdownWinSock();
588
589 delete wndLogin;
590 delete wndRegister;
591 delete wndLobby;
592 delete wndGame;
593 delete wndGameDebug;
594
595 delete gameMap;
596
597 if (game != NULL)
598 delete game;
599
600 map<unsigned int, Player*>::iterator it;
601
602 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++) {
603 delete it->second;
604 }
605
606 al_destroy_event_queue(event_queue);
607 al_destroy_display(display);
608 al_destroy_timer(timer);
609
610 outputLog << "Stopped client on " << getCurrentDateTimeString() << endl;
611 outputLog.close();
612
613 return 0;
614}
615
616
617
618// need to make a function like this that works on windows
619void error(const char *msg)
620{
621 perror(msg);
622 shutdownWinSock();
623 exit(1);
624}
625
626void initWinSock()
627{
628#if defined WINDOWS
629 WORD wVersionRequested;
630 WSADATA wsaData;
631 int wsaerr;
632
633 wVersionRequested = MAKEWORD(2, 2);
634 wsaerr = WSAStartup(wVersionRequested, &wsaData);
635
636 if (wsaerr != 0) {
637 cout << "The Winsock dll not found." << endl;
638 exit(1);
639 }else
640 cout << "The Winsock dll was found." << endl;
641#endif
642}
643
644void shutdownWinSock()
645{
646#if defined WINDOWS
647 WSACleanup();
648#endif
649}
650
651void processMessage(NETWORK_MSG &msg, int &state, chat &chatConsole, WorldMap *gameMap, map<unsigned int, Player*>& mapPlayers, map<unsigned int, Projectile>& mapProjectiles, unsigned int& curPlayerId, int &scoreBlue, int &scoreRed)
652{
653 // this is outdated since most messages now don't contain just a text string
654 string response = string(msg.buffer);
655
656 switch(state)
657 {
658 case STATE_START:
659 {
660 cout << "In STATE_START" << endl;
661
662 switch(msg.type)
663 {
664 case MSG_TYPE_REGISTER:
665 {
666 lblRegisterStatus->setText(response);
667 break;
668 }
669 default:
670 {
671 cout << "(STATE_REGISTER) Received invalid message of type " << msg.type << endl;
672 break;
673 }
674 }
675
676 break;
677 }
678 case STATE_LOBBY:
679 cout << "In STATE_LOBBY" << endl;
680 case STATE_GAME:
681 {
682 switch(msg.type)
683 {
684 case MSG_TYPE_LOGIN:
685 {
686 if (response.compare("Player has already logged in.") == 0)
687 {
688 goToLoginScreen();
689 state = STATE_START;
690
691 lblLoginStatus->setText(response);
692 }
693 else if (response.compare("Incorrect username or password") == 0)
694 {
695 goToLoginScreen();
696 state = STATE_START;
697
698 lblLoginStatus->setText(response);
699 }
700 else
701 {
702 wndCurrent = wndLobby;
703
704 // this message should only be sent when a player first logs in so they know their id
705
706 Player* p = new Player("", "");
707 p->deserialize(msg.buffer);
708
709 if (mapPlayers.find(p->id) != mapPlayers.end())
710 delete mapPlayers[p->id];
711 mapPlayers[p->id] = p;
712 curPlayerId = p->id;
713
714 cout << "Got a valid login response with the player" << endl;
715 cout << "Player id: " << curPlayerId << endl;
716 cout << "Player health: " << p->health << endl;
717 cout << "player map size: " << mapPlayers.size() << endl;
718 }
719
720 break;
721 }
722 case MSG_TYPE_LOGOUT:
723 {
724 cout << "Got a logout message" << endl;
725
726 int playerId;
727
728 // Check if it's about you or another player
729 memcpy(&playerId, msg.buffer, 4);
730 response = string(msg.buffer+4);
731
732 if (playerId == curPlayerId)
733 {
734 if (response.compare("You have successfully logged out.") == 0)
735 {
736 cout << "Logged out" << endl;
737 state = STATE_START;
738 goToLoginScreen();
739 }
740
741 // if there was an error logging out, nothing happens
742 }
743 else
744 {
745 delete mapPlayers[playerId];
746 }
747
748 break;
749 }
750 case MSG_TYPE_PLAYER:
751 {
752 cout << "Received MSG_TYPE_PLAYER" << endl;
753
754 Player p("", "");
755 p.deserialize(msg.buffer);
756 p.timeLastUpdated = getCurrentMillis();
757 p.isChasing = false;
758 if (p.health <= 0)
759 p.isDead = true;
760 else
761 p.isDead = false;
762
763 if (mapPlayers.find(p.id) != mapPlayers.end())
764 *(mapPlayers[p.id]) = p;
765 else
766 mapPlayers[p.id] = new Player(p);
767
768 break;
769 }
770 case MSG_TYPE_PLAYER_MOVE:
771 {
772 unsigned int id;
773 int x, y;
774
775 memcpy(&id, msg.buffer, 4);
776 memcpy(&x, msg.buffer+4, 4);
777 memcpy(&y, msg.buffer+8, 4);
778
779 mapPlayers[id]->target.x = x;
780 mapPlayers[id]->target.y = y;
781
782 break;
783 }
784 case MSG_TYPE_CHAT:
785 {
786 chatConsole.addLine(response);
787
788 break;
789 }
790 case MSG_TYPE_OBJECT:
791 {
792 cout << "Received OBJECT message" << endl;
793
794 WorldMap::Object o(0, WorldMap::OBJECT_NONE, 0, 0);
795 o.deserialize(msg.buffer);
796 cout << "object id: " << o.id << endl;
797 gameMap->updateObject(o.id, o.type, o.pos.x, o.pos.y);
798
799 break;
800 }
801 case MSG_TYPE_REMOVE_OBJECT:
802 {
803 cout << "Received REMOVE_OBJECT message!" << endl;
804
805 int id;
806 memcpy(&id, msg.buffer, 4);
807
808 cout << "Removing object with id " << id << endl;
809
810 if (!gameMap->removeObject(id))
811 cout << "Did not remove the object" << endl;
812
813 break;
814 }
815 case MSG_TYPE_SCORE:
816 {
817 memcpy(&scoreBlue, msg.buffer, 4);
818 memcpy(&scoreRed, msg.buffer+4, 4);
819
820 break;
821 }
822 case MSG_TYPE_ATTACK:
823 {
824 cout << "Received ATTACK message" << endl;
825
826 break;
827 }
828 case MSG_TYPE_START_ATTACK:
829 {
830 cout << "Received START_ATTACK message" << endl;
831
832 unsigned int id, targetID;
833 memcpy(&id, msg.buffer, 4);
834 memcpy(&targetID, msg.buffer+4, 4);
835
836 cout << "source id: " << id << endl;
837 cout << "target id: " << targetID << endl;
838
839 Player* source = mapPlayers[id];
840 source->targetPlayer = targetID;
841 source->isChasing = true;
842
843 break;
844 }
845 case MSG_TYPE_PROJECTILE:
846 {
847 cout << "Received a PROJECTILE message" << endl;
848
849 unsigned int id, x, y, targetId;
850
851 memcpy(&id, msg.buffer, 4);
852 memcpy(&x, msg.buffer+4, 4);
853 memcpy(&y, msg.buffer+8, 4);
854 memcpy(&targetId, msg.buffer+12, 4);
855
856 cout << "id: " << id << endl;
857 cout << "x: " << x << endl;
858 cout << "y: " << y << endl;
859 cout << "Target: " << targetId << endl;
860
861 Projectile proj(x, y, targetId, 0);
862 proj.setId(id);
863
864 mapProjectiles[id] = proj;
865
866 break;
867 }
868 case MSG_TYPE_REMOVE_PROJECTILE:
869 {
870 cout << "Received a REMOVE_PROJECTILE message" << endl;
871
872 int id;
873 memcpy(&id, msg.buffer, 4);
874
875 mapProjectiles.erase(id);
876
877 break;
878 }
879 case MSG_TYPE_GAME_INFO:
880 {
881 cout << "Received a GAME_INFO message" << endl;
882
883 string gameName(msg.buffer+4);
884 int numPlayers;
885
886 memcpy(&numPlayers, msg.buffer, 4);
887
888 cout << "Received game info for " << gameName << " (num players: " << numPlayers << ")" << endl;
889
890 if (numPlayers > 0)
891 mapGames[gameName] = numPlayers;
892 else
893 mapGames.erase(gameName);
894
895 break;
896 }
897 case MSG_TYPE_JOIN_GAME_SUCCESS:
898 {
899 cout << "Received a JOIN_GAME_SUCCESS message" << endl;
900
901 string gameName(msg.buffer);
902 game = new Game(gameName, "../../data/map.txt");
903 cout << "Game name: " << gameName << endl;
904
905 state = STATE_NEW_GAME;
906 wndCurrent = wndNewGame;
907
908 msgTo.type = MSG_TYPE_JOIN_GAME_ACK;
909 strcpy(msgTo.buffer, gameName.c_str());
910
911 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
912
913 break;
914 }
915 case MSG_TYPE_JOIN_GAME_FAILURE:
916 {
917 cout << "Received a JOIN_GAME_FAILURE message" << endl;
918
919 break;
920 }
921 default:
922 {
923 cout << "(STATE_LOBBY) Received invlaid message of type " << msg.type << endl;
924
925 break;
926 }
927 }
928
929 break;
930 }
931 case STATE_NEW_GAME:
932 {
933 cout << "(STATE_NEW_GAME) ";
934 switch(msg.type)
935 {
936 case MSG_TYPE_GAME_INFO:
937 {
938 cout << "Received a GAME_INFO message" << endl;
939
940 string gameName(msg.buffer+4);
941 int numPlayers;
942
943 memcpy(&numPlayers, msg.buffer, 4);
944
945 cout << "Received game info for " << gameName << " (num players: " << numPlayers << ")" << endl;
946
947 if (numPlayers > 0)
948 mapGames[gameName] = numPlayers;
949 else
950 mapGames.erase(gameName);
951
952 break;
953 }
954 case MSG_TYPE_PLAYER:
955 {
956 cout << "Received MSG_TYPE_PLAYER" << endl;
957
958 Player p("", "");
959 p.deserialize(msg.buffer);
960 p.timeLastUpdated = getCurrentMillis();
961 p.isChasing = false;
962 if (p.health <= 0)
963 p.isDead = true;
964 else
965 p.isDead = false;
966
967 if (mapPlayers.find(p.id) != mapPlayers.end())
968 *(mapPlayers[p.id]) = p;
969 else
970 mapPlayers[p.id] = new Player(p);
971
972 break;
973 }
974 case MSG_TYPE_PLAYER_JOIN_GAME:
975 {
976 cout << "Received MSG_TYPE_PLAYER_JOIN_GAME" << endl;
977
978 Player p("", "");
979 p.deserialize(msg.buffer);
980 p.timeLastUpdated = getCurrentMillis();
981 p.isChasing = false;
982 if (p.health <= 0)
983 p.isDead = true;
984 else
985 p.isDead = false;
986
987 if (mapPlayers.find(p.id) != mapPlayers.end())
988 *(mapPlayers[p.id]) = p;
989 else
990 mapPlayers[p.id] = new Player(p);
991
992 game->addPlayer(mapPlayers[p.id]);
993
994 break;
995 }
996 case MSG_TYPE_PLAYER_MOVE:
997 {
998 cout << "Received PLAYER_MOVE message" << endl;
999
1000 unsigned int id;
1001 int x, y;
1002
1003 memcpy(&id, msg.buffer, 4);
1004 memcpy(&x, msg.buffer+4, 4);
1005 memcpy(&y, msg.buffer+8, 4);
1006
1007 cout << "id: " << id << endl;
1008
1009 mapPlayers[id]->target.x = x;
1010 mapPlayers[id]->target.y = y;
1011
1012 break;
1013 }
1014 case MSG_TYPE_OBJECT:
1015 {
1016 cout << "Received object message in STATE_NEW_GAME" << endl;
1017
1018 WorldMap::Object o(0, WorldMap::OBJECT_NONE, 0, 0);
1019 o.deserialize(msg.buffer);
1020 cout << "object id: " << o.id << endl;
1021 game->getMap()->updateObject(o.id, o.type, o.pos.x, o.pos.y);
1022
1023 break;
1024 }
1025 case MSG_TYPE_REMOVE_OBJECT:
1026 {
1027 cout << "Received REMOVE_OBJECT message!" << endl;
1028
1029 int id;
1030 memcpy(&id, msg.buffer, 4);
1031
1032 cout << "Removing object with id " << id << endl;
1033
1034 if (!game->getMap()->removeObject(id))
1035 cout << "Did not remove the object" << endl;
1036
1037 break;
1038 }
1039 case MSG_TYPE_SCORE:
1040 {
1041 cout << "Received SCORE message!" << endl;
1042
1043 int blueScore;
1044 memcpy(&blueScore, msg.buffer, 4);
1045 cout << "blue score: " << blueScore << endl;
1046 game->setBlueScore(blueScore);
1047
1048 int redScore;
1049 memcpy(&redScore, msg.buffer+4, 4);
1050 cout << "red score: " << redScore << endl;
1051 game->setRedScore(redScore);
1052
1053 cout << "Processed SCORE message!" << endl;
1054
1055 break;
1056 }
1057 default:
1058 {
1059 cout << "Received invalid message of type " << msg.type << endl;
1060
1061 break;
1062 }
1063 }
1064
1065 break;
1066 }
1067 default:
1068 {
1069 cout << "The state has an invalid value: " << state << endl;
1070
1071 break;
1072 }
1073 }
1074}
1075
1076int getRefreshRate(int width, int height)
1077{
1078 int numRefreshRates = al_get_num_display_modes();
1079 ALLEGRO_DISPLAY_MODE displayMode;
1080
1081 for(int i=0; i<numRefreshRates; i++) {
1082 al_get_display_mode(i, &displayMode);
1083
1084 if (displayMode.width == width && displayMode.height == height)
1085 return displayMode.refresh_rate;
1086 }
1087
1088 return 0;
1089}
1090
1091void drawMessageStatus(ALLEGRO_FONT* font)
1092{
1093 int clientMsgOffset = 5;
1094 int serverMsgOffset = 950;
1095
1096 al_draw_text(font, al_map_rgb(0, 255, 255), 0+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "ID");
1097 al_draw_text(font, al_map_rgb(0, 255, 255), 20+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "Type");
1098 al_draw_text(font, al_map_rgb(0, 255, 255), 240+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "Acked?");
1099
1100 al_draw_text(font, al_map_rgb(0, 255, 255), serverMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "ID");
1101
1102 map<unsigned int, map<unsigned long, MessageContainer> >& sentMessages = msgProcessor.getSentMessages();
1103 int id, type;
1104 bool acked;
1105 ostringstream ossId, ossAcked;
1106
1107 map<unsigned int, map<unsigned long, MessageContainer> >::iterator it;
1108
1109 int msgCount = 0;
1110 for (it = sentMessages.begin(); it != sentMessages.end(); it++) {
1111 map<unsigned long, MessageContainer> playerMessage = it->second;
1112 map<unsigned long, MessageContainer>::iterator it2;
1113 for (it2 = playerMessage.begin(); it2 != playerMessage.end(); it2++) {
1114
1115 id = it->first;
1116 ossId.str("");;
1117 ossId << id;
1118
1119 type = it2->second.getMessage()->type;
1120 string typeStr = MessageContainer::getMsgTypeString(type);
1121
1122 acked = it2->second.getAcked();
1123 ossAcked.str("");;
1124 ossAcked << boolalpha << acked;
1125
1126 al_draw_text(font, al_map_rgb(0, 255, 0), clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossId.str().c_str());
1127 al_draw_text(font, al_map_rgb(0, 255, 0), 20+clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, typeStr.c_str());
1128 al_draw_text(font, al_map_rgb(0, 255, 0), 240+clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossAcked.str().c_str());
1129
1130 msgCount++;
1131 }
1132 }
1133
1134 if (msgProcessor.getAckedMessages().size() > 0) {
1135 map<unsigned int, unsigned long long> ackedMessages = msgProcessor.getAckedMessages()[0];
1136 map<unsigned int, unsigned long long>::iterator it3;
1137
1138 msgCount = 0;
1139 for (it3 = ackedMessages.begin(); it3 != ackedMessages.end(); it3++) {
1140 ossId.str("");;
1141 ossId << it3->first;
1142
1143 al_draw_text(font, al_map_rgb(255, 0, 0), 25+serverMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossId.str().c_str());
1144
1145 msgCount++;
1146 }
1147 }
1148}
1149
1150// Callback definitions
1151
1152void goToRegisterScreen()
1153{
1154 txtUsernameRegister->clear();
1155 txtPasswordRegister->clear();
1156 lblRegisterStatus->setText("");
1157 rblClasses->setSelectedButton(-1);
1158
1159 wndCurrent = wndRegister;
1160}
1161
1162void goToLoginScreen()
1163{
1164 txtUsername->clear();
1165 txtPassword->clear();
1166 lblLoginStatus->setText("");
1167
1168 wndCurrent = wndLogin;
1169}
1170
1171// maybe need a goToGameScreen function as well and add state changes to these functions as well
1172
1173void registerAccount()
1174{
1175 string username = txtUsernameRegister->getStr();
1176 string password = txtPasswordRegister->getStr();
1177
1178 txtUsernameRegister->clear();
1179 txtPasswordRegister->clear();
1180 // maybe clear rblClasses as well (add a method to RadioButtonList to enable this)
1181
1182 Player::PlayerClass playerClass;
1183
1184 switch (rblClasses->getSelectedButton()) {
1185 case 0:
1186 playerClass = Player::CLASS_WARRIOR;
1187 break;
1188 case 1:
1189 playerClass = Player::CLASS_RANGER;
1190 break;
1191 default:
1192 cout << "Invalid class selection" << endl;
1193 playerClass = Player::CLASS_NONE;
1194 break;
1195 }
1196
1197 msgTo.type = MSG_TYPE_REGISTER;
1198
1199 strcpy(msgTo.buffer, username.c_str());
1200 strcpy(msgTo.buffer+username.size()+1, password.c_str());
1201 memcpy(msgTo.buffer+username.size()+password.size()+2, &playerClass, 4);
1202
1203 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
1204}
1205
1206void login()
1207{
1208 string strUsername = txtUsername->getStr();
1209 string strPassword = txtPassword->getStr();
1210 username = strUsername;
1211
1212 txtUsername->clear();
1213 txtPassword->clear();
1214
1215 msgTo.type = MSG_TYPE_LOGIN;
1216
1217 strcpy(msgTo.buffer, strUsername.c_str());
1218 strcpy(msgTo.buffer+username.size()+1, strPassword.c_str());
1219
1220 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
1221
1222 state = STATE_LOBBY;
1223}
1224
1225void logout()
1226{
1227 switch(state) {
1228 case STATE_LOBBY:
1229 txtJoinGame->clear();
1230 txtCreateGame->clear();
1231 break;
1232 case STATE_GAME:
1233 txtChat->clear();
1234 chatConsole.clear();
1235 break;
1236 default:
1237 cout << "Logout called from invalid state: " << state << endl;
1238 break;
1239 }
1240
1241 msgTo.type = MSG_TYPE_LOGOUT;
1242
1243 strcpy(msgTo.buffer, username.c_str());
1244
1245 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
1246}
1247
1248void quit()
1249{
1250 doexit = true;
1251}
1252
1253void sendChatMessage()
1254{
1255 string msg = txtChat->getStr();
1256 txtChat->clear();
1257
1258 msgTo.type = MSG_TYPE_CHAT;
1259 strcpy(msgTo.buffer, msg.c_str());
1260
1261 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
1262}
1263
1264void toggleDebugging()
1265{
1266 debugging = !debugging;
1267}
1268
1269void joinGame()
1270{
1271 cout << "Joining game" << endl;
1272
1273 string msg = txtJoinGame->getStr();
1274 txtJoinGame->clear();
1275
1276 msgTo.type = MSG_TYPE_JOIN_GAME;
1277 strcpy(msgTo.buffer, msg.c_str());
1278
1279 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
1280}
1281
1282void createGame()
1283{
1284 cout << "Creating game" << endl;
1285
1286 string msg = txtCreateGame->getStr();
1287 txtCreateGame->clear();
1288
1289 cout << "Sending message: " << msg.c_str() << endl;
1290
1291 msgTo.type = MSG_TYPE_CREATE_GAME;
1292 strcpy(msgTo.buffer, msg.c_str());
1293
1294 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
1295}
1296
1297void leaveGame()
1298{
1299 cout << "Leaving game" << endl;
1300
1301 game = NULL;
1302
1303 state = STATE_LOBBY;
1304 wndCurrent = wndLobby;
1305
1306 msgTo.type = MSG_TYPE_LEAVE_GAME;
1307
1308 msgProcessor.sendMessage(&msgTo, sock, &server, &outputLog);
1309}
Note: See TracBrowser for help on using the repository browser.