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

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

The client processes SCORE messages and displays the score

  • Property mode set to 100644
File size: 20.1 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, int &scoreBlue, int &scoreRed);
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 int scoreBlue, scoreRed;
103
104 scoreBlue = 0;
105 scoreRed = 0;
106
107 state = STATE_START;
108
109 if(!al_init()) {
110 fprintf(stderr, "failed to initialize allegro!\n");
111 return -1;
112 }
113
114 if (al_init_primitives_addon())
115 cout << "Primitives initialized" << endl;
116 else
117 cout << "Primitives not initialized" << endl;
118
119 al_init_font_addon();
120 al_init_ttf_addon();
121
122 #if defined WINDOWS
123 ALLEGRO_FONT *font = al_load_ttf_font("../pirulen.ttf", 12, 0);
124 #elif defined LINUX
125 ALLEGRO_FONT *font = al_load_ttf_font("pirulen.ttf", 12, 0);
126 #endif
127
128 if (!font) {
129 fprintf(stderr, "Could not load 'pirulen.ttf'.\n");
130 getchar();
131 return -1;
132 }
133
134 if(!al_install_keyboard()) {
135 fprintf(stderr, "failed to initialize the keyboard!\n");
136 return -1;
137 }
138
139 if(!al_install_mouse()) {
140 fprintf(stderr, "failed to initialize the mouse!\n");
141 return -1;
142 }
143
144 timer = al_create_timer(1.0 / FPS);
145 if(!timer) {
146 fprintf(stderr, "failed to create timer!\n");
147 return -1;
148 }
149
150 display = al_create_display(SCREEN_W, SCREEN_H);
151 if(!display) {
152 fprintf(stderr, "failed to create display!\n");
153 al_destroy_timer(timer);
154 return -1;
155 }
156
157 WorldMap* gameMap = WorldMap::loadMapFromFile("../../data/map.txt");
158
159 wndLogin = new Window(0, 0, SCREEN_W, SCREEN_H);
160 wndLogin->addComponent(new Textbox(104, 40, 100, 20, font));
161 wndLogin->addComponent(new Textbox(104, 70, 100, 20, font));
162 wndLogin->addComponent(new Button(22, 100, 90, 20, font, "Register", registerAccount));
163 wndLogin->addComponent(new Button(122, 100, 60, 20, font, "Login", login));
164 wndLogin->addComponent(new Button(540, 10, 80, 20, font, "Quit", quit));
165
166 txtUsername = (Textbox*)wndLogin->getComponent(0);
167 txtPassword = (Textbox*)wndLogin->getComponent(1);
168
169 wndMain = new Window(0, 0, SCREEN_W, SCREEN_H);
170 wndMain->addComponent(new Textbox(95, 40, 525, 20, font));
171 wndMain->addComponent(new Button(95, 70, 160, 20, font, "Send Message", sendChatMessage));
172 wndMain->addComponent(new Button(540, 10, 80, 20, font, "Logout", logout));
173
174 txtChat = (Textbox*)wndMain->getComponent(0);
175
176 wndCurrent = wndLogin;
177
178 event_queue = al_create_event_queue();
179 if(!event_queue) {
180 fprintf(stderr, "failed to create event_queue!\n");
181 al_destroy_display(display);
182 al_destroy_timer(timer);
183 return -1;
184 }
185
186 al_set_target_bitmap(al_get_backbuffer(display));
187
188 al_register_event_source(event_queue, al_get_display_event_source(display));
189 al_register_event_source(event_queue, al_get_timer_event_source(timer));
190 al_register_event_source(event_queue, al_get_keyboard_event_source());
191 al_register_event_source(event_queue, al_get_mouse_event_source());
192
193 al_clear_to_color(al_map_rgb(0,0,0));
194
195 al_flip_display();
196
197 if (argc != 3) {
198 cout << "Usage: server port" << endl;
199 exit(1);
200 }
201
202 initWinSock();
203
204 sock = socket(AF_INET, SOCK_DGRAM, 0);
205 if (sock < 0)
206 error("socket");
207
208 set_nonblock(sock);
209
210 server.sin_family = AF_INET;
211 hp = gethostbyname(argv[1]);
212 if (hp==0)
213 error("Unknown host");
214
215 memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length);
216 server.sin_port = htons(atoi(argv[2]));
217
218 al_start_timer(timer);
219
220 while(!doexit)
221 {
222 ALLEGRO_EVENT ev;
223
224 al_wait_for_event(event_queue, &ev);
225
226 if(wndCurrent->handleEvent(ev)) {
227 // do nothing
228 }
229 else if(ev.type == ALLEGRO_EVENT_TIMER) {
230 redraw = true; // seems like we should just call a draw function here instead
231 }
232 else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
233 doexit = true;
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 case ALLEGRO_KEY_S: // pickup an item next to you
243 if (state == STATE_LOGIN) {
244 msgTo.type = MSG_TYPE_PICKUP_FLAG;
245 memcpy(msgTo.buffer, &curPlayerId, 4);
246 sendMessage(&msgTo, sock, &server);
247 }
248 break;
249 case ALLEGRO_KEY_D: // drop the current item
250 if (state == STATE_LOGIN) {
251 // find the current player in the player list
252 map<unsigned int, Player>::iterator it;
253 Player* p = NULL;
254 for(it = mapPlayers.begin(); it != mapPlayers.end(); it++)
255 {
256 &it->second;
257 if (it->second.id == curPlayerId)
258 p = &it->second;
259 }
260
261 if (p != NULL) {
262 int flagType = WorldMap::OBJECT_NONE;
263
264 if (p->hasBlueFlag)
265 flagType = WorldMap::OBJECT_BLUE_FLAG;
266 else if (p->hasRedFlag)
267 flagType = WorldMap::OBJECT_RED_FLAG;
268
269 if (flagType != WorldMap::OBJECT_NONE) {
270 msgTo.type = MSG_TYPE_DROP_FLAG;
271 memcpy(msgTo.buffer, &curPlayerId, 4);
272 sendMessage(&msgTo, sock, &server);
273 }
274 }
275 }
276 break;
277 }
278 }
279 else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
280 if(wndCurrent == wndMain) {
281 msgTo.type = MSG_TYPE_PLAYER_MOVE;
282
283 POSITION pos;
284 pos.x = ev.mouse.x;
285 pos.y = ev.mouse.y;
286 pos = screenToMap(pos);
287
288 if (pos.x != -1)
289 {
290 memcpy(msgTo.buffer, &curPlayerId, 4);
291 memcpy(msgTo.buffer+4, &pos.x, 4);
292 memcpy(msgTo.buffer+8, &pos.y, 4);
293
294 sendMessage(&msgTo, sock, &server);
295 }
296 else
297 cout << "Invalid point: User did not click on the map" << endl;
298 }
299 }
300
301 if (receiveMessage(&msgFrom, sock, &from) >= 0)
302 processMessage(msgFrom, state, chatConsole, gameMap, mapPlayers, curPlayerId, scoreBlue, scoreRed);
303
304 if (redraw)
305 {
306 redraw = false;
307
308 wndCurrent->draw(display);
309
310 chatConsole.draw(font, al_map_rgb(255,255,255));
311
312 if(wndCurrent == wndLogin) {
313 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 43, ALLEGRO_ALIGN_LEFT, "Username:");
314 al_draw_text(font, al_map_rgb(0, 255, 0), 1, 73, ALLEGRO_ALIGN_LEFT, "Password:");
315 }
316 else if(wndCurrent == wndMain) {
317 al_draw_text(font, al_map_rgb(0, 255, 0), 4, 43, ALLEGRO_ALIGN_LEFT, "Message:");
318
319 ostringstream ossScoreBlue, ossScoreRed;
320
321 ossScoreBlue << "Blue: " << scoreBlue << endl;
322 ossScoreRed << "Red: " << scoreRed << endl;
323
324 al_draw_text(font, al_map_rgb(0, 255, 0), 330, 80, ALLEGRO_ALIGN_LEFT, ossScoreBlue.str().c_str());
325 al_draw_text(font, al_map_rgb(0, 255, 0), 515, 80, ALLEGRO_ALIGN_LEFT, ossScoreRed.str().c_str());
326
327 // update player positions
328 map<unsigned int, Player>::iterator it;
329 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
330 {
331 it->second.move(gameMap); // ignore return value
332 }
333
334 drawMap(gameMap);
335 drawPlayers(mapPlayers, curPlayerId);
336 }
337
338 al_flip_display();
339 }
340 }
341
342 #if defined WINDOWS
343 closesocket(sock);
344 #elif defined LINUX
345 close(sock);
346 #endif
347
348 shutdownWinSock();
349
350 delete wndLogin;
351 delete wndMain;
352
353 delete gameMap;
354
355 al_destroy_event_queue(event_queue);
356 al_destroy_display(display);
357 al_destroy_timer(timer);
358
359 return 0;
360}
361
362// need to make a function like this that works on windows
363void error(const char *msg)
364{
365 perror(msg);
366 shutdownWinSock();
367 exit(1);
368}
369
370void initWinSock()
371{
372#if defined WINDOWS
373 WORD wVersionRequested;
374 WSADATA wsaData;
375 int wsaerr;
376
377 wVersionRequested = MAKEWORD(2, 2);
378 wsaerr = WSAStartup(wVersionRequested, &wsaData);
379
380 if (wsaerr != 0) {
381 cout << "The Winsock dll not found." << endl;
382 exit(1);
383 }else
384 cout << "The Winsock dll was found." << endl;
385#endif
386}
387
388void shutdownWinSock()
389{
390#if defined WINDOWS
391 WSACleanup();
392#endif
393}
394
395POSITION screenToMap(POSITION pos)
396{
397 pos.x = pos.x-300;
398 pos.y = pos.y-100;
399
400 if (pos.x < 0 || pos.y < 0)
401 {
402 pos.x = -1;
403 pos.y = -1;
404 }
405
406 return pos;
407}
408
409POSITION mapToScreen(POSITION pos)
410{
411 pos.x = pos.x+300;
412 pos.y = pos.y+100;
413
414 return pos;
415}
416
417POSITION mapToScreen(FLOAT_POSITION pos)
418{
419 POSITION p;
420 p.x = pos.x+300;
421 p.y = pos.y+100;
422
423 return p;
424}
425
426void processMessage(NETWORK_MSG &msg, int &state, chat &chatConsole, WorldMap *gameMap, map<unsigned int, Player>& mapPlayers, unsigned int& curPlayerId, int &scoreBlue, int &scoreRed)
427{
428 string response = string(msg.buffer);
429
430 cout << "Processing message" << endl;
431
432 switch(state)
433 {
434 case STATE_START:
435 {
436 cout << "In STATE_START" << endl;
437
438 switch(msg.type)
439 {
440 case MSG_TYPE_REGISTER:
441 {
442 break;
443 }
444 case MSG_TYPE_LOGIN:
445 {
446 if (response.compare("Player has already logged in.") == 0)
447 {
448 username.clear();
449 cout << "User login failed" << endl;
450 }
451 else if (response.compare("Incorrect username or password") == 0)
452 {
453 username.clear();
454 cout << "User login failed" << endl;
455 }
456 else
457 {
458 state = STATE_LOGIN;
459 wndCurrent = wndMain;
460
461 Player p("", "");
462 p.deserialize(msg.buffer);
463 mapPlayers[p.id] = p;
464 curPlayerId = p.id;
465
466 cout << "Got a valid login response with the player" << endl;
467 cout << "Player id: " << curPlayerId << endl;
468 cout << "map size: " << mapPlayers.size() << endl;
469 }
470
471 break;
472 }
473 case MSG_TYPE_PLAYER: // kind of hacky to put this here
474 {
475 cout << "Got MSG_TYPE_PLAYER message in STATE_START" << endl;
476
477 Player p("", "");
478 p.deserialize(msg.buffer);
479 p.timeLastUpdated = getCurrentMillis();
480 mapPlayers[p.id] = p;
481
482 cout << "new player id: " << p.id << endl;
483 cout << "map size: " << mapPlayers.size() << endl;
484
485 break;
486 }
487 case MSG_TYPE_OBJECT:
488 {
489 cout << "Received OBJECT message in STATE_START." << endl;
490
491 WorldMap::Object o(0, WorldMap::OBJECT_NONE, 0, 0);
492 o.deserialize(msg.buffer);
493 cout << "object id: " << o.id << endl;
494 gameMap->updateObject(o.id, o.type, o.pos.x, o.pos.y);
495
496 break;
497 }
498 }
499
500 break;
501 }
502 case STATE_LOGIN:
503 {
504 switch(msg.type)
505 {
506 case MSG_TYPE_REGISTER:
507 {
508 break;
509 }
510 case MSG_TYPE_LOGIN:
511 {
512 cout << "Got a login message" << endl;
513
514 chatConsole.addLine(response);
515 cout << "Added new line" << endl;
516
517 break;
518 }
519 case MSG_TYPE_LOGOUT:
520 {
521 cout << "Got a logout message" << endl;
522
523 if (response.compare("You have successfully logged out.") == 0)
524 {
525 cout << "Logged out" << endl;
526 state = STATE_START;
527 wndCurrent = wndLogin;
528 }
529
530 break;
531 }
532 case MSG_TYPE_PLAYER:
533 {
534 cout << "Got MSG_TYPE_PLAYER message in STATE_LOGIN" << endl;
535
536 Player p("", "");
537 p.deserialize(msg.buffer);
538 p.timeLastUpdated = getCurrentMillis();
539 mapPlayers[p.id] = p;
540
541 break;
542 }
543 case MSG_TYPE_PLAYER_MOVE:
544 {
545 cout << "Got a player move message" << endl;
546
547 unsigned int id;
548 int x, y;
549
550 memcpy(&id, msg.buffer, 4);
551 memcpy(&x, msg.buffer+4, 4);
552 memcpy(&y, msg.buffer+8, 4);
553
554 mapPlayers[id].target.x = x;
555 mapPlayers[id].target.y = y;
556
557 break;
558 }
559 case MSG_TYPE_CHAT:
560 {
561 chatConsole.addLine(response);
562
563 break;
564 }
565 case MSG_TYPE_OBJECT:
566 {
567 cout << "Received object message in STATE_LOGIN." << endl;
568
569 WorldMap::Object o(0, WorldMap::OBJECT_NONE, 0, 0);
570 o.deserialize(msg.buffer);
571 gameMap->updateObject(o.id, o.type, o.pos.x, o.pos.y);
572
573 break;
574 }
575 case MSG_TYPE_REMOVE_OBJECT:
576 {
577 cout << "Received REMOVE_OBJECT message!" << endl;
578
579 int id;
580 memcpy(&id, msg.buffer, 4);
581
582 cout << "Removing object with id " << id << endl;
583
584 if (!gameMap->removeObject(id))
585 cout << "Did not remove the object" << endl;
586
587 break;
588 }
589 case MSG_TYPE_SCORE:
590 {
591 memcpy(&scoreBlue, msg.buffer, 4);
592 memcpy(&scoreRed, msg.buffer+4, 4);
593
594 break;
595 }
596 default:
597 {
598 cout << "Received an unexpected message type: " << msg.type << endl;
599 }
600 }
601
602 break;
603 }
604 default:
605 {
606 cout << "The state has an invalid value: " << state << endl;
607
608 break;
609 }
610 }
611}
612
613// this should probably be in the WorldMap class
614void drawMap(WorldMap* gameMap)
615{
616 POSITION mapPos;
617 mapPos.x = 0;
618 mapPos.y = 0;
619 mapPos = mapToScreen(mapPos);
620
621 for (int x=0; x<12; x++)
622 {
623 for (int y=0; y<12; y++)
624 {
625 WorldMap::TerrainType el = gameMap->getElement(x, y);
626 WorldMap::StructureType structure = gameMap->getStructure(x, y);
627
628 if (el == WorldMap::TERRAIN_GRASS)
629 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));
630 else if (el == WorldMap::TERRAIN_OCEAN)
631 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));
632 else if (el == WorldMap::TERRAIN_ROCK)
633 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));
634
635 if (structure == WorldMap::STRUCTURE_BLUE_FLAG) {
636 al_draw_circle(x*25+12+mapPos.x, y*25+12+mapPos.y, 12, al_map_rgb(0, 0, 0), 3);
637 //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));
638 }else if (structure == WorldMap::STRUCTURE_RED_FLAG) {
639 al_draw_circle(x*25+12+mapPos.x, y*25+12+mapPos.y, 12, al_map_rgb(0, 0, 0), 3);
640 //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));
641 }
642 }
643 }
644
645 for (int x=0; x<12; x++)
646 {
647 for (int y=0; y<12; y++)
648 {
649 vector<WorldMap::Object> vctObjects = gameMap->getObjects(x, y);
650
651 vector<WorldMap::Object>::iterator it;
652 for(it = vctObjects.begin(); it != vctObjects.end(); it++) {
653 switch(it->type) {
654 case WorldMap::OBJECT_BLUE_FLAG:
655 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));
656 break;
657 case WorldMap::OBJECT_RED_FLAG:
658 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));
659 break;
660 }
661 }
662 }
663 }
664}
665
666void drawPlayers(map<unsigned int, Player>& mapPlayers, unsigned int curPlayerId)
667{
668 map<unsigned int, Player>::iterator it;
669
670 Player* p;
671 POSITION pos;
672
673 for(it = mapPlayers.begin(); it != mapPlayers.end(); it++)
674 {
675 p = &it->second;
676 pos = mapToScreen(p->pos);
677
678 if (p->id == curPlayerId)
679 al_draw_filled_circle(pos.x, pos.y, 14, al_map_rgb(0, 0, 0));
680
681 if (p->team == 0)
682 al_draw_filled_circle(pos.x, pos.y, 12, al_map_rgb(0, 0, 255));
683 else if (p->team == 1)
684 al_draw_filled_circle(pos.x, pos.y, 12, al_map_rgb(255, 0, 0));
685
686 if (p->hasBlueFlag)
687 al_draw_filled_rectangle(pos.x+4, pos.y-18, pos.x+18, pos.y-4, al_map_rgb(0, 0, 255));
688 else if (p->hasRedFlag)
689 al_draw_filled_rectangle(pos.x+4, pos.y-18, pos.x+18, pos.y-4, al_map_rgb(255, 0, 0));
690 }
691}
692
693void registerAccount()
694{
695 string username = txtUsername->getStr();
696 string password = txtPassword->getStr();
697
698 txtUsername->clear();
699 txtPassword->clear();
700
701 msgTo.type = MSG_TYPE_REGISTER;
702
703 strcpy(msgTo.buffer, username.c_str());
704 strcpy(msgTo.buffer+username.size()+1, password.c_str());
705
706 sendMessage(&msgTo, sock, &server);
707}
708
709void login()
710{
711 string strUsername = txtUsername->getStr();
712 string strPassword = txtPassword->getStr();
713 username = strUsername;
714
715 txtUsername->clear();
716 txtPassword->clear();
717
718 msgTo.type = MSG_TYPE_LOGIN;
719
720 strcpy(msgTo.buffer, strUsername.c_str());
721 strcpy(msgTo.buffer+username.size()+1, strPassword.c_str());
722
723 sendMessage(&msgTo, sock, &server);
724}
725
726void logout()
727{
728 txtChat->clear();
729
730 msgTo.type = MSG_TYPE_LOGOUT;
731
732 strcpy(msgTo.buffer, username.c_str());
733
734 sendMessage(&msgTo, sock, &server);
735}
736
737void quit()
738{
739 doexit = true;
740}
741
742void sendChatMessage()
743{
744 string msg = txtChat->getStr();
745
746 txtChat->clear();
747
748 msgTo.type = MSG_TYPE_CHAT;
749
750 strcpy(msgTo.buffer, msg.c_str());
751
752 sendMessage(&msgTo, sock, &server);
753}
Note: See TracBrowser for help on using the repository browser.