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

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

Client correctly handles other players leaving

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