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

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

The client stores and displays a list of existing games

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