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

Last change on this file since a9e808e was 0b6f9ec, checked in by Dmitry Portnoy <dmp1488@…>, 11 years ago

Very minor client changes

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