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

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

The client draws the map and players in individual games

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