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

Last change on this file since 3ef8cf4 was 03ba5e3, checked in by Dmitry Portnoy <dportnoy@…>, 11 years ago

Added a NEW_GAME screen with a button to leave the game and return to the lobby

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