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

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

Removed the draw method from the Player class to avoid an allegro dependency on the server

  • Property mode set to 100644
File size: 15.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 <sys/types.h>
16#include <cstdio>
17#include <cstdlib>
18#include <string>
19#include <iostream>
20#include <sstream>
21
22#include <map>
23
24#include <map>
25
26#include <allegro5/allegro.h>
27#include <allegro5/allegro_font.h>
28#include <allegro5/allegro_ttf.h>
29#include <allegro5/allegro_primitives.h>
30
31#include "../../common/Message.h"
32#include "../../common/Common.h"
33#include "../../common/WorldMap.h"
34#include "../../common/Player.h"
35
36#include "Window.h"
37#include "Textbox.h"
38#include "Button.h"
39#include "chat.h"
40
41#ifdef WINDOWS
42 #pragma comment(lib, "ws2_32.lib")
43#endif
44
45using namespace std;
46
47void initWinSock();
48void shutdownWinSock();
49void processMessage(NETWORK_MSG &msg, int &state, chat &chatConsole, map<unsigned int, Player>& mapPlayers, unsigned int& curPlayerId);
50void drawMap(WorldMap* gameMap);
51void drawPlayers(map<unsigned int, Player>& mapPlayers, unsigned int curPlayerId);
52POSITION screenToMap(POSITION pos);
53POSITION mapToScreen(POSITION pos);
54
55// callbacks
56void registerAccount();
57void login();
58void logout();
59void quit();
60void sendChatMessage();
61
62void error(const char *);
63
64const float FPS = 60;
65const int SCREEN_W = 640;
66const int SCREEN_H = 480;
67
68enum STATE {
69 STATE_START,
70 STATE_LOGIN // this means you're already logged in
71};
72
73int state;
74
75bool doexit;
76
77Window* wndLogin;
78Window* wndMain;
79Window* wndCurrent;
80
81Textbox* txtUsername;
82Textbox* txtPassword;
83Textbox* txtChat;
84
85int sock;
86struct sockaddr_in server, from;
87struct hostent *hp;
88NETWORK_MSG msgTo, msgFrom;
89string username;
90chat chatConsole;
91
92int main(int argc, char **argv)
93{
94 ALLEGRO_DISPLAY *display = NULL;
95 ALLEGRO_EVENT_QUEUE *event_queue = NULL;
96 ALLEGRO_TIMER *timer = NULL;
97 bool key[4] = { false, false, false, false };
98 bool redraw = true;
99 doexit = false;
100 map<unsigned int, Player> mapPlayers;
101 unsigned int curPlayerId = -1;
102
103 state = STATE_START;
104
105 if(!al_init()) {
106 fprintf(stderr, "failed to initialize allegro!\n");
107 return -1;
108 }
109
110 if (al_init_primitives_addon())
111 cout << "Primitives initialized" << endl;
112 else
113 cout << "Primitives not initialized" << endl;
114
115 al_init_font_addon();
116 al_init_ttf_addon();
117
118 #if defined WINDOWS
119 ALLEGRO_FONT *font = al_load_ttf_font("../pirulen.ttf", 12, 0);
120 #elif defined LINUX
121 ALLEGRO_FONT *font = al_load_ttf_font("pirulen.ttf", 12, 0);
122 #endif
123
124 if (!font) {
125 fprintf(stderr, "Could not load 'pirulen.ttf'.\n");
126 getchar();
127 return -1;
128 }
129
130 if(!al_install_keyboard()) {
131 fprintf(stderr, "failed to initialize the keyboard!\n");
132 return -1;
133 }
134
135 if(!al_install_mouse()) {
136 fprintf(stderr, "failed to initialize the mouse!\n");
137 return -1;
138 }
139
140 timer = al_create_timer(1.0 / FPS);
141 if(!timer) {
142 fprintf(stderr, "failed to create timer!\n");
143 return -1;
144 }
145
146 display = al_create_display(SCREEN_W, SCREEN_H);
147 if(!display) {
148 fprintf(stderr, "failed to create display!\n");
149 al_destroy_timer(timer);
150 return -1;
151 }
152
153 WorldMap* gameMap = WorldMap::loadMapFromFile("../../data/map.txt");
154
155 wndLogin = new Window(0, 0, SCREEN_W, SCREEN_H);
156 wndLogin->addComponent(new Textbox(104, 40, 100, 20, font));
157 wndLogin->addComponent(new Textbox(104, 70, 100, 20, font));
158 wndLogin->addComponent(new Button(22, 100, 90, 20, font, "Register", registerAccount));
159 wndLogin->addComponent(new Button(122, 100, 60, 20, font, "Login", login));
160 wndLogin->addComponent(new Button(540, 10, 80, 20, font, "Quit", quit));
161
162 txtUsername = (Textbox*)wndLogin->getComponent(0);
163 txtPassword = (Textbox*)wndLogin->getComponent(1);
164
165 wndMain = new Window(0, 0, SCREEN_W, SCREEN_H);
166 wndMain->addComponent(new Textbox(95, 40, 525, 20, font));
167 wndMain->addComponent(new Button(95, 70, 160, 20, font, "Send Message", sendChatMessage));
168 wndMain->addComponent(new Button(540, 10, 80, 20, font, "Logout", logout));
169
170 txtChat = (Textbox*)wndMain->getComponent(0);
171
172 wndCurrent = wndLogin;
173
174 event_queue = al_create_event_queue();
175 if(!event_queue) {
176 fprintf(stderr, "failed to create event_queue!\n");
177 al_destroy_display(display);
178 al_destroy_timer(timer);
179 return -1;
180 }
181
182 al_set_target_bitmap(al_get_backbuffer(display));
183
184 al_register_event_source(event_queue, al_get_display_event_source(display));
185 al_register_event_source(event_queue, al_get_timer_event_source(timer));
186 al_register_event_source(event_queue, al_get_keyboard_event_source());
187 al_register_event_source(event_queue, al_get_mouse_event_source());
188
189 al_clear_to_color(al_map_rgb(0,0,0));
190
191 al_flip_display();
192
193 if (argc != 3) {
194 cout << "Usage: server port" << endl;
195 exit(1);
196 }
197
198 initWinSock();
199
200 sock = socket(AF_INET, SOCK_DGRAM, 0);
201 if (sock < 0)
202 error("socket");
203
204 set_nonblock(sock);
205
206 server.sin_family = AF_INET;
207 hp = gethostbyname(argv[1]);
208 if (hp==0)
209 error("Unknown host");
210
211 memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);
212 server.sin_port = htons(atoi(argv[2]));
213
214 al_start_timer(timer);
215
216 while(!doexit)
217 {
218 ALLEGRO_EVENT ev;
219
220 al_wait_for_event(event_queue, &ev);
221
222 if(wndCurrent->handleEvent(ev)) {
223 // do nothing
224 }
225 else if(ev.type == ALLEGRO_EVENT_TIMER) {
226 redraw = true; // seems like we should just call a draw function here instead
227 }
228 else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
229 doexit = true;
230
231 // perform a check to see if it's time to send an update to the server
232 // need to store num ticks since the lst update for this
233 // also check how often each update actually happens and how much it deviates from 60 times per second
234 }
235 else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
236 }
237 else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
238 switch(ev.keyboard.keycode) {
239 case ALLEGRO_KEY_ESCAPE:
240 doexit = true;
241 break;
242 }
243 }
244 else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
245 if(wndCurrent == wndMain) {
246 msgTo.type = MSG_TYPE_PLAYER_MOVE;
247
248 POSITION pos;
249 pos.x = ev.mouse.x;
250 pos.y = ev.mouse.y;
251 pos = screenToMap(pos);
252
253 if (pos.x != -1)
254 {
255 memcpy(msgTo.buffer, &curPlayerId, 4);
256 memcpy(msgTo.buffer+4, &pos.x, 4);
257 memcpy(msgTo.buffer+8, &pos.y, 4);
258
259 sendMessage(&msgTo, sock, &server);
260 }
261 else
262 cout << "Invalid point: User did not click on the map" << endl;
263 }
264 }
265
266 if (receiveMessage(&msgFrom, sock, &from) >= 0)
267 processMessage(msgFrom, state, chatConsole, mapPlayers, curPlayerId);
268
269 if (redraw)
270 {
271 redraw = false;
272
273 wndCurrent->draw(display);
274
275 chatConsole.draw(font, al_map_rgb(255,255,255));
276
277 if(wndCurrent == wndLogin) {
278 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 43, ALLEGRO_ALIGN_LEFT, "Username:");
279 al_draw_text(font, al_map_rgb(0, 255, 0), 1, 73, ALLEGRO_ALIGN_LEFT, "Password:");
280 }
281 else if(wndCurrent == wndMain) {
282 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 43, ALLEGRO_ALIGN_LEFT, "Message:");
283
284 // update player positions
285 map<unsigned int, Player>::iterator it;
286 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
287 {
288 it->second.move(gameMap); // ignore return value
289 }
290
291 drawMap(gameMap);
292 drawPlayers(mapPlayers, curPlayerId);
293 }
294
295 al_flip_display();
296 }
297 }
298
299 #if defined WINDOWS
300 closesocket(sock);
301 #elif defined LINUX
302 close(sock);
303 #endif
304
305 shutdownWinSock();
306
307 delete wndLogin;
308 delete wndMain;
309
310 delete gameMap;
311
312 al_destroy_event_queue(event_queue);
313 al_destroy_display(display);
314 al_destroy_timer(timer);
315
316 return 0;
317}
318
319// need to make a function like this that works on windows
320void error(const char *msg)
321{
322 perror(msg);
323 shutdownWinSock();
324 exit(1);
325}
326
327void initWinSock()
328{
329#if defined WINDOWS
330 WORD wVersionRequested;
331 WSADATA wsaData;
332 int wsaerr;
333
334 wVersionRequested = MAKEWORD(2, 2);
335 wsaerr = WSAStartup(wVersionRequested, &wsaData);
336
337 if (wsaerr != 0) {
338 cout << "The Winsock dll not found." << endl;
339 exit(1);
340 }else
341 cout << "The Winsock dll was found." << endl;
342#endif
343}
344
345void shutdownWinSock()
346{
347#if defined WINDOWS
348 WSACleanup();
349#endif
350}
351
352POSITION screenToMap(POSITION pos)
353{
354 pos.x = pos.x-300;
355 pos.y = pos.y-100;
356
357 if (pos.x < 0 || pos.y < 0)
358 {
359 pos.x = -1;
360 pos.y = -1;
361 }
362
363 return pos;
364}
365
366POSITION mapToScreen(POSITION pos)
367{
368 pos.x = pos.x+300;
369 pos.y = pos.y+100;
370
371 return pos;
372}
373
374POSITION mapToScreen(FLOAT_POSITION pos)
375{
376 POSITION p;
377 p.x = pos.x+300;
378 p.y = pos.y+100;
379
380 return p;
381}
382
383void processMessage(NETWORK_MSG &msg, int &state, chat &chatConsole, map<unsigned int, Player>& mapPlayers, unsigned int& curPlayerId)
384{
385 string response = string(msg.buffer);
386
387 cout << "Processing message" << endl;
388 cout << response << endl;
389
390 switch(state)
391 {
392 case STATE_START:
393 {
394 cout << "In STATE_START" << endl;
395
396 switch(msg.type)
397 {
398 case MSG_TYPE_REGISTER:
399 {
400 break;
401 }
402 case MSG_TYPE_LOGIN:
403 {
404 if (response.compare("Player has already logged in.") == 0)
405 {
406 username.clear();
407 cout << "User login failed" << endl;
408 }
409 else if (response.compare("Incorrect username or password") == 0)
410 {
411 username.clear();
412 cout << "User login failed" << endl;
413 }
414 else
415 {
416 state = STATE_LOGIN;
417 wndCurrent = wndMain;
418
419 Player p("", "");
420 p.deserialize(msg.buffer);
421 mapPlayers[p.id] = p;
422 curPlayerId = p.id;
423
424 cout << "Got a valid login response with the player" << endl;
425 cout << "Player id: " << curPlayerId << endl;
426 cout << "map size: " << mapPlayers.size() << endl;
427 }
428
429 break;
430 }
431 case MSG_TYPE_PLAYER: // kind of hacky to put this here
432 {
433 cout << "Got MSG_TYPE_PLAYER message in Start" << endl;
434
435 Player p("", "");
436 p.deserialize(msg.buffer);
437 p.timeLastUpdated = getCurrentMillis();
438 mapPlayers[p.id] = p;
439
440 cout << "new player id: " << p.id << endl;
441 cout << "map size: " << mapPlayers.size() << endl;
442
443 break;
444 }
445 }
446
447 break;
448 }
449 case STATE_LOGIN:
450 {
451 switch(msg.type)
452 {
453 case MSG_TYPE_REGISTER:
454 {
455 break;
456 }
457 case MSG_TYPE_LOGIN:
458 {
459 cout << "Got a login message" << endl;
460
461 chatConsole.addLine(response);
462 cout << "Added new line" << endl;
463
464 break;
465 }
466 case MSG_TYPE_LOGOUT:
467 {
468 cout << "Got a logout message" << endl;
469
470 if (response.compare("You have successfully logged out.") == 0)
471 {
472 cout << "Logged out" << endl;
473 state = STATE_START;
474 wndCurrent = wndLogin;
475 }
476
477 break;
478 }
479 case MSG_TYPE_PLAYER:
480 {
481 cout << "Got MSG_TYPE_PLAYER message in Login" << endl;
482
483 Player p("", "");
484 p.deserialize(msg.buffer);
485 p.timeLastUpdated = getCurrentMillis();
486 mapPlayers[p.id] = p;
487
488 break;
489 }
490 case MSG_TYPE_PLAYER_MOVE:
491 {
492 cout << "Got a player move message" << endl;
493
494 unsigned int id;
495 int x, y;
496
497 memcpy(&id, msg.buffer, 4);
498 memcpy(&x, msg.buffer+4, 4);
499 memcpy(&y, msg.buffer+8, 4);
500
501 mapPlayers[id].target.x = x;
502 mapPlayers[id].target.y = y;
503
504 break;
505 }
506 case MSG_TYPE_CHAT:
507 {
508 chatConsole.addLine(response);
509
510 break;
511 }
512 }
513
514 break;
515 }
516 default:
517 {
518 cout << "The state has an invalid value: " << state << endl;
519
520 break;
521 }
522 }
523}
524
525// this should probably be in the WorldMap class
526void drawMap(WorldMap* gameMap)
527{
528 POSITION mapPos;
529 mapPos.x = 0;
530 mapPos.y = 0;
531 mapPos = mapToScreen(mapPos);
532 for (int x=0; x<12; x++)
533 {
534 for (int y=0; y<12; y++)
535 {
536 WorldMap::TerrainType el = gameMap->getElement(x, y);
537 WorldMap::ObjectType obj = gameMap->getObject(x, y);
538
539 if (el == WorldMap::TERRAIN_GRASS)
540 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));
541 else if (el == WorldMap::TERRAIN_OCEAN)
542 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));
543 else if (el == WorldMap::TERRAIN_ROCK)
544 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));
545
546 if (obj == WorldMap::OBJECT_RED_FLAG)
547 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));
548 else if (obj == WorldMap::OBJECT_BLUE_FLAG)
549 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));
550 }
551 }
552}
553
554void drawPlayers(map<unsigned int, Player>& mapPlayers, unsigned int curPlayerId)
555{
556 map<unsigned int, Player>::iterator it;
557
558 Player* p;
559 POSITION pos;
560
561 for(it = mapPlayers.begin(); it != mapPlayers.end(); it++)
562 {
563 p = &it->second;
564 pos = mapToScreen(p->pos);
565
566 if (p->id == curPlayerId)
567 al_draw_filled_circle(pos.x, pos.y, 12, al_map_rgb(255, 0, 0));
568 else
569 al_draw_filled_circle(pos.x, pos.y, 12, al_map_rgb(191, 0, 0));
570
571 if (o->hasBlueFlag)
572 al_draw_filled_rectangle(pos.x+4, pos.y-18, pos.x+18, pos.y-4, al_map_rgb(0, 0, 255));
573 else if(o->hasRedFlag)
574 al_draw_filled_rectangle(pos.x+4, pos.y-18, pos.x+18, pos.y-4, al_map_rgb(255, 0, 0));
575 }
576}
577
578void registerAccount()
579{
580 string username = txtUsername->getStr();
581 string password = txtPassword->getStr();
582
583 txtUsername->clear();
584 txtPassword->clear();
585
586 msgTo.type = MSG_TYPE_REGISTER;
587
588 strcpy(msgTo.buffer, username.c_str());
589 strcpy(msgTo.buffer+username.size()+1, password.c_str());
590
591 sendMessage(&msgTo, sock, &server);
592}
593
594void login()
595{
596 string strUsername = txtUsername->getStr();
597 string strPassword = txtPassword->getStr();
598 username = strUsername;
599
600 txtUsername->clear();
601 txtPassword->clear();
602
603 msgTo.type = MSG_TYPE_LOGIN;
604
605 strcpy(msgTo.buffer, strUsername.c_str());
606 strcpy(msgTo.buffer+username.size()+1, strPassword.c_str());
607
608 sendMessage(&msgTo, sock, &server);
609}
610
611void logout()
612{
613 txtChat->clear();
614
615 msgTo.type = MSG_TYPE_LOGOUT;
616
617 strcpy(msgTo.buffer, username.c_str());
618
619 sendMessage(&msgTo, sock, &server);
620}
621
622void quit()
623{
624 doexit = true;
625}
626
627void sendChatMessage()
628{
629 string msg = txtChat->getStr();
630
631 txtChat->clear();
632
633 msgTo.type = MSG_TYPE_CHAT;
634
635 strcpy(msgTo.buffer, msg.c_str());
636
637 sendMessage(&msgTo, sock, &server);
638}
Note: See TracBrowser for help on using the repository browser.