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

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

The lobby has a chat console

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