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

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

Client gui creation code moved to its own method

  • Property mode set to 100644
File size: 40.9 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 map<string, int>::iterator it;
389 int i=0;
390 ostringstream ossGame;
391 for (it = mapGames.begin(); it != mapGames.end(); it++) {
392 ossGame << it->first << " (" << it->second << " players)" << endl;
393 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());
394 ossGame.clear();
395 ossGame.str("");
396 i++;
397 }
398 }
399 else if (wndCurrent == wndGame)
400 {
401 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 4, ALLEGRO_ALIGN_LEFT, "Players");
402
403 map<unsigned int, Player*>& gamePlayers = game->getPlayers();
404 map<unsigned int, Player*>::iterator it;
405
406 if (!debugging) {
407 int playerCount = 0;
408 for (it = gamePlayers.begin(); it != gamePlayers.end(); it++)
409 {
410 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 19+(playerCount+1)*15, ALLEGRO_ALIGN_LEFT, it->second->name.c_str());
411 playerCount++;
412 }
413 }
414
415 ostringstream ossScoreBlue, ossScoreRed;
416
417 ossScoreBlue << "Blue: " << game->getBlueScore() << endl;
418 ossScoreRed << "Red: " << game->getRedScore() << endl;
419
420 al_draw_text(font, al_map_rgb(0, 255, 0), 330, 80, ALLEGRO_ALIGN_LEFT, ossScoreBlue.str().c_str());
421 al_draw_text(font, al_map_rgb(0, 255, 0), 515, 80, ALLEGRO_ALIGN_LEFT, ossScoreRed.str().c_str());
422
423 // update players
424 for (it = game->getPlayers().begin(); it != game->getPlayers().end(); it++)
425 {
426 it->second->updateTarget(game->getPlayers());
427 }
428
429 for (it = game->getPlayers().begin(); it != game->getPlayers().end(); it++)
430 {
431 it->second->move(game->getMap()); // ignore return value
432 }
433
434 // update projectile positions
435 map<unsigned int, Projectile>::iterator it2;
436 for (it2 = game->getProjectiles().begin(); it2 != game->getProjectiles().end(); it2++)
437 {
438 it2->second.move(game->getPlayers());
439 }
440
441 GameRender::drawMap(game->getMap());
442 GameRender::drawPlayers(game->getPlayers(), font, curPlayerId);
443 GameRender::drawProjectiles(game->getProjectiles(), game->getPlayers());
444 }
445 else if (wndCurrent == wndGameSummary)
446 {
447 ostringstream ossBlueScore, ossRedScore;
448
449 ossBlueScore << "Blue Score: " << gameSummary->getBlueScore();
450 ossRedScore << "Red Score: " << gameSummary->getRedScore();
451
452 string strWinner;
453
454 if (gameSummary->getWinner() == 0)
455 strWinner = "Blue Team Wins";
456 else if (gameSummary->getWinner() == 1)
457 strWinner = "Red Team Wins";
458 else
459 strWinner = "winner set to wrong value";
460
461 al_draw_text(font, al_map_rgb(0, 255, 0), 512, 40, ALLEGRO_ALIGN_CENTRE, gameSummary->getName().c_str());
462 al_draw_text(font, al_map_rgb(0, 255, 0), 330, 80, ALLEGRO_ALIGN_LEFT, ossBlueScore.str().c_str());
463 al_draw_text(font, al_map_rgb(0, 255, 0), 515, 80, ALLEGRO_ALIGN_LEFT, ossRedScore.str().c_str());
464 al_draw_text(font, al_map_rgb(0, 255, 0), 512, 120, ALLEGRO_ALIGN_CENTRE, strWinner.c_str());
465 }
466
467 if (debugging) {
468 //debugConsole.draw(font, al_map_rgb(255,255,255));
469 drawMessageStatus(font);
470 }
471
472 al_flip_display();
473 }
474 }
475
476 #if defined WINDOWS
477 closesocket(sock);
478 #elif defined LINUX
479 close(sock);
480 #endif
481
482 shutdownWinSock();
483
484 // delete all components
485 for (unsigned int x=0; x<vctComponents.size(); x++)
486 delete vctComponents[x];
487
488 delete wndLogin;
489 delete wndRegister;
490 delete wndLobby;
491 delete wndLobbyDebug;
492 delete wndGame;
493 delete wndGameSummary;
494
495 // game should be deleted when the player leaves a gamw
496 if (game != NULL)
497 delete game;
498
499 if (gameSummary != NULL)
500 delete gameSummary;
501
502 map<unsigned int, Player*>::iterator it;
503
504 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++) {
505 delete it->second;
506 }
507
508 al_destroy_event_queue(event_queue);
509 al_destroy_display(display);
510 al_destroy_timer(timer);
511
512 outputLog << "Stopped client on " << getCurrentDateTimeString() << endl;
513 outputLog.close();
514
515 return 0;
516}
517
518void initWinSock()
519{
520#if defined WINDOWS
521 WORD wVersionRequested;
522 WSADATA wsaData;
523 int wsaerr;
524
525 wVersionRequested = MAKEWORD(2, 2);
526 wsaerr = WSAStartup(wVersionRequested, &wsaData);
527
528 if (wsaerr != 0) {
529 cout << "The Winsock dll not found." << endl;
530 exit(1);
531 }else
532 cout << "The Winsock dll was found." << endl;
533#endif
534}
535
536void shutdownWinSock()
537{
538#if defined WINDOWS
539 WSACleanup();
540#endif
541}
542
543void createGui(ALLEGRO_FONT* font) {
544 // wndLogin
545
546 wndLogin = new Window(0, 0, SCREEN_W, SCREEN_H);
547 vctComponents.push_back(wndLogin->addComponent(new Textbox(516, 40, 100, 20, font)));
548 vctComponents.push_back(wndLogin->addComponent(new Textbox(516, 70, 100, 20, font)));
549 vctComponents.push_back(wndLogin->addComponent(new TextLabel(410, 40, 100, 20, font, "Username:", ALLEGRO_ALIGN_RIGHT)));
550 vctComponents.push_back(wndLogin->addComponent(new TextLabel(410, 70, 100, 20, font, "Password:", ALLEGRO_ALIGN_RIGHT)));
551 vctComponents.push_back(wndLogin->addComponent(new TextLabel((SCREEN_W-600)/2, 100, 600, 20, font, "", ALLEGRO_ALIGN_CENTRE)));
552 vctComponents.push_back(wndLogin->addComponent(new Button(SCREEN_W/2-100, 130, 90, 20, font, "Register", goToRegisterScreen)));
553 vctComponents.push_back(wndLogin->addComponent(new Button(SCREEN_W/2+10, 130, 90, 20, font, "Login", login)));
554 vctComponents.push_back(wndLogin->addComponent(new Button(920, 10, 80, 20, font, "Quit", quit)));
555 vctComponents.push_back(wndLogin->addComponent(new Button(20, 10, 160, 20, font, "Toggle Debugging", toggleDebugging)));
556
557 txtUsername = (Textbox*)wndLogin->getComponent(0);
558 txtPassword = (Textbox*)wndLogin->getComponent(1);
559 lblLoginStatus = (TextLabel*)wndLogin->getComponent(4);
560
561 cout << "Created login screen" << endl;
562
563
564 // wndRegister
565
566 wndRegister = new Window(0, 0, SCREEN_W, SCREEN_H);
567 vctComponents.push_back(wndRegister->addComponent(new Textbox(516, 40, 100, 20, font)));
568 vctComponents.push_back(wndRegister->addComponent(new Textbox(516, 70, 100, 20, font)));
569 vctComponents.push_back(wndRegister->addComponent(new TextLabel(410, 40, 100, 20, font, "Username:", ALLEGRO_ALIGN_RIGHT)));
570 vctComponents.push_back(wndRegister->addComponent(new TextLabel(410, 70, 100, 20, font, "Password:", ALLEGRO_ALIGN_RIGHT)));
571 vctComponents.push_back(wndRegister->addComponent(new RadioButtonList(432, 100, "Pick a class", font)));
572 vctComponents.push_back(wndRegister->addComponent(new TextLabel((SCREEN_W-600)/2, 190, 600, 20, font, "", ALLEGRO_ALIGN_CENTRE)));
573 vctComponents.push_back(wndRegister->addComponent(new Button(SCREEN_W/2-100, 220, 90, 20, font, "Back", goToLoginScreen)));
574 vctComponents.push_back(wndRegister->addComponent(new Button(SCREEN_W/2+10, 220, 90, 20, font, "Submit", registerAccount)));
575 vctComponents.push_back(wndRegister->addComponent(new Button(920, 10, 80, 20, font, "Quit", quit)));
576 vctComponents.push_back(wndRegister->addComponent(new Button(20, 10, 160, 20, font, "Toggle Debugging", toggleDebugging)));
577
578 txtUsernameRegister = (Textbox*)wndRegister->getComponent(0);
579 txtPasswordRegister = (Textbox*)wndRegister->getComponent(1);
580
581 rblClasses = (RadioButtonList*)wndRegister->getComponent(4);
582 rblClasses->addRadioButton("Warrior");
583 rblClasses->addRadioButton("Ranger");
584
585 lblRegisterStatus = (TextLabel*)wndRegister->getComponent(5);
586
587 cout << "Created register screen" << endl;
588
589
590 // wndLobby
591
592 txtJoinGame = new Textbox(SCREEN_W*1/2+15+4, 40, 100, 20, font);
593 vctComponents.push_back(txtJoinGame);
594
595 txtCreateGame = new Textbox(SCREEN_W*3/4+4, 40, 100, 20, font);
596 vctComponents.push_back(txtCreateGame);
597
598 wndLobby = new Window(0, 0, SCREEN_W, SCREEN_H);
599 vctComponents.push_back(wndLobby->addComponent(new Button(920, 10, 80, 20, font, "Logout", logout)));
600 vctComponents.push_back(wndLobby->addComponent(new TextLabel(SCREEN_W*1/2+15-112, 40, 110, 20, font, "Game Name:", ALLEGRO_ALIGN_RIGHT)));
601 wndLobby->addComponent(txtJoinGame);
602 vctComponents.push_back(wndLobby->addComponent(new Button(SCREEN_W*1/2+15-100, 80, 200, 20, font, "Join Existing Game", joinGame)));
603 vctComponents.push_back(wndLobby->addComponent(new TextLabel(SCREEN_W*3/4-112, 40, 110, 20, font, "Game Name:", ALLEGRO_ALIGN_RIGHT)));
604 wndLobby->addComponent(txtCreateGame);
605 vctComponents.push_back(wndLobby->addComponent(new Button(SCREEN_W*3/4-100, 80, 200, 20, font, "Create New Game", createGame)));
606 vctComponents.push_back(wndLobby->addComponent(new Textbox(95, 40, 300, 20, font)));
607 vctComponents.push_back(wndLobby->addComponent(new Button(95, 70, 60, 20, font, "Send", sendChatMessage)));
608 vctComponents.push_back(wndLobby->addComponent(new Button(20, 10, 160, 20, font, "Toggle Debugging", toggleDebugging)));
609
610 txtChat = (Textbox*)wndLobby->getComponent(7);
611
612 cout << "Created lobby screen" << endl;
613
614
615 // wndLobbyDebug
616
617 wndLobbyDebug = new Window(0, 0, SCREEN_W, SCREEN_H);
618 vctComponents.push_back(wndLobbyDebug->addComponent(new Button(920, 10, 80, 20, font, "Logout", logout)));
619 vctComponents.push_back(wndLobbyDebug->addComponent(new TextLabel(SCREEN_W*1/2+15-112, 40, 110, 20, font, "Game Name:", ALLEGRO_ALIGN_RIGHT)));
620 wndLobbyDebug->addComponent(txtJoinGame);
621 vctComponents.push_back(wndLobbyDebug->addComponent(new Button(SCREEN_W*1/2+15-100, 80, 200, 20, font, "Join Existing Game", joinGame)));
622 vctComponents.push_back(wndLobbyDebug->addComponent(new TextLabel(SCREEN_W*3/4-112, 40, 110, 20, font, "Game Name:", ALLEGRO_ALIGN_RIGHT)));
623 wndLobbyDebug->addComponent(txtCreateGame);
624 vctComponents.push_back(wndLobbyDebug->addComponent(new Button(SCREEN_W*3/4-100, 80, 200, 20, font, "Create New Game", createGame)));
625 vctComponents.push_back(wndLobbyDebug->addComponent(new Button(20, 10, 160, 20, font, "Toggle Debugging", toggleDebugging)));
626
627 cout << "Created debug lobby screen" << endl;
628
629
630 // wndGame
631
632 wndGame = new Window(0, 0, SCREEN_W, SCREEN_H);
633 vctComponents.push_back(wndGame->addComponent(new Button(880, 10, 120, 20, font, "Leave Game", leaveGame)));
634
635 cout << "Created new game screen" << endl;
636
637 wndGameSummary = new Window(0, 0, SCREEN_W, SCREEN_H);
638 vctComponents.push_back(wndGameSummary->addComponent(new Button(840, 730, 160, 20, font, "Back to Lobby", closeGameSummary)));
639
640 cout << "Created game summary screen" << endl;
641}
642
643void processMessage(NETWORK_MSG &msg, int &state, chat &chatConsole, map<unsigned int, Player*>& mapPlayers, unsigned int& curPlayerId)
644{
645 // this is outdated since most messages now don't contain just a text string
646 string response = string(msg.buffer);
647
648 switch(state)
649 {
650 case STATE_START:
651 {
652 cout << "In STATE_START" << endl;
653
654 switch(msg.type)
655 {
656 case MSG_TYPE_REGISTER:
657 {
658 lblRegisterStatus->setText(response);
659 break;
660 }
661 default:
662 {
663 cout << "(STATE_REGISTER) Received invalid message of type " << msg.type << endl;
664 break;
665 }
666 }
667
668 break;
669 }
670 case STATE_LOBBY:
671 {
672 cout << "In STATE_LOBBY" << endl;
673 switch(msg.type)
674 {
675 case MSG_TYPE_LOGIN:
676 {
677 if (response.compare("Player has already logged in.") == 0)
678 {
679 goToLoginScreen();
680 state = STATE_START;
681
682 lblLoginStatus->setText(response);
683 }
684 else if (response.compare("Incorrect username or password") == 0)
685 {
686 goToLoginScreen();
687 state = STATE_START;
688
689 lblLoginStatus->setText(response);
690 }
691 else
692 {
693 wndCurrent = wndLobby;
694
695 // this message should only be sent when a player first logs in so they know their id
696
697 Player* p = new Player("", "");
698 p->deserialize(msg.buffer);
699
700 if (mapPlayers.find(p->getId()) != mapPlayers.end())
701 delete mapPlayers[p->getId()];
702 mapPlayers[p->getId()] = p;
703 curPlayerId = p->getId();
704
705 cout << "Got a valid login response with the player" << endl;
706 cout << "Player id: " << curPlayerId << endl;
707 cout << "Player health: " << p->health << endl;
708 cout << "player map size: " << mapPlayers.size() << endl;
709 }
710
711 break;
712 }
713 case MSG_TYPE_LOGOUT:
714 {
715 cout << "Got a logout message" << endl;
716
717 unsigned int playerId;
718
719 // Check if it's about you or another player
720 memcpy(&playerId, msg.buffer, 4);
721 response = string(msg.buffer+4);
722
723 if (playerId == curPlayerId)
724 {
725 if (response.compare("You have successfully logged out.") == 0)
726 {
727 cout << "Logged out" << endl;
728 state = STATE_START;
729 goToLoginScreen();
730 }
731
732 // if there was an error logging out, nothing happens
733 }
734 else
735 {
736 delete mapPlayers[playerId];
737 }
738
739 break;
740 }
741 case MSG_TYPE_PLAYER:
742 {
743 cout << "Received MSG_TYPE_PLAYER" << endl;
744
745 Player p("", "");
746 p.deserialize(msg.buffer);
747 p.timeLastUpdated = getCurrentMillis();
748 p.isChasing = false;
749 if (p.health <= 0)
750 p.isDead = true;
751 else
752 p.isDead = false;
753
754 if (mapPlayers.find(p.getId()) != mapPlayers.end())
755 *(mapPlayers[p.getId()]) = p;
756 else
757 mapPlayers[p.getId()] = new Player(p);
758
759 break;
760 }
761 case MSG_TYPE_PLAYER_MOVE:
762 {
763 unsigned int id;
764 int x, y;
765
766 memcpy(&id, msg.buffer, 4);
767 memcpy(&x, msg.buffer+4, 4);
768 memcpy(&y, msg.buffer+8, 4);
769
770 mapPlayers[id]->target.x = x;
771 mapPlayers[id]->target.y = y;
772
773 mapPlayers[id]->isChasing = false;
774 mapPlayers[id]->setTargetPlayer(0);
775
776 break;
777 }
778 case MSG_TYPE_CHAT:
779 {
780 chatConsole.addLine(response);
781
782 break;
783 }
784 case MSG_TYPE_ATTACK:
785 {
786 cout << "Received START_ATTACK message" << endl;
787
788 unsigned int id, targetID;
789 memcpy(&id, msg.buffer, 4);
790 memcpy(&targetID, msg.buffer+4, 4);
791
792 cout << "source id: " << id << endl;
793 cout << "target id: " << targetID << endl;
794
795 Player* source = mapPlayers[id];
796 source->setTargetPlayer(targetID);
797 source->isChasing = true;
798
799 break;
800 }
801 case MSG_TYPE_GAME_INFO:
802 {
803 cout << "Received a GAME_INFO message" << endl;
804
805 string gameName(msg.buffer+4);
806 int numPlayers;
807
808 memcpy(&numPlayers, msg.buffer, 4);
809
810 cout << "Received game info for " << gameName << " (num players: " << numPlayers << ")" << endl;
811
812 if (numPlayers > 0)
813 mapGames[gameName] = numPlayers;
814 else
815 mapGames.erase(gameName);
816
817 break;
818 }
819 case MSG_TYPE_JOIN_GAME_SUCCESS:
820 {
821 cout << "Received a JOIN_GAME_SUCCESS message" << endl;
822
823 string gameName(msg.buffer);
824
825 #if defined WINDOWS
826 game = new Game(gameName, "../../data/map.txt", &msgProcessor);
827 #elif defined LINUX
828 game = new Game(gameName, "../data/map.txt", &msgProcessor);
829 #endif
830
831 cout << "Game name: " << gameName << endl;
832
833 state = STATE_GAME;
834 wndCurrent = wndGame;
835
836 msgTo.type = MSG_TYPE_JOIN_GAME_ACK;
837 strcpy(msgTo.buffer, gameName.c_str());
838
839 msgProcessor.sendMessage(&msgTo, &server);
840
841 break;
842 }
843 case MSG_TYPE_JOIN_GAME_FAILURE:
844 {
845 cout << "Received a JOIN_GAME_FAILURE message" << endl;
846
847 break;
848 }
849 default:
850 {
851 cout << "(STATE_LOBBY) Received invlaid message of type " << msg.type << endl;
852
853 break;
854 }
855 }
856
857 break;
858 }
859 case STATE_GAME:
860 {
861 cout << "(STATE_GAME) ";
862 switch(msg.type)
863 {
864 case MSG_TYPE_GAME_INFO:
865 {
866 cout << "Received a GAME_INFO message" << endl;
867
868 string gameName(msg.buffer+4);
869 int numPlayers;
870
871 memcpy(&numPlayers, msg.buffer, 4);
872
873 cout << "Received game info for " << gameName << " (num players: " << numPlayers << ")" << endl;
874
875 if (numPlayers > 0)
876 mapGames[gameName] = numPlayers;
877 else
878 mapGames.erase(gameName);
879
880 break;
881 }
882 case MSG_TYPE_SCORE:
883 {
884 cout << "Received SCORE message!" << endl;
885
886 int blueScore;
887 memcpy(&blueScore, msg.buffer, 4);
888 cout << "blue score: " << blueScore << endl;
889 game->setBlueScore(blueScore);
890
891 int redScore;
892 memcpy(&redScore, msg.buffer+4, 4);
893 cout << "red score: " << redScore << endl;
894 game->setRedScore(redScore);
895
896 cout << "Processed SCORE message!" << endl;
897
898 break;
899 }
900 case MSG_TYPE_FINISH_GAME:
901 {
902 cout << "Got a finish game message" << endl;
903 cout << "Should switch to STATE_LOBBY and show the final score" << endl;
904
905 unsigned int winner, blueScore, redScore;
906 memcpy(&winner, msg.buffer, 4);
907 memcpy(&blueScore, msg.buffer+4, 4);
908 memcpy(&redScore, msg.buffer+8, 4);
909
910 string gameName(msg.buffer+12);
911
912 cout << "winner: " << winner << endl;
913 cout << "blueScore: " << blueScore << endl;
914 cout << "redScore: " << redScore << endl;
915 cout << "gameName: " << gameName << endl;
916
917 gameSummary = new GameSummary(gameName, winner, blueScore, redScore);
918
919 delete game;
920 game = NULL;
921 state = STATE_LOBBY;
922 wndCurrent = wndGameSummary;
923
924
925 cout << "winner from obj: " << gameSummary->getWinner() << endl;
926 cout << "blueScore from obj: " << gameSummary->getBlueScore() << endl;
927 cout << "redScore from obj: " << gameSummary->getRedScore() << endl;
928 cout << "gameName from obj: " << gameSummary->getName() << endl;
929 break;
930 }
931 case MSG_TYPE_PLAYER:
932 {
933 cout << "Received MSG_TYPE_PLAYER" << endl;
934
935 Player p("", "");
936 p.deserialize(msg.buffer);
937 p.timeLastUpdated = getCurrentMillis();
938 p.isChasing = false;
939 if (p.health <= 0)
940 p.isDead = true;
941 else
942 p.isDead = false;
943
944 if (mapPlayers.find(p.getId()) != mapPlayers.end())
945 *(mapPlayers[p.getId()]) = p;
946 else
947 mapPlayers[p.getId()] = new Player(p);
948
949 break;
950 }
951 case MSG_TYPE_LOGOUT:
952 {
953 cout << "Got a logout message" << endl;
954
955 int playerId;
956
957 // Check if it's about you or another player
958 memcpy(&playerId, msg.buffer, 4);
959 response = string(msg.buffer+4);
960
961 if (playerId == curPlayerId)
962 cout << "Received MSG_TYPE_LOGOUT for self in STATE_GAME. This shouldn't happen." << endl;
963 else
964 delete mapPlayers[playerId];
965
966 break;
967 }
968 case MSG_TYPE_PLAYER_JOIN_GAME:
969 {
970 cout << "Received MSG_TYPE_PLAYER_JOIN_GAME" << endl;
971
972 Player p("", "");
973 p.deserialize(msg.buffer);
974 cout << "Deserialized player" << endl;
975 p.timeLastUpdated = getCurrentMillis();
976 p.isChasing = false;
977 if (p.health <= 0)
978 p.isDead = true;
979 else
980 p.isDead = false;
981
982 if (mapPlayers.find(p.getId()) != mapPlayers.end())
983 *(mapPlayers[p.getId()]) = p;
984 else
985 mapPlayers[p.getId()] = new Player(p);
986
987 game->addPlayer(mapPlayers[p.getId()]);
988
989 break;
990 }
991 case MSG_TYPE_LEAVE_GAME:
992 {
993 cout << "Received a LEAVE_GAME message" << endl;
994
995 string gameName(msg.buffer+4);
996 unsigned int playerId;
997
998 memcpy(&playerId, msg.buffer, 4);
999
1000 game->removePlayer(playerId);
1001
1002 break;
1003 }
1004 case MSG_TYPE_PLAYER_MOVE:
1005 {
1006 cout << "Received PLAYER_MOVE message" << endl;
1007
1008 unsigned int id;
1009 int x, y;
1010
1011 memcpy(&id, msg.buffer, 4);
1012 memcpy(&x, msg.buffer+4, 4);
1013 memcpy(&y, msg.buffer+8, 4);
1014
1015 cout << "id: " << id << endl;
1016
1017 mapPlayers[id]->target.x = x;
1018 mapPlayers[id]->target.y = y;
1019
1020 mapPlayers[id]->isChasing = false;
1021 mapPlayers[id]->setTargetPlayer(0);
1022
1023 break;
1024 }
1025 case MSG_TYPE_OBJECT:
1026 {
1027 cout << "Received object message in STATE_GAME" << endl;
1028
1029 WorldMap::Object o(0, OBJECT_NONE, 0, 0);
1030 o.deserialize(msg.buffer);
1031 cout << "object id: " << o.id << endl;
1032 game->getMap()->updateObject(o.id, o.type, o.pos.x, o.pos.y);
1033
1034 break;
1035 }
1036 case MSG_TYPE_REMOVE_OBJECT:
1037 {
1038 cout << "Received REMOVE_OBJECT message!" << endl;
1039
1040 int id;
1041 memcpy(&id, msg.buffer, 4);
1042
1043 cout << "Removing object with id " << id << endl;
1044
1045 if (!game->getMap()->removeObject(id))
1046 cout << "Did not remove the object" << endl;
1047
1048 break;
1049 }
1050 case MSG_TYPE_ATTACK:
1051 {
1052 cout << "Received START_ATTACK message" << endl;
1053
1054 unsigned int id, targetId;
1055 memcpy(&id, msg.buffer, 4);
1056 memcpy(&targetId, msg.buffer+4, 4);
1057
1058 cout << "source id: " << id << endl;
1059 cout << "target id: " << targetId << endl;
1060
1061 // need to check the target exists in the current game
1062 Player* source = game->getPlayers()[id];
1063 source->setTargetPlayer(targetId);
1064 source->isChasing = true;
1065
1066 break;
1067 }
1068 case MSG_TYPE_PROJECTILE:
1069 {
1070 cout << "Received a PROJECTILE message" << endl;
1071
1072 unsigned int projId, x, y, targetId;
1073
1074 memcpy(&projId, msg.buffer, 4);
1075 memcpy(&x, msg.buffer+4, 4);
1076 memcpy(&y, msg.buffer+8, 4);
1077 memcpy(&targetId, msg.buffer+12, 4);
1078
1079 cout << "projId: " << projId << endl;
1080 cout << "x: " << x << endl;
1081 cout << "y: " << y << endl;
1082 cout << "Target: " << targetId << endl;
1083
1084 Projectile proj(x, y, targetId, 0);
1085 proj.setId(projId);
1086
1087 game->addProjectile(proj);
1088
1089 break;
1090 }
1091 case MSG_TYPE_REMOVE_PROJECTILE:
1092 {
1093 cout << "Received a REMOVE_PROJECTILE message" << endl;
1094
1095 unsigned int id;
1096 memcpy(&id, msg.buffer, 4);
1097
1098 game->removeProjectile(id);
1099
1100 break;
1101 }
1102 default:
1103 {
1104 cout << "Received invalid message of type " << msg.type << endl;
1105
1106 break;
1107 }
1108 }
1109
1110 break;
1111 }
1112 default:
1113 {
1114 cout << "The state has an invalid value: " << state << endl;
1115
1116 break;
1117 }
1118 }
1119}
1120
1121int getRefreshRate(int width, int height)
1122{
1123 int numRefreshRates = al_get_num_display_modes();
1124 ALLEGRO_DISPLAY_MODE displayMode;
1125
1126 for(int i=0; i<numRefreshRates; i++) {
1127 al_get_display_mode(i, &displayMode);
1128
1129 if (displayMode.width == width && displayMode.height == height)
1130 return displayMode.refresh_rate;
1131 }
1132
1133 return 0;
1134}
1135
1136void drawMessageStatus(ALLEGRO_FONT* font)
1137{
1138 int clientMsgOffset = 5;
1139 int serverMsgOffset = 950;
1140
1141 al_draw_text(font, al_map_rgb(0, 255, 255), 0+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "ID");
1142 al_draw_text(font, al_map_rgb(0, 255, 255), 20+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "Type");
1143 al_draw_text(font, al_map_rgb(0, 255, 255), 240+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "Acked?");
1144
1145 //al_draw_text(font, al_map_rgb(0, 255, 255), serverMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "ID");
1146
1147 map<unsigned int, map<unsigned long, MessageContainer> >& sentMessages = msgProcessor.getSentMessages();
1148 int id, type;
1149 bool acked;
1150 ostringstream ossId, ossAcked;
1151
1152 map<unsigned int, map<unsigned long, MessageContainer> >::iterator it;
1153
1154 int msgCount = 0;
1155 for (it = sentMessages.begin(); it != sentMessages.end(); it++) {
1156 map<unsigned long, MessageContainer> playerMessage = it->second;
1157 map<unsigned long, MessageContainer>::iterator it2;
1158 for (it2 = playerMessage.begin(); it2 != playerMessage.end(); it2++) {
1159
1160 id = it->first;
1161 ossId.str("");;
1162 ossId << id;
1163
1164 type = it2->second.getMessage()->type;
1165 string typeStr = MessageContainer::getMsgTypeString(type);
1166
1167 acked = it2->second.getAcked();
1168 ossAcked.str("");;
1169 ossAcked << boolalpha << acked;
1170
1171 al_draw_text(font, al_map_rgb(0, 255, 0), clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossId.str().c_str());
1172 al_draw_text(font, al_map_rgb(0, 255, 0), 20+clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, typeStr.c_str());
1173 al_draw_text(font, al_map_rgb(0, 255, 0), 240+clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossAcked.str().c_str());
1174
1175 msgCount++;
1176 }
1177 }
1178
1179 if (msgProcessor.getAckedMessages().size() > 0) {
1180 map<unsigned int, unsigned long long> ackedMessages = msgProcessor.getAckedMessages()[0];
1181 map<unsigned int, unsigned long long>::iterator it3;
1182
1183 msgCount = 0;
1184 for (it3 = ackedMessages.begin(); it3 != ackedMessages.end(); it3++) {
1185 ossId.str("");;
1186 ossId << it3->first;
1187
1188 al_draw_text(font, al_map_rgb(255, 0, 0), 25+serverMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossId.str().c_str());
1189
1190 msgCount++;
1191 }
1192 }
1193}
1194
1195// Callback definitions
1196
1197void goToRegisterScreen()
1198{
1199 txtUsernameRegister->clear();
1200 txtPasswordRegister->clear();
1201 lblRegisterStatus->setText("");
1202 rblClasses->setSelectedButton(-1);
1203
1204 wndCurrent = wndRegister;
1205}
1206
1207void goToLoginScreen()
1208{
1209 txtUsername->clear();
1210 txtPassword->clear();
1211 lblLoginStatus->setText("");
1212
1213 wndCurrent = wndLogin;
1214}
1215
1216// maybe need a goToGameScreen function as well and add state changes to these functions as well
1217
1218void registerAccount()
1219{
1220 string username = txtUsernameRegister->getStr();
1221 string password = txtPasswordRegister->getStr();
1222
1223 txtUsernameRegister->clear();
1224 txtPasswordRegister->clear();
1225 // maybe clear rblClasses as well (add a method to RadioButtonList to enable this)
1226
1227 Player::PlayerClass playerClass;
1228
1229 switch (rblClasses->getSelectedButton()) {
1230 case 0:
1231 playerClass = Player::CLASS_WARRIOR;
1232 break;
1233 case 1:
1234 playerClass = Player::CLASS_RANGER;
1235 break;
1236 default:
1237 cout << "Invalid class selection" << endl;
1238 playerClass = Player::CLASS_NONE;
1239 break;
1240 }
1241
1242 msgTo.type = MSG_TYPE_REGISTER;
1243
1244 strcpy(msgTo.buffer, username.c_str());
1245 strcpy(msgTo.buffer+username.size()+1, password.c_str());
1246 memcpy(msgTo.buffer+username.size()+password.size()+2, &playerClass, 4);
1247
1248 msgProcessor.sendMessage(&msgTo, &server);
1249}
1250
1251void login()
1252{
1253 string strUsername = txtUsername->getStr();
1254 string strPassword = txtPassword->getStr();
1255 username = strUsername;
1256
1257 txtUsername->clear();
1258 txtPassword->clear();
1259
1260 msgTo.type = MSG_TYPE_LOGIN;
1261
1262 strcpy(msgTo.buffer, strUsername.c_str());
1263 strcpy(msgTo.buffer+username.size()+1, strPassword.c_str());
1264
1265 msgProcessor.sendMessage(&msgTo, &server);
1266
1267 state = STATE_LOBBY;
1268}
1269
1270void logout()
1271{
1272 switch(state) {
1273 case STATE_LOBBY:
1274 txtJoinGame->clear();
1275 txtCreateGame->clear();
1276 break;
1277 default:
1278 cout << "Logout called from invalid state: " << state << endl;
1279 break;
1280 }
1281
1282 msgTo.type = MSG_TYPE_LOGOUT;
1283
1284 strcpy(msgTo.buffer, username.c_str());
1285
1286 msgProcessor.sendMessage(&msgTo, &server);
1287}
1288
1289void quit()
1290{
1291 doexit = true;
1292}
1293
1294void sendChatMessage()
1295{
1296 string msg = txtChat->getStr();
1297 txtChat->clear();
1298
1299 msgTo.type = MSG_TYPE_CHAT;
1300 strcpy(msgTo.buffer, msg.c_str());
1301
1302 msgProcessor.sendMessage(&msgTo, &server);
1303}
1304
1305void toggleDebugging()
1306{
1307 debugging = !debugging;
1308}
1309
1310void joinGame()
1311{
1312 cout << "Joining game" << endl;
1313
1314 string msg = txtJoinGame->getStr();
1315 txtJoinGame->clear();
1316
1317 msgTo.type = MSG_TYPE_JOIN_GAME;
1318 strcpy(msgTo.buffer, msg.c_str());
1319
1320 msgProcessor.sendMessage(&msgTo, &server);
1321}
1322
1323void createGame()
1324{
1325 cout << "Creating game" << endl;
1326
1327 string msg = txtCreateGame->getStr();
1328 txtCreateGame->clear();
1329
1330 cout << "Sending message: " << msg.c_str() << endl;
1331
1332 msgTo.type = MSG_TYPE_CREATE_GAME;
1333 strcpy(msgTo.buffer, msg.c_str());
1334
1335 msgProcessor.sendMessage(&msgTo, &server);
1336}
1337
1338void leaveGame()
1339{
1340 cout << "Leaving game" << endl;
1341
1342 game = NULL;
1343
1344 state = STATE_LOBBY;
1345 wndCurrent = wndLobby;
1346
1347 msgTo.type = MSG_TYPE_LEAVE_GAME;
1348
1349 msgProcessor.sendMessage(&msgTo, &server);
1350}
1351
1352void closeGameSummary()
1353{
1354 delete gameSummary;
1355 gameSummary = NULL;
1356 wndCurrent = wndLobby;
1357 cout << "Processed button actions" << endl;
1358}
Note: See TracBrowser for help on using the repository browser.