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

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

The client prints a list of all online players in the lobby

  • Property mode set to 100644
File size: 41.6 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 // this is outdated since most messages now don't contain just a text string
660 string response = string(msg.buffer);
661
662 switch(state)
663 {
664 case STATE_START:
665 {
666 cout << "In STATE_START" << endl;
667
668 switch(msg.type)
669 {
670 case MSG_TYPE_REGISTER:
671 {
672 lblRegisterStatus->setText(response);
673 break;
674 }
675 default:
676 {
677 cout << "(STATE_REGISTER) Received invalid message of type " << msg.type << endl;
678 break;
679 }
680 }
681
682 break;
683 }
684 case STATE_LOBBY:
685 {
686 cout << "In STATE_LOBBY" << endl;
687 switch(msg.type)
688 {
689 case MSG_TYPE_LOGIN:
690 {
691 if (response.compare("Player has already logged in.") == 0)
692 {
693 goToLoginScreen();
694 state = STATE_START;
695
696 lblLoginStatus->setText(response);
697 }
698 else if (response.compare("Incorrect username or password") == 0)
699 {
700 goToLoginScreen();
701 state = STATE_START;
702
703 lblLoginStatus->setText(response);
704 }
705 else
706 {
707 wndCurrent = wndLobby;
708
709 // this message should only be sent when a player first logs in so they know their id
710
711 Player* p = new Player("", "");
712 p->deserialize(msg.buffer);
713
714 if (mapPlayers.find(p->getId()) != mapPlayers.end())
715 delete mapPlayers[p->getId()];
716 mapPlayers[p->getId()] = p;
717 curPlayerId = p->getId();
718
719 cout << "Got a valid login response with the player" << endl;
720 cout << "Player id: " << curPlayerId << endl;
721 cout << "Player health: " << p->health << endl;
722 cout << "player map size: " << mapPlayers.size() << endl;
723 }
724
725 break;
726 }
727 case MSG_TYPE_LOGOUT:
728 {
729 cout << "Got a logout message" << endl;
730
731 unsigned int playerId;
732
733 // Check if it's about you or another player
734 memcpy(&playerId, msg.buffer, 4);
735 response = string(msg.buffer+4);
736
737 if (playerId == curPlayerId)
738 {
739 if (response.compare("You have successfully logged out.") == 0)
740 {
741 cout << "Logged out" << endl;
742 state = STATE_START;
743 goToLoginScreen();
744 }
745
746 // if there was an error logging out, nothing happens
747 }
748 else
749 {
750 delete mapPlayers[playerId];
751 }
752
753 break;
754 }
755 case MSG_TYPE_PLAYER:
756 {
757 cout << "Received MSG_TYPE_PLAYER" << endl;
758
759 Player p("", "");
760 p.deserialize(msg.buffer);
761 p.timeLastUpdated = getCurrentMillis();
762 p.isChasing = false;
763 if (p.health <= 0)
764 p.isDead = true;
765 else
766 p.isDead = false;
767
768 if (mapPlayers.find(p.getId()) != mapPlayers.end())
769 *(mapPlayers[p.getId()]) = p;
770 else
771 mapPlayers[p.getId()] = new Player(p);
772
773 break;
774 }
775 case MSG_TYPE_PLAYER_MOVE:
776 {
777 unsigned int id;
778 int x, y;
779
780 memcpy(&id, msg.buffer, 4);
781 memcpy(&x, msg.buffer+4, 4);
782 memcpy(&y, msg.buffer+8, 4);
783
784 mapPlayers[id]->target.x = x;
785 mapPlayers[id]->target.y = y;
786
787 mapPlayers[id]->isChasing = false;
788 mapPlayers[id]->setTargetPlayer(0);
789
790 break;
791 }
792 case MSG_TYPE_CHAT:
793 {
794 chatConsole.addLine(response);
795
796 break;
797 }
798 case MSG_TYPE_ATTACK:
799 {
800 cout << "Received START_ATTACK message" << endl;
801
802 unsigned int id, targetID;
803 memcpy(&id, msg.buffer, 4);
804 memcpy(&targetID, msg.buffer+4, 4);
805
806 cout << "source id: " << id << endl;
807 cout << "target id: " << targetID << endl;
808
809 Player* source = mapPlayers[id];
810 source->setTargetPlayer(targetID);
811 source->isChasing = true;
812
813 break;
814 }
815 case MSG_TYPE_GAME_INFO:
816 {
817 cout << "Received a GAME_INFO message" << endl;
818
819 string gameName(msg.buffer+4);
820 int numPlayers;
821
822 memcpy(&numPlayers, msg.buffer, 4);
823
824 cout << "Received game info for " << gameName << " (num players: " << numPlayers << ")" << endl;
825
826 if (numPlayers > 0)
827 mapGames[gameName] = numPlayers;
828 else
829 mapGames.erase(gameName);
830
831 break;
832 }
833 case MSG_TYPE_JOIN_GAME_SUCCESS:
834 {
835 cout << "Received a JOIN_GAME_SUCCESS message" << endl;
836
837 string gameName(msg.buffer);
838
839 #if defined WINDOWS
840 game = new Game(gameName, "../../data/map.txt", &msgProcessor);
841 #elif defined LINUX
842 game = new Game(gameName, "../data/map.txt", &msgProcessor);
843 #endif
844
845 cout << "Game name: " << gameName << endl;
846
847 state = STATE_GAME;
848 wndCurrent = wndGame;
849
850 msgTo.type = MSG_TYPE_JOIN_GAME_ACK;
851 strcpy(msgTo.buffer, gameName.c_str());
852
853 msgProcessor.sendMessage(&msgTo, &server);
854
855 break;
856 }
857 case MSG_TYPE_JOIN_GAME_FAILURE:
858 {
859 cout << "Received a JOIN_GAME_FAILURE message" << endl;
860
861 break;
862 }
863 default:
864 {
865 cout << "(STATE_LOBBY) Received invlaid message of type " << msg.type << endl;
866
867 break;
868 }
869 }
870
871 break;
872 }
873 case STATE_GAME:
874 {
875 cout << "(STATE_GAME) ";
876 switch(msg.type)
877 {
878 case MSG_TYPE_GAME_INFO:
879 {
880 cout << "Received a GAME_INFO message" << endl;
881
882 string gameName(msg.buffer+4);
883 int numPlayers;
884
885 memcpy(&numPlayers, msg.buffer, 4);
886
887 cout << "Received game info for " << gameName << " (num players: " << numPlayers << ")" << endl;
888
889 if (numPlayers > 0)
890 mapGames[gameName] = numPlayers;
891 else
892 mapGames.erase(gameName);
893
894 break;
895 }
896 case MSG_TYPE_SCORE:
897 {
898 cout << "Received SCORE message!" << endl;
899
900 int blueScore;
901 memcpy(&blueScore, msg.buffer, 4);
902 cout << "blue score: " << blueScore << endl;
903 game->setBlueScore(blueScore);
904
905 int redScore;
906 memcpy(&redScore, msg.buffer+4, 4);
907 cout << "red score: " << redScore << endl;
908 game->setRedScore(redScore);
909
910 cout << "Processed SCORE message!" << endl;
911
912 break;
913 }
914 case MSG_TYPE_FINISH_GAME:
915 {
916 cout << "Got a finish game message" << endl;
917 cout << "Should switch to STATE_LOBBY and show the final score" << endl;
918
919 unsigned int winner, blueScore, redScore;
920 memcpy(&winner, msg.buffer, 4);
921 memcpy(&blueScore, msg.buffer+4, 4);
922 memcpy(&redScore, msg.buffer+8, 4);
923
924 string gameName(msg.buffer+12);
925
926 cout << "winner: " << winner << endl;
927 cout << "blueScore: " << blueScore << endl;
928 cout << "redScore: " << redScore << endl;
929 cout << "gameName: " << gameName << endl;
930
931 gameSummary = new GameSummary(gameName, winner, blueScore, redScore);
932
933 delete game;
934 game = NULL;
935 state = STATE_LOBBY;
936 wndCurrent = wndGameSummary;
937
938
939 cout << "winner from obj: " << gameSummary->getWinner() << endl;
940 cout << "blueScore from obj: " << gameSummary->getBlueScore() << endl;
941 cout << "redScore from obj: " << gameSummary->getRedScore() << endl;
942 cout << "gameName from obj: " << gameSummary->getName() << endl;
943 break;
944 }
945 case MSG_TYPE_PLAYER:
946 {
947 cout << "Received MSG_TYPE_PLAYER" << endl;
948
949 Player p("", "");
950 p.deserialize(msg.buffer);
951 p.timeLastUpdated = getCurrentMillis();
952 p.isChasing = false;
953 if (p.health <= 0)
954 p.isDead = true;
955 else
956 p.isDead = false;
957
958 if (mapPlayers.find(p.getId()) != mapPlayers.end())
959 *(mapPlayers[p.getId()]) = p;
960 else
961 mapPlayers[p.getId()] = new Player(p);
962
963 break;
964 }
965 case MSG_TYPE_LOGOUT:
966 {
967 cout << "Got a logout message" << endl;
968
969 int playerId;
970
971 // Check if it's about you or another player
972 memcpy(&playerId, msg.buffer, 4);
973 response = string(msg.buffer+4);
974
975 if (playerId == curPlayerId)
976 cout << "Received MSG_TYPE_LOGOUT for self in STATE_GAME. This shouldn't happen." << endl;
977 else
978 delete mapPlayers[playerId];
979
980 break;
981 }
982 case MSG_TYPE_PLAYER_JOIN_GAME:
983 {
984 cout << "Received MSG_TYPE_PLAYER_JOIN_GAME" << endl;
985
986 Player p("", "");
987 p.deserialize(msg.buffer);
988 cout << "Deserialized player" << endl;
989 p.timeLastUpdated = getCurrentMillis();
990 p.isChasing = false;
991 if (p.health <= 0)
992 p.isDead = true;
993 else
994 p.isDead = false;
995
996 if (mapPlayers.find(p.getId()) != mapPlayers.end())
997 *(mapPlayers[p.getId()]) = p;
998 else
999 mapPlayers[p.getId()] = new Player(p);
1000
1001 game->addPlayer(mapPlayers[p.getId()]);
1002
1003 break;
1004 }
1005 case MSG_TYPE_LEAVE_GAME:
1006 {
1007 cout << "Received a LEAVE_GAME message" << endl;
1008
1009 string gameName(msg.buffer+4);
1010 unsigned int playerId;
1011
1012 memcpy(&playerId, msg.buffer, 4);
1013
1014 game->removePlayer(playerId);
1015
1016 break;
1017 }
1018 case MSG_TYPE_PLAYER_MOVE:
1019 {
1020 cout << "Received PLAYER_MOVE message" << endl;
1021
1022 unsigned int id;
1023 int x, y;
1024
1025 memcpy(&id, msg.buffer, 4);
1026 memcpy(&x, msg.buffer+4, 4);
1027 memcpy(&y, msg.buffer+8, 4);
1028
1029 cout << "id: " << id << endl;
1030
1031 mapPlayers[id]->target.x = x;
1032 mapPlayers[id]->target.y = y;
1033
1034 mapPlayers[id]->isChasing = false;
1035 mapPlayers[id]->setTargetPlayer(0);
1036
1037 break;
1038 }
1039 case MSG_TYPE_OBJECT:
1040 {
1041 cout << "Received object message in STATE_GAME" << endl;
1042
1043 WorldMap::Object o(0, OBJECT_NONE, 0, 0);
1044 o.deserialize(msg.buffer);
1045 cout << "object id: " << o.id << endl;
1046 game->getMap()->updateObject(o.id, o.type, o.pos.x, o.pos.y);
1047
1048 break;
1049 }
1050 case MSG_TYPE_REMOVE_OBJECT:
1051 {
1052 cout << "Received REMOVE_OBJECT message!" << endl;
1053
1054 int id;
1055 memcpy(&id, msg.buffer, 4);
1056
1057 cout << "Removing object with id " << id << endl;
1058
1059 if (!game->getMap()->removeObject(id))
1060 cout << "Did not remove the object" << endl;
1061
1062 break;
1063 }
1064 case MSG_TYPE_ATTACK:
1065 {
1066 cout << "Received START_ATTACK message" << endl;
1067
1068 unsigned int id, targetId;
1069 memcpy(&id, msg.buffer, 4);
1070 memcpy(&targetId, msg.buffer+4, 4);
1071
1072 cout << "source id: " << id << endl;
1073 cout << "target id: " << targetId << endl;
1074
1075 // need to check the target exists in the current game
1076 Player* source = game->getPlayers()[id];
1077 source->setTargetPlayer(targetId);
1078 source->isChasing = true;
1079
1080 break;
1081 }
1082 case MSG_TYPE_PROJECTILE:
1083 {
1084 cout << "Received a PROJECTILE message" << endl;
1085
1086 unsigned int projId, x, y, targetId;
1087
1088 memcpy(&projId, msg.buffer, 4);
1089 memcpy(&x, msg.buffer+4, 4);
1090 memcpy(&y, msg.buffer+8, 4);
1091 memcpy(&targetId, msg.buffer+12, 4);
1092
1093 cout << "projId: " << projId << endl;
1094 cout << "x: " << x << endl;
1095 cout << "y: " << y << endl;
1096 cout << "Target: " << targetId << endl;
1097
1098 Projectile proj(x, y, targetId, 0);
1099 proj.setId(projId);
1100
1101 game->addProjectile(proj);
1102
1103 break;
1104 }
1105 case MSG_TYPE_REMOVE_PROJECTILE:
1106 {
1107 cout << "Received a REMOVE_PROJECTILE message" << endl;
1108
1109 unsigned int id;
1110 memcpy(&id, msg.buffer, 4);
1111
1112 game->removeProjectile(id);
1113
1114 break;
1115 }
1116 default:
1117 {
1118 cout << "Received invalid message of type " << msg.type << endl;
1119
1120 break;
1121 }
1122 }
1123
1124 break;
1125 }
1126 default:
1127 {
1128 cout << "The state has an invalid value: " << state << endl;
1129
1130 break;
1131 }
1132 }
1133}
1134
1135int getRefreshRate(int width, int height)
1136{
1137 int numRefreshRates = al_get_num_display_modes();
1138 ALLEGRO_DISPLAY_MODE displayMode;
1139
1140 for(int i=0; i<numRefreshRates; i++) {
1141 al_get_display_mode(i, &displayMode);
1142
1143 if (displayMode.width == width && displayMode.height == height)
1144 return displayMode.refresh_rate;
1145 }
1146
1147 return 0;
1148}
1149
1150void drawMessageStatus(ALLEGRO_FONT* font)
1151{
1152 int clientMsgOffset = 5;
1153 int serverMsgOffset = 950;
1154
1155 al_draw_text(font, al_map_rgb(0, 255, 255), 0+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "ID");
1156 al_draw_text(font, al_map_rgb(0, 255, 255), 20+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "Type");
1157 al_draw_text(font, al_map_rgb(0, 255, 255), 240+clientMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "Acked?");
1158
1159 //al_draw_text(font, al_map_rgb(0, 255, 255), serverMsgOffset, 43, ALLEGRO_ALIGN_LEFT, "ID");
1160
1161 map<unsigned int, map<unsigned long, MessageContainer> >& sentMessages = msgProcessor.getSentMessages();
1162 int id, type;
1163 bool acked;
1164 ostringstream ossId, ossAcked;
1165
1166 map<unsigned int, map<unsigned long, MessageContainer> >::iterator it;
1167
1168 int msgCount = 0;
1169 for (it = sentMessages.begin(); it != sentMessages.end(); it++) {
1170 map<unsigned long, MessageContainer> playerMessage = it->second;
1171 map<unsigned long, MessageContainer>::iterator it2;
1172 for (it2 = playerMessage.begin(); it2 != playerMessage.end(); it2++) {
1173
1174 id = it->first;
1175 ossId.str("");;
1176 ossId << id;
1177
1178 type = it2->second.getMessage()->type;
1179 string typeStr = MessageContainer::getMsgTypeString(type);
1180
1181 acked = it2->second.getAcked();
1182 ossAcked.str("");;
1183 ossAcked << boolalpha << acked;
1184
1185 al_draw_text(font, al_map_rgb(0, 255, 0), clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossId.str().c_str());
1186 al_draw_text(font, al_map_rgb(0, 255, 0), 20+clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, typeStr.c_str());
1187 al_draw_text(font, al_map_rgb(0, 255, 0), 240+clientMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossAcked.str().c_str());
1188
1189 msgCount++;
1190 }
1191 }
1192
1193 if (msgProcessor.getAckedMessages().size() > 0) {
1194 map<unsigned int, unsigned long long> ackedMessages = msgProcessor.getAckedMessages()[0];
1195 map<unsigned int, unsigned long long>::iterator it3;
1196
1197 msgCount = 0;
1198 for (it3 = ackedMessages.begin(); it3 != ackedMessages.end(); it3++) {
1199 ossId.str("");;
1200 ossId << it3->first;
1201
1202 al_draw_text(font, al_map_rgb(255, 0, 0), 25+serverMsgOffset, 60+15*msgCount, ALLEGRO_ALIGN_LEFT, ossId.str().c_str());
1203
1204 msgCount++;
1205 }
1206 }
1207}
1208
1209// Callback definitions
1210
1211void goToRegisterScreen()
1212{
1213 txtUsernameRegister->clear();
1214 txtPasswordRegister->clear();
1215 lblRegisterStatus->setText("");
1216 rblClasses->setSelectedButton(-1);
1217
1218 wndCurrent = wndRegister;
1219}
1220
1221void goToLoginScreen()
1222{
1223 txtUsername->clear();
1224 txtPassword->clear();
1225 lblLoginStatus->setText("");
1226
1227 wndCurrent = wndLogin;
1228}
1229
1230// maybe need a goToGameScreen function as well and add state changes to these functions as well
1231
1232void registerAccount()
1233{
1234 string username = txtUsernameRegister->getStr();
1235 string password = txtPasswordRegister->getStr();
1236
1237 txtUsernameRegister->clear();
1238 txtPasswordRegister->clear();
1239 // maybe clear rblClasses as well (add a method to RadioButtonList to enable this)
1240
1241 Player::PlayerClass playerClass;
1242
1243 switch (rblClasses->getSelectedButton()) {
1244 case 0:
1245 playerClass = Player::CLASS_WARRIOR;
1246 break;
1247 case 1:
1248 playerClass = Player::CLASS_RANGER;
1249 break;
1250 default:
1251 cout << "Invalid class selection" << endl;
1252 playerClass = Player::CLASS_NONE;
1253 break;
1254 }
1255
1256 msgTo.type = MSG_TYPE_REGISTER;
1257
1258 strcpy(msgTo.buffer, username.c_str());
1259 strcpy(msgTo.buffer+username.size()+1, password.c_str());
1260 memcpy(msgTo.buffer+username.size()+password.size()+2, &playerClass, 4);
1261
1262 msgProcessor.sendMessage(&msgTo, &server);
1263}
1264
1265void login()
1266{
1267 string strUsername = txtUsername->getStr();
1268 string strPassword = txtPassword->getStr();
1269 username = strUsername;
1270
1271 txtUsername->clear();
1272 txtPassword->clear();
1273
1274 msgTo.type = MSG_TYPE_LOGIN;
1275
1276 strcpy(msgTo.buffer, strUsername.c_str());
1277 strcpy(msgTo.buffer+username.size()+1, strPassword.c_str());
1278
1279 msgProcessor.sendMessage(&msgTo, &server);
1280
1281 state = STATE_LOBBY;
1282}
1283
1284void logout()
1285{
1286 switch(state) {
1287 case STATE_LOBBY:
1288 txtJoinGame->clear();
1289 txtCreateGame->clear();
1290 break;
1291 default:
1292 cout << "Logout called from invalid state: " << state << endl;
1293 break;
1294 }
1295
1296 msgTo.type = MSG_TYPE_LOGOUT;
1297
1298 strcpy(msgTo.buffer, username.c_str());
1299
1300 msgProcessor.sendMessage(&msgTo, &server);
1301}
1302
1303void quit()
1304{
1305 doexit = true;
1306}
1307
1308void sendChatMessage()
1309{
1310 string msg = txtChat->getStr();
1311 txtChat->clear();
1312
1313 msgTo.type = MSG_TYPE_CHAT;
1314 strcpy(msgTo.buffer, msg.c_str());
1315
1316 msgProcessor.sendMessage(&msgTo, &server);
1317}
1318
1319void toggleDebugging()
1320{
1321 debugging = !debugging;
1322}
1323
1324void joinGame()
1325{
1326 cout << "Joining game" << endl;
1327
1328 string msg = txtJoinGame->getStr();
1329 txtJoinGame->clear();
1330
1331 msgTo.type = MSG_TYPE_JOIN_GAME;
1332 strcpy(msgTo.buffer, msg.c_str());
1333
1334 msgProcessor.sendMessage(&msgTo, &server);
1335}
1336
1337void createGame()
1338{
1339 cout << "Creating game" << endl;
1340
1341 string msg = txtCreateGame->getStr();
1342 txtCreateGame->clear();
1343
1344 cout << "Sending message: " << msg.c_str() << endl;
1345
1346 msgTo.type = MSG_TYPE_CREATE_GAME;
1347 strcpy(msgTo.buffer, msg.c_str());
1348
1349 msgProcessor.sendMessage(&msgTo, &server);
1350}
1351
1352void leaveGame()
1353{
1354 cout << "Leaving game" << endl;
1355
1356 game = NULL;
1357
1358 state = STATE_LOBBY;
1359 wndCurrent = wndLobby;
1360
1361 msgTo.type = MSG_TYPE_LEAVE_GAME;
1362
1363 msgProcessor.sendMessage(&msgTo, &server);
1364}
1365
1366void closeGameSummary()
1367{
1368 delete gameSummary;
1369 gameSummary = NULL;
1370 wndCurrent = wndLobby;
1371 cout << "Processed button actions" << endl;
1372}
Note: See TracBrowser for help on using the repository browser.