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

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

Resolved a bug where objects with duplicate ids were getting created

  • Property mode set to 100644
File size: 18.9 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, WorldMap *gameMap, 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 else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
232 }
233 else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
234 switch(ev.keyboard.keycode) {
235 case ALLEGRO_KEY_ESCAPE:
236 doexit = true;
237 break;
238 case ALLEGRO_KEY_D: // drop the current item
239 if (state == STATE_LOGIN) {
240 map<unsigned int, Player>::iterator it;
241 Player* p = NULL;
242 for(it = mapPlayers.begin(); it != mapPlayers.end(); it++)
243 {
244 &it->second;
245 if (it->second.id == curPlayerId)
246 p = &it->second;
247 }
248
249 if (p != NULL) {
250 int flagType = WorldMap::OBJECT_NONE;
251
252 if (p->hasBlueFlag)
253 flagType = WorldMap::OBJECT_BLUE_FLAG;
254 else if (p->hasRedFlag)
255 flagType = WorldMap::OBJECT_RED_FLAG;
256
257 if (flagType != WorldMap::OBJECT_NONE) {
258 msgTo.type = MSG_TYPE_DROP_FLAG;
259 memcpy(msgTo.buffer, &curPlayerId, 4);
260 sendMessage(&msgTo, sock, &server);
261 }
262 }
263 }
264 break;
265 }
266 }
267 else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
268 if(wndCurrent == wndMain) {
269 msgTo.type = MSG_TYPE_PLAYER_MOVE;
270
271 POSITION pos;
272 pos.x = ev.mouse.x;
273 pos.y = ev.mouse.y;
274 pos = screenToMap(pos);
275
276 if (pos.x != -1)
277 {
278 memcpy(msgTo.buffer, &curPlayerId, 4);
279 memcpy(msgTo.buffer+4, &pos.x, 4);
280 memcpy(msgTo.buffer+8, &pos.y, 4);
281
282 sendMessage(&msgTo, sock, &server);
283 }
284 else
285 cout << "Invalid point: User did not click on the map" << endl;
286 }
287 }
288
289 if (receiveMessage(&msgFrom, sock, &from) >= 0)
290 processMessage(msgFrom, state, chatConsole, gameMap, mapPlayers, curPlayerId);
291
292 if (redraw)
293 {
294 redraw = false;
295
296 wndCurrent->draw(display);
297
298 chatConsole.draw(font, al_map_rgb(255,255,255));
299
300 if(wndCurrent == wndLogin) {
301 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 43, ALLEGRO_ALIGN_LEFT, "Username:");
302 al_draw_text(font, al_map_rgb(0, 255, 0), 1, 73, ALLEGRO_ALIGN_LEFT, "Password:");
303 }
304 else if(wndCurrent == wndMain) {
305 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 43, ALLEGRO_ALIGN_LEFT, "Message:");
306
307 // update player positions
308 map<unsigned int, Player>::iterator it;
309 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
310 {
311 it->second.move(gameMap); // ignore return value
312 }
313
314 drawMap(gameMap);
315 drawPlayers(mapPlayers, curPlayerId);
316 }
317
318 al_flip_display();
319 }
320 }
321
322 #if defined WINDOWS
323 closesocket(sock);
324 #elif defined LINUX
325 close(sock);
326 #endif
327
328 shutdownWinSock();
329
330 delete wndLogin;
331 delete wndMain;
332
333 delete gameMap;
334
335 al_destroy_event_queue(event_queue);
336 al_destroy_display(display);
337 al_destroy_timer(timer);
338
339 return 0;
340}
341
342// need to make a function like this that works on windows
343void error(const char *msg)
344{
345 perror(msg);
346 shutdownWinSock();
347 exit(1);
348}
349
350void initWinSock()
351{
352#if defined WINDOWS
353 WORD wVersionRequested;
354 WSADATA wsaData;
355 int wsaerr;
356
357 wVersionRequested = MAKEWORD(2, 2);
358 wsaerr = WSAStartup(wVersionRequested, &wsaData);
359
360 if (wsaerr != 0) {
361 cout << "The Winsock dll not found." << endl;
362 exit(1);
363 }else
364 cout << "The Winsock dll was found." << endl;
365#endif
366}
367
368void shutdownWinSock()
369{
370#if defined WINDOWS
371 WSACleanup();
372#endif
373}
374
375POSITION screenToMap(POSITION pos)
376{
377 pos.x = pos.x-300;
378 pos.y = pos.y-100;
379
380 if (pos.x < 0 || pos.y < 0)
381 {
382 pos.x = -1;
383 pos.y = -1;
384 }
385
386 return pos;
387}
388
389POSITION mapToScreen(POSITION pos)
390{
391 pos.x = pos.x+300;
392 pos.y = pos.y+100;
393
394 return pos;
395}
396
397POSITION mapToScreen(FLOAT_POSITION pos)
398{
399 POSITION p;
400 p.x = pos.x+300;
401 p.y = pos.y+100;
402
403 return p;
404}
405
406void processMessage(NETWORK_MSG &msg, int &state, chat &chatConsole, WorldMap *gameMap, map<unsigned int, Player>& mapPlayers, unsigned int& curPlayerId)
407{
408 string response = string(msg.buffer);
409
410 cout << "Processing message" << endl;
411
412 switch(state)
413 {
414 case STATE_START:
415 {
416 cout << "In STATE_START" << endl;
417
418 switch(msg.type)
419 {
420 case MSG_TYPE_REGISTER:
421 {
422 break;
423 }
424 case MSG_TYPE_LOGIN:
425 {
426 if (response.compare("Player has already logged in.") == 0)
427 {
428 username.clear();
429 cout << "User login failed" << endl;
430 }
431 else if (response.compare("Incorrect username or password") == 0)
432 {
433 username.clear();
434 cout << "User login failed" << endl;
435 }
436 else
437 {
438 state = STATE_LOGIN;
439 wndCurrent = wndMain;
440
441 Player p("", "");
442 p.deserialize(msg.buffer);
443 mapPlayers[p.id] = p;
444 curPlayerId = p.id;
445
446 cout << "Got a valid login response with the player" << endl;
447 cout << "Player id: " << curPlayerId << endl;
448 cout << "map size: " << mapPlayers.size() << endl;
449 }
450
451 break;
452 }
453 case MSG_TYPE_PLAYER: // kind of hacky to put this here
454 {
455 cout << "Got MSG_TYPE_PLAYER message in STATE_START" << endl;
456
457 Player p("", "");
458 p.deserialize(msg.buffer);
459 p.timeLastUpdated = getCurrentMillis();
460 mapPlayers[p.id] = p;
461
462 cout << "new player id: " << p.id << endl;
463 cout << "map size: " << mapPlayers.size() << endl;
464
465 break;
466 }
467 case MSG_TYPE_OBJECT:
468 {
469 cout << "Received OBJECT message in STATE_START." << endl;
470
471 WorldMap::Object o(0, WorldMap::OBJECT_NONE, 0, 0);
472 o.deserialize(msg.buffer);
473 cout << "object id: " << o.id << endl;
474 gameMap->updateObject(o.id, o.type, o.pos.x, o.pos.y);
475
476 break;
477 }
478 }
479
480 break;
481 }
482 case STATE_LOGIN:
483 {
484 switch(msg.type)
485 {
486 case MSG_TYPE_REGISTER:
487 {
488 break;
489 }
490 case MSG_TYPE_LOGIN:
491 {
492 cout << "Got a login message" << endl;
493
494 chatConsole.addLine(response);
495 cout << "Added new line" << endl;
496
497 break;
498 }
499 case MSG_TYPE_LOGOUT:
500 {
501 cout << "Got a logout message" << endl;
502
503 if (response.compare("You have successfully logged out.") == 0)
504 {
505 cout << "Logged out" << endl;
506 state = STATE_START;
507 wndCurrent = wndLogin;
508 }
509
510 break;
511 }
512 case MSG_TYPE_PLAYER:
513 {
514 cout << "Got MSG_TYPE_PLAYER message in STATE_LOGIN" << endl;
515
516 Player p("", "");
517 p.deserialize(msg.buffer);
518 p.timeLastUpdated = getCurrentMillis();
519 mapPlayers[p.id] = p;
520
521 break;
522 }
523 case MSG_TYPE_PLAYER_MOVE:
524 {
525 cout << "Got a player move message" << endl;
526
527 unsigned int id;
528 int x, y;
529
530 memcpy(&id, msg.buffer, 4);
531 memcpy(&x, msg.buffer+4, 4);
532 memcpy(&y, msg.buffer+8, 4);
533
534 mapPlayers[id].target.x = x;
535 mapPlayers[id].target.y = y;
536
537 break;
538 }
539 case MSG_TYPE_CHAT:
540 {
541 chatConsole.addLine(response);
542
543 break;
544 }
545 case MSG_TYPE_OBJECT:
546 {
547 cout << "Received object message in STATE_LOGIN." << endl;
548
549 WorldMap::Object o(0, WorldMap::OBJECT_NONE, 0, 0);
550 o.deserialize(msg.buffer);
551 gameMap->updateObject(o.id, o.type, o.pos.x, o.pos.y);
552
553 break;
554 }
555 case MSG_TYPE_REMOVE_OBJECT:
556 {
557 cout << "Received REMOVE_OBJECT message!" << endl;
558
559 int id;
560 memcpy(&id, msg.buffer, 4);
561
562 cout << "Removing object with id " << id << endl;
563
564 if (!gameMap->removeObject(id))
565 cout << "Did not remove the object" << endl;
566
567 break;
568 }
569 default:
570 {
571 cout << "Received an unexpected message type: " << msg.type << endl;
572 }
573 }
574
575 break;
576 }
577 default:
578 {
579 cout << "The state has an invalid value: " << state << endl;
580
581 break;
582 }
583 }
584}
585
586// this should probably be in the WorldMap class
587void drawMap(WorldMap* gameMap)
588{
589 POSITION mapPos;
590 mapPos.x = 0;
591 mapPos.y = 0;
592 mapPos = mapToScreen(mapPos);
593
594 for (int x=0; x<12; x++)
595 {
596 for (int y=0; y<12; y++)
597 {
598 WorldMap::TerrainType el = gameMap->getElement(x, y);
599 WorldMap::StructureType structure = gameMap->getStructure(x, y);
600
601 if (el == WorldMap::TERRAIN_GRASS)
602 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));
603 else if (el == WorldMap::TERRAIN_OCEAN)
604 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));
605 else if (el == WorldMap::TERRAIN_ROCK)
606 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));
607
608 if (structure == WorldMap::STRUCTURE_BLUE_FLAG) {
609 al_draw_circle(x*25+12+mapPos.x, y*25+12+mapPos.y, 12, al_map_rgb(0, 0, 0), 3);
610 //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));
611 }else if (structure == WorldMap::STRUCTURE_RED_FLAG) {
612 al_draw_circle(x*25+12+mapPos.x, y*25+12+mapPos.y, 12, al_map_rgb(0, 0, 0), 3);
613 //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));
614 }
615 }
616 }
617
618 for (int x=0; x<12; x++)
619 {
620 for (int y=0; y<12; y++)
621 {
622 vector<WorldMap::Object> vctObjects = gameMap->getObjects(x, y);
623
624 vector<WorldMap::Object>::iterator it;
625 for(it = vctObjects.begin(); it != vctObjects.end(); it++) {
626 switch(it->type) {
627 case WorldMap::OBJECT_BLUE_FLAG:
628 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));
629 break;
630 case WorldMap::OBJECT_RED_FLAG:
631 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));
632 break;
633 }
634 }
635 }
636 }
637}
638
639void drawPlayers(map<unsigned int, Player>& mapPlayers, unsigned int curPlayerId)
640{
641 map<unsigned int, Player>::iterator it;
642
643 Player* p;
644 POSITION pos;
645
646 for(it = mapPlayers.begin(); it != mapPlayers.end(); it++)
647 {
648 p = &it->second;
649 pos = mapToScreen(p->pos);
650
651 if (p->id == curPlayerId)
652 al_draw_filled_circle(pos.x, pos.y, 12, al_map_rgb(255, 0, 0));
653 else
654 al_draw_filled_circle(pos.x, pos.y, 12, al_map_rgb(191, 0, 0));
655
656 if (p->hasBlueFlag)
657 al_draw_filled_rectangle(pos.x+4, pos.y-18, pos.x+18, pos.y-4, al_map_rgb(0, 0, 255));
658 else if(p->hasRedFlag)
659 al_draw_filled_rectangle(pos.x+4, pos.y-18, pos.x+18, pos.y-4, al_map_rgb(255, 0, 0));
660 }
661}
662
663void registerAccount()
664{
665 string username = txtUsername->getStr();
666 string password = txtPassword->getStr();
667
668 txtUsername->clear();
669 txtPassword->clear();
670
671 msgTo.type = MSG_TYPE_REGISTER;
672
673 strcpy(msgTo.buffer, username.c_str());
674 strcpy(msgTo.buffer+username.size()+1, password.c_str());
675
676 sendMessage(&msgTo, sock, &server);
677}
678
679void login()
680{
681 string strUsername = txtUsername->getStr();
682 string strPassword = txtPassword->getStr();
683 username = strUsername;
684
685 txtUsername->clear();
686 txtPassword->clear();
687
688 msgTo.type = MSG_TYPE_LOGIN;
689
690 strcpy(msgTo.buffer, strUsername.c_str());
691 strcpy(msgTo.buffer+username.size()+1, strPassword.c_str());
692
693 sendMessage(&msgTo, sock, &server);
694}
695
696void logout()
697{
698 txtChat->clear();
699
700 msgTo.type = MSG_TYPE_LOGOUT;
701
702 strcpy(msgTo.buffer, username.c_str());
703
704 sendMessage(&msgTo, sock, &server);
705}
706
707void quit()
708{
709 doexit = true;
710}
711
712void sendChatMessage()
713{
714 string msg = txtChat->getStr();
715
716 txtChat->clear();
717
718 msgTo.type = MSG_TYPE_CHAT;
719
720 strcpy(msgTo.buffer, msg.c_str());
721
722 sendMessage(&msgTo, sock, &server);
723}
Note: See TracBrowser for help on using the repository browser.