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

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

Clients store the total number of players in each game

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