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

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

Merge branch 'master' of github.com:weretaco/network-game

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