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

Last change on this file since 3ea1839 was 34bd549, checked in by Dmitry Portnoy <dmp1488@…>, 10 years ago

Make client compile on a Mac

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