-
Notifications
You must be signed in to change notification settings - Fork 2
/
toplevel.cpp
1267 lines (1107 loc) · 34.2 KB
/
toplevel.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* FILE: toplevel.c
* AUTHOR: name (email)
* DATE: March 31 23:59:59 PST 2013
* DESCR:
*/
/* #define DEBUG */
#include "main.h"
#include <string>
#include "mazewar.h"
static bool updateView; /* true if update needed */
MazewarInstance::Ptr M;
/* Use this socket address to send packets to the multi-cast group. */
static Sockaddr groupAddr;
#define MAX_OTHER_RATS (MAX_RATS - 1)
int main(int argc, char *argv[])
{
Loc x(1);
Loc y(5);
Direction dir(0);
char *ratName;
signal(SIGHUP, quit);
signal(SIGINT, quit);
signal(SIGTERM, quit);
if(argc < 2) {
getName((char *)("Welcome to CS244B MazeWar!\n\nYour Name"), &ratName);
ratName[strlen(ratName) - 1] = 0;
} else {
printf("Welcome to CS244B MazeWar!\n\nYour Name: %s\n", argv[1]);
ratName = (char *)malloc(sizeof(char)*NAMESIZE);
strncpy(ratName, argv[1], NAMESIZE);
}
if(strlen(ratName) >= NAMESIZE )
ratName[NAMESIZE-1] = 0;
M = MazewarInstance::mazewarInstanceNew(string(ratName));
MazewarInstance* a = M.ptr();
strncpy(M->myName_, ratName, NAMESIZE);
free(ratName);
MazeInit(argc, argv);
requestToJoin();
// NewPosition(M);
M->getCurTime();
M->updateMoveTime();
sendStatus();
cout << "before play begin:"<< MY_X_LOC <<endl;
updateView = TRUE;
DoViewUpdate();
/* So you can see what a Rat is supposed to look like, we create
one rat in the single player mode Mazewar.
It doesn't move, you can't shoot it, you can just walk around it */
play();
return 0;
}
/* ----------------------------------------------------------------------- */
void
play(void)
{
MWEvent event;
MW244BPacket incoming;
event.eventDetail = &incoming;
while (TRUE) {
NextEvent(&event, M->theSocket());
M->getCurTime();
bool rat_move = false;
bool rat_dir_change = false;
bool rat_score_change = false;
if (!M->peeking())
switch(event.eventType) {
case EVENT_A:
aboutFace();
rat_dir_change = true;
break;
case EVENT_S:
leftTurn();
rat_dir_change = true;
break;
case EVENT_D:
forward();
rat_move = true;
break;
case EVENT_F:
rightTurn();
rat_dir_change = true;
break;
case EVENT_BAR:
backward();
rat_move = true;
break;
case EVENT_LEFT_D:
peekLeft();
break;
case EVENT_MIDDLE_D:
rat_score_change = shoot();
break;
case EVENT_RIGHT_D:
peekRight();
break;
case EVENT_NETWORK:
processPacket(&event);
break;
case EVENT_INT:
quit(0);
break;
}
else
switch (event.eventType) {
case EVENT_RIGHT_U:
case EVENT_LEFT_U:
peekStop();
break;
case EVENT_NETWORK:
processPacket(&event);
break;
}
ratStates(rat_move, rat_dir_change, rat_score_change); /* clean house */
bool needShowMe = manageMissiles();
if(needShowMe)
updateView = TRUE;
DoViewUpdate();
/* Any info to send over network? */
}
}
/* ----------------------------------------------------------------------- */
static Direction _aboutFace[NDIRECTION] ={SOUTH, NORTH, WEST, EAST};
static Direction _leftTurn[NDIRECTION] = {WEST, EAST, NORTH, SOUTH};
static Direction _rightTurn[NDIRECTION] ={EAST, WEST, SOUTH, NORTH};
void
aboutFace(void)
{
M->dirIs(_aboutFace[MY_DIR]);
updateView = TRUE;
}
/* ----------------------------------------------------------------------- */
void
leftTurn(void)
{
M->dirIs(_leftTurn[MY_DIR]);
updateView = TRUE;
}
/* ----------------------------------------------------------------------- */
void
rightTurn(void)
{
M->dirIs(_rightTurn[MY_DIR]);
updateView = TRUE;
}
/* ----------------------------------------------------------------------- */
/* remember ... "North" is to the right ... positive X motion */
void
forward(void)
{
register int tx = MY_X_LOC;
register int ty = MY_Y_LOC;
switch(MY_DIR) {
case NORTH: if (!M->maze_[tx+1][ty]) tx++; break;
case SOUTH: if (!M->maze_[tx-1][ty]) tx--; break;
case EAST: if (!M->maze_[tx][ty+1]) ty++; break;
case WEST: if (!M->maze_[tx][ty-1]) ty--; break;
default:
MWError("bad direction in Forward");
}
vector<uint32_t> sameloc;
if(checkOtherLoc(Loc(tx), Loc(ty), sameloc))
return;
if ((MY_X_LOC != tx) || (MY_Y_LOC != ty)) {
M->preLoc.push_front(pair<uint16_t, uint16_t>(MY_X_LOC, MY_Y_LOC));
if(M->preLoc.size() > MAX_RATS)
M->preLoc.pop_back();
M->xlocIs(Loc(tx));
M->ylocIs(Loc(ty));
updateView = TRUE;
}
}
/* ----------------------------------------------------------------------- */
void backward()
{
register int tx = MY_X_LOC;
register int ty = MY_Y_LOC;
switch(MY_DIR) {
case NORTH: if (!M->maze_[tx-1][ty]) tx--; break;
case SOUTH: if (!M->maze_[tx+1][ty]) tx++; break;
case EAST: if (!M->maze_[tx][ty-1]) ty--; break;
case WEST: if (!M->maze_[tx][ty+1]) ty++; break;
default:
MWError("bad direction in Backward");
}
vector<uint32_t> sameloc;
if(checkOtherLoc(Loc(tx), Loc(ty), sameloc))
return;
if ((MY_X_LOC != tx) || (MY_Y_LOC != ty)) {
M->preLoc.push_front(pair<uint16_t, uint16_t>(MY_X_LOC, MY_Y_LOC));
if(M->preLoc.size() > MAX_RATS)
M->preLoc.pop_back();
M->xlocIs(Loc(tx));
M->ylocIs(Loc(ty));
updateView = TRUE;
}
}
/* ----------------------------------------------------------------------- */
void peekLeft()
{
M->xPeekIs(MY_X_LOC);
M->yPeekIs(MY_Y_LOC);
M->dirPeekIs(MY_DIR);
switch(MY_DIR) {
case NORTH: if (!M->maze_[MY_X_LOC+1][MY_Y_LOC]) {
M->xPeekIs(MY_X_LOC + 1);
M->dirPeekIs(WEST);
}
break;
case SOUTH: if (!M->maze_[MY_X_LOC-1][MY_Y_LOC]) {
M->xPeekIs(MY_X_LOC - 1);
M->dirPeekIs(EAST);
}
break;
case EAST: if (!M->maze_[MY_X_LOC][MY_Y_LOC+1]) {
M->yPeekIs(MY_Y_LOC + 1);
M->dirPeekIs(NORTH);
}
break;
case WEST: if (!M->maze_[MY_X_LOC][MY_Y_LOC-1]) {
M->yPeekIs(MY_Y_LOC - 1);
M->dirPeekIs(SOUTH);
}
break;
default:
MWError("bad direction in PeekLeft");
}
/* if any change, display the new view without moving! */
if ((M->xPeek() != MY_X_LOC) || (M->yPeek() != MY_Y_LOC)) {
M->peekingIs(TRUE);
updateView = TRUE;
}
}
/* ----------------------------------------------------------------------- */
void peekRight()
{
M->xPeekIs(MY_X_LOC);
M->yPeekIs(MY_Y_LOC);
M->dirPeekIs(MY_DIR);
switch(MY_DIR) {
case NORTH: if (!M->maze_[MY_X_LOC+1][MY_Y_LOC]) {
M->xPeekIs(MY_X_LOC + 1);
M->dirPeekIs(EAST);
}
break;
case SOUTH: if (!M->maze_[MY_X_LOC-1][MY_Y_LOC]) {
M->xPeekIs(MY_X_LOC - 1);
M->dirPeekIs(WEST);
}
break;
case EAST: if (!M->maze_[MY_X_LOC][MY_Y_LOC+1]) {
M->yPeekIs(MY_Y_LOC + 1);
M->dirPeekIs(SOUTH);
}
break;
case WEST: if (!M->maze_[MY_X_LOC][MY_Y_LOC-1]) {
M->yPeekIs(MY_Y_LOC - 1);
M->dirPeekIs(NORTH);
}
break;
default:
MWError("bad direction in PeekRight");
}
/* if any change, display the new view without moving! */
if ((M->xPeek() != MY_X_LOC) || (M->yPeek() != MY_Y_LOC)) {
M->peekingIs(TRUE);
updateView = TRUE;
}
}
/* ----------------------------------------------------------------------- */
void peekStop()
{
M->peekingIs(FALSE);
updateView = TRUE;
}
/* ----------------------------------------------------------------------- */
bool MazewarInstance::launch() {
if(canLaunch()) {
missiles_.insert(pair<unsigned int, Missile>(nextMissileID_,
Missile(nextMissileID_, xloc_, yloc_, dir_, &curTime_)));
++nextMissileID_;
updateLaunchTime();
return true;
}
return false;
}
//shoot, return true if score changes
bool shoot()
{
// sendPacketToPlayer(M->myRatId());
if(M->launch()) {
M->scoreIs( M->score().value()-1 );
UpdateScoreCard(M->myRatId().value());
return true;
} else {
cout << "shoot no success"<<endl;
return false;
}
}
/* ----------------------------------------------------------------------- */
/*
* Exit from game, clean up window
*/
void quit(int sig)
{
MW244BPacket pack;
pack.type = PKT_RTE;
memset(pack.body, 0, sizeof(pack.body));
struct RTEPacket *p = (struct RTEPacket *)&pack.body;
p->playerID = htonl(M->playerID);
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
StopWindow();
exit(0);
}
void processRTEPacket(struct RTEPacket * RTE)
{
unsigned int playerID = ntohl(RTE->playerID);
if(M->allPlayers_.find(playerID) != M->allPlayers_.end()){
RatIndexType idx(M->allPlayers_[playerID]);
M->updateRat(idx).playing = false;
M->updateRat(idx).pinned = false;
M->updateRat(idx).getName = false;
M->updateRat(idx).statusSeqNum = 0;
UpdateScoreCard(idx);
M->allPlayers_.erase(playerID);
updateView = TRUE;
}
}
void newPlayerHandlePacket(MW244BPacket *pack){
struct PacketWithName * pName;
pName = (struct PacketWithName *) &(pack->body);
switch (pack->type) {
case PKT_ATN:
if(ntohl(pName->playerID) != M->playerID) {
// cout << "New Player Handle ATN\n";
processATNPacket((struct PacketWithName *)&(pack->body));
}
break;
case PKT_LOC_DIR_SCORE:
if(ntohl(pName->playerID) != M->playerID) {
// cout << "New Player Hanlde status packet\n";
processLocDirScore((struct PacketLocDirScore *)&(pack->body));
}
break;
case PKT_REQNAME:
if(ntohl(pName->playerID) == M->playerID) {
processReqNamePacket((struct PacketReqName *)&(pack->body));
}
break;
default: break;
}
}
void requestToJoin()
{
srand(time(NULL));
unsigned int rand_val = rand();
M->playerID = rand_val;
M->allPlayers_[M->playerID] = 0; //self
M->updateRat(RatIndexType(0)).pinned = true;
sendRTJPacket();
struct timeval joinTime;
gettimeofday(&joinTime, NULL);
MWEvent event;
MW244BPacket incoming;
event.eventDetail = &incoming;
//wait other players' reply
while (TRUE) {
NextEvent(&event, M->theSocket());
M->getCurTime();
if(event.eventType == EVENT_NETWORK) {
newPlayerHandlePacket(event.eventDetail);
}
if(M->curTime().tv_sec-joinTime.tv_sec
+(M->curTime().tv_usec-joinTime.tv_usec)/1000000 >= 1.0) {
cout << "Finish waiting"<<endl;
break;
}
}
vector<unsigned int> other;
if(checkOtherLoc(M->xloc(), M->yloc(), other))
NewPosition(M);
}
void formPacketWithName(void *packBody)
{
struct PacketWithName * p = (struct PacketWithName *)packBody;
p->playerID = htonl(M->playerID); //current player
size_t length = strlen(M->myName_);
if(length > 15 ){
length = 15;
M->myName_[length] = 0;
}
p->nameLen = char(length);
strncpy(p->name, M->myName_, NAMESIZE);
}
/* Request To Join packet */
void sendRTJPacket()
{
MW244BPacket pack;
pack.type = 1;
memset(pack.body, 0, sizeof(pack.body));
formPacketWithName((void *) &(pack.body));
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
}
void addPlayerName(RatIndexType idx, size_t length, char *name)
{
M->updateRat(idx).getName = true;
if(length >= NAMESIZE)
length = NAMESIZE - 1;
strncpy(M->updateRat(idx).name, name, length);
// printf("after copy %s\n", M->updateRat(idx).name);
M->updateRat(idx).name[NAMESIZE-1] = 0;
}
void addPlayerName(unsigned int playerID, size_t length, char *name)
{
if(M->allPlayers_.find(playerID) == M->allPlayers_.end()) {
int i;
for(i=1; i<MAX_RATS; ++i) {
RatIndexType idx(i);
if(!M->rat(idx).pinned) {
M->allPlayers_[playerID] = i;
M->updateRat(idx).playing = true;
M->updateRat(idx).pinned = true;
M->updateRat(idx).statusSeqNum = 0;
addPlayerName(idx, length, (char *)(name));
UpdateScoreCard(idx);
break;
}
}
if(i == MAX_RATS){
cout << "Handle Me: player is full\n";
}
} else {
RatIndexType idx(M->allPlayers_[playerID]);
if(!M->rat(idx).getName){
addPlayerName(idx, length, (char *)(name));
UpdateScoreCard(idx);
}
}
}
void processRTJPacket(struct RTJPacket * RTJ)
{
unsigned int playerID = ntohl(RTJ->playerID);
cout << "playerID "<<playerID << endl;
cout << "namelen " << int(RTJ->nameLen) << endl;
cout << "name " << (RTJ->name) <<endl;
addPlayerName(playerID, size_t(RTJ->nameLen), RTJ->name);
//form reply packet with Name, ATN packet
MW244BPacket pack;
pack.type = 2;
memset(pack.body, 0, sizeof(pack.body));
formPacketWithName((void* )&(pack.body));
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
//report current status
sendStatus();
//hack, see the Rat
}
void processATNPacket(struct PacketWithName * packName)
{
unsigned int playerID = ntohl(packName->playerID);
size_t length = size_t(packName->nameLen);
addPlayerName(playerID, length, packName->name);
// no need to further reply
}
/* ----------------------------------------------------------------------- */
void NewPosition(MazewarInstance::Ptr m, int x, int y, int dir_in)
{
Loc newX(0);
Loc newY(0);
if(x>=0 && x < MAZEXMAX )
newX = Loc(x);
if(y>=0 && y < MAZEYMAX )
newY = Loc(y);
Direction dir(0); /* start on occupied square */
vector<uint32_t> sameloc;
while (M->maze_[newX.value()][newY.value()] ||
checkOtherLoc(newX, newY, sameloc)) {
/* MAZE[XY]MAX is a power of 2 */
newX = Loc(random() & (MAZEXMAX - 1));
newY = Loc(random() & (MAZEYMAX - 1));
sameloc.clear();
/* In real game, also check that square is
unoccupied by another rat */
}
/* prevent a blank wall at first glimpse */
if(dir_in < 0 || dir_in > 3) {
if (!m->maze_[(newX.value())+1][(newY.value())]) dir = Direction(NORTH);
if (!m->maze_[(newX.value())-1][(newY.value())]) dir = Direction(SOUTH);
if (!m->maze_[(newX.value())][(newY.value())+1]) dir = Direction(EAST);
if (!m->maze_[(newX.value())][(newY.value())-1]) dir = Direction(WEST);
} else
dir = Direction(dir_in);
m->xlocIs(newX);
m->ylocIs(newY);
m->dirIs(dir);
}
/* ----------------------------------------------------------------------- */
void MWError(const char *s)
{
StopWindow();
fprintf(stderr, "CS244BMazeWar: %s\n", s);
perror("CS244BMazeWar");
exit(-1);
}
/* ----------------------------------------------------------------------- */
/* This is just for the sample version, rewrite your own */
Score GetRatScore(RatIndexType ratId)
{
if (ratId.value() == M->myRatId().value())
{ return(M->score()); }
else {
return M->rat(ratId).score;
}
}
/* ----------------------------------------------------------------------- */
/* This is just for the sample version, rewrite your own */
char *GetRatName(RatIndexType ratId)
{
if (ratId.value() == M->myRatId().value())
{ return(M->myName_); }
else { //return (char *)("Dummy");
// why it needs to be first convert to string then to c_str()?
// printf("in get name, id is %d\n", ratId.value());
return (char *)(string(M->rat(ratId).name).c_str());
}
}
/* ----------------------------------------------------------------------- */
/* This is just for the sample version, rewrite your own if necessary */
void ConvertIncoming(MW244BPacket *p)
{
}
/* ----------------------------------------------------------------------- */
/* This is just for the sample version, rewrite your own if necessary */
void ConvertOutgoing(MW244BPacket *p)
{
}
/* ----------------------------------------------------------------------- */
void sendStatus(void)
{
MW244BPacket pack;
pack.type = PKT_LOC_DIR_SCORE;
memset(pack.body, 0, sizeof(pack.body));
struct PacketLocDirScore * p = (struct PacketLocDirScore *) &(pack.body);
p->playerID = htonl(M->playerID);
p->statusSeqNum = htonl(M->updateStatusSeqNum());
p->xloc = char(MY_X_LOC);
p->yloc = char(MY_Y_LOC);
p->dir = char(MY_DIR);
p->score = htonl(M->score().value());
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
M->updateStatusTime();
}
/* This is just for the sample version, rewrite your own */
void ratStates(bool rat_move, bool rat_dir_change, bool rat_score_change)
{
/* In our sample version, we don't know about the state of any rats over
the net, so this is a no-op */
if(rat_move) {
M->updateMoveTime();
if(M->checkSendStatusPKT(MIN_LOC_UPDATE_WAIT))
sendStatus();
} else if((rat_dir_change || rat_score_change)
&& M->checkSendStatusPKT(MIN_DIR_SCORE_UPDATE_WAIT)) {
sendStatus();
} else if(M->checkSendStatusPKT(PERIODIC_UPDATE_WAIT))
sendStatus();
map<uint32_t, int>::iterator mapit;
for(mapit = M->allPlayers_.begin(); mapit != M->allPlayers_.end(); ) {
RatIndexType idx(mapit->second);
if(idx.value() == 0){//self
++mapit;
continue;
}
if(M->rat(idx).pinned) {
struct timeval & t = M->updateRat(idx).lastUpdate;
if(M->rat(idx).playing) {
M->updateRat(idx).playing = (M->curTime().tv_sec - t.tv_sec) * 1000
+ (M->curTime().tv_usec - t.tv_usec)/1000 < DISCONNECT_TIME;
if(!M->updateRat(idx).playing) {
cout << idx.value() <<" someone disconnected\n";
updateView = TRUE;
}
} else
if((M->curTime().tv_sec - t.tv_sec) * 1000
+ (M->curTime().tv_usec - t.tv_usec)/1000 > QUIT_TIME){
M->updateRat(idx).playing = false;
M->updateRat(idx).pinned = false;
M->updateRat(idx).getName = false;
M->updateRat(idx).statusSeqNum = 0;
map<uint32_t, int>::iterator erase_it = mapit++;
M->allPlayers_.erase(erase_it);
UpdateScoreCard(idx);
updateView = TRUE;
continue;
}
++mapit;
} else {
M->updateRat(idx).getName = false;
map<uint32_t, int>::iterator erase_it = mapit++;
M->allPlayers_.erase(erase_it);
UpdateScoreCard(idx);
updateView = TRUE;
}
}
}
void processLocDirScore(struct PacketLocDirScore * p){
unsigned int playerID = ntohl(p->playerID);
unsigned short xloc_v = p->xloc;
unsigned short yloc_v = p->yloc;
unsigned short dir = p->dir;
unsigned int statusSeqNum = ntohl(p->statusSeqNum);
int score = ntohl(p->score);
// printf("%s, receive status update\n", GetRatName(RatIndexType(0)));
if(M->allPlayers_.find(playerID) != M->allPlayers_.end()) {
RatIndexType idx(M->allPlayers_[playerID]);
M->updateRat(idx).playing = true;
M->updateRat(idx).lastUpdate = M->curTime();
if(!M->rat(idx).getName)
sendReqNamePacket(playerID);
if(statusSeqNum > M->rat(idx).statusSeqNum){
M->updateRat(idx).statusSeqNum = statusSeqNum;
} else {
// cout << "duplicate status pkt"<<endl;
return;
}
if(xloc_v == MY_X_LOC && yloc_v == MY_Y_LOC) {
if(M->checkSettleDown())
sendRTBPacket(p->playerID, p->xloc, p->yloc);
else
playerBackoff();
}else if(xloc_v != M->rat(idx).x.value() || yloc_v != M->rat(idx).y.value()
|| dir != M->rat(idx).y.value()) {
SetRatPosition(idx, Loc(xloc_v), Loc(yloc_v), Direction(dir));
updateView = TRUE;
}
if(score != M->rat(idx).score.value()){
M->updateRat(idx).score = Score(score);
UpdateScoreCard(idx);
}
} else {
int i;
for(i=1; i<MAX_RATS; ++i) {
RatIndexType idx(i);
if(!M->rat(idx).pinned) {
M->allPlayers_[playerID] = i;
M->updateRat(idx).playing = true;
M->updateRat(idx).pinned = true;
M->updateRat(idx).getName = false;
sendReqNamePacket(playerID);
M->updateRat(idx).statusSeqNum = statusSeqNum;
SetRatPosition(idx, Loc(xloc_v), Loc(yloc_v), Direction(dir));
M->updateRat(idx).score = Score(score);
updateView = TRUE;
UpdateScoreCard(idx);
M->updateRat(idx).lastUpdate = M->curTime();
break;
}
}
if(i == MAX_RATS){
cout << "Handle Me: player is full\n";
}
}
}
void sendReqNamePacket(unsigned int playerID)
{
MW244BPacket pack;
pack.type = PKT_REQNAME;
struct PacketReqName * REQ = (struct PacketReqName *)&pack.body;
REQ->playerID = htonl(playerID);
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
}
void processReqNamePacket(struct PacketReqName * p)
{
MW244BPacket pack;
pack.type = PKT_ATN;
memset(pack.body, 0, sizeof(pack.body));
formPacketWithName((void* )&(pack.body));
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
}
void sendRTBPacket(unsigned int playerID_n, char xloc, char yloc)
{
cout << "send RTB packet\n";
MW244BPacket pack;
pack.type = PKT_RTB;
struct RTBPacket * RTB = (struct RTBPacket *)&pack.body;
RTB->invaderID = playerID_n;
RTB->xloc = xloc;
RTB->yloc = yloc;
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
}
void playerBackoff()
{
list<pair<uint16_t, uint16_t> >::iterator lit;
for(lit = M->preLoc.begin(); lit != M->preLoc.end(); lit++){
M->xlocIs(Loc(lit->first));
M->ylocIs(Loc(lit->second));
M->preLoc.erase(lit);
updateView = TRUE;
break;
}
}
void processRTBPacket(struct RTBPacket *p)
{
cout << "handle RTB packet\n";
unsigned short xloc_v = p->xloc;
unsigned short yloc_v = p->yloc;
if(xloc_v != MY_X_LOC || yloc_v != MY_Y_LOC)
return;
playerBackoff();
}
/* ----------------------------------------------------------------------- */
void Missile::updateMissileLoc(struct timeval curTime)
{
register int mx = xloc_.value();
register int my = yloc_.value();
switch(dir_.value()) {
case EAST: if(!M->maze_[mx][my+1]) my ++ ;
else hitWall_ = true; break;
case WEST: if(!M->maze_[mx][my-1]) my -- ;
else hitWall_ = true; break;
case NORTH: if(!M->maze_[mx+1][my]) mx ++ ;
else hitWall_ = true; break;
case SOUTH: if(!M->maze_[mx-1][my]) mx -- ;
else hitWall_ = true; break;
default: MWError("bad direction in shoot");
}
update_ = curTime;
if(!hitWall_) {
xloc_ = Loc(mx);
yloc_ = Loc(my);
//on the new location, try to see if it tag some player
}
}
// Check for all other player who is in the game, if there location is this
// Return true if there is someone in this location, and push the player ID
// back in the vector
bool checkOtherLoc(Loc xloc, Loc yloc, vector<uint32_t> &sameloc){
map<uint32_t, int>::iterator mapit;
for(mapit= M->allPlayers_.begin(); mapit!= M->allPlayers_.end(); ++mapit){
if(mapit->first == M->playerID)
continue;
RatIndexType idx(mapit->second);
if(!M->rat(idx).playing)
continue;
if(M->rat(idx).x.value() == xloc.value()
&& M->rat(idx).y.value() == yloc.value()){
sameloc.push_back(mapit->first);
}
}
if(sameloc.size())
return true;
else
return false;
}
void sendRTTPacket(Missile & mi, uint32_t dstID)
{
printf("send RTT packet\n");
MW244BPacket pack;
pack.type = PKT_RTT;
// memset(pack.body, 0, sizeof(pack.body));
struct RTTPacket * RTT = (struct RTTPacket *) &pack.body;
RTT->hitPlayerID = htonl(dstID);
RTT->shootPlayerID = htonl(M->playerID);
RTT->xloc = char(mi.xloc().value());
RTT->yloc = char(mi.yloc().value());
RTT->missileID = htonl(mi.missileID());
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
}
void sendAckTagPacket(bool tagged, unsigned int shootPlayerID_n,
unsigned int missileID_n)
{
MW244BPacket pack;
pack.type = PKT_ACK_TAG;
memset(pack.body, 0, sizeof(pack.body));
struct AckTagPacket * AckTag = (struct AckTagPacket *) &pack.body;
AckTag->shootPlayerID = shootPlayerID_n;
AckTag->hitPlayerID = htonl(M->playerID);
AckTag->tagged = char(tagged);
AckTag->missileID = missileID_n;
if (sendto(M->theSocket(), &pack, sizeof(pack), 0,
(const struct sockaddr*)&groupAddr , sizeof(Sockaddr)) < 0)
{ MWError("Sample error"); }
}
void processRTTPacket(struct RTTPacket * p)
{
unsigned short px = (unsigned short)(p->xloc);
unsigned short py = (unsigned short)(p->yloc);
if(px == MY_X_LOC && py ==MY_Y_LOC){
sendAckTagPacket(true, p->shootPlayerID, p->missileID);
cout << "I am hit" <<endl;
M->scoreIs( M->score().value()- 5 );
UpdateScoreCard(M->myRatId().value());
//need to respawn
NewPosition(M);
sendStatus();
updateView = true;
} else
sendAckTagPacket(false, p->shootPlayerID, p->missileID);
}
void processAckTagPacket(struct AckTagPacket * AckTag)
{
bool tagged = (bool)(AckTag->tagged);
unsigned int hitPlayerId = ntohl(AckTag->hitPlayerID);
// cout << "Hit Player ID "<< hitPlayerId <<endl;
unsigned int missileID = ntohl(AckTag->missileID);
// cout << "Receive AckTagPacket" <<endl;
if(M->missiles_.find(missileID) == M->missiles_.end()){
// printf("This missile is out\n");
return;
}
Missile & mi = M->missiles_.find(missileID)->second;
list<struct TagRat>::iterator lit;
for(lit = mi.tagRats_.begin(); lit != mi.tagRats_.end(); lit++)
if(lit ->tagRatId == hitPlayerId )
break;
if(lit == mi.tagRats_.end()) {
printf( "Not in the tag queue\n");
return;
}
if(tagged){
M->scoreIs( M->score().value()+11 );
UpdateScoreCard(M->myRatId().value());
sendStatus();
clearSquare(mi.xloc(), mi.yloc());
mi.tagRats_.clear();
M->missiles_.erase(missileID);
} else
mi.tagRats_.erase(lit);
}
void setMissileInitialReqTime(Missile & mi){
mi.lastReqTime_ = M->curTime();
if(mi.lastReqTime_.tv_usec/1000 > 200)
mi.lastReqTime_.tv_usec -= 200000;
else{
mi.lastReqTime_.tv_sec -= 1;
mi.lastReqTime_.tv_usec += 800000;
}
}
inline bool AckTagTimeOut(Missile & mi){
if((M->curTime().tv_sec - mi.lastReqTime_.tv_sec) * 1000
+ (M->curTime().tv_usec - mi.lastReqTime_.tv_usec)/1000 > 200)
return true;
else
return false;
}
/* This is just for the sample version, rewrite your own */
bool manageMissiles()
{
/* Leave this up to you. */
map<unsigned int, Missile>::iterator mapit;
map<unsigned int, Missile>::iterator mapit_erase;
bool needShowMe = false;
// bool sendMissileReq = false;
for(mapit = M->missiles_.begin(); mapit != M->missiles_.end(); ) {
Missile & mi = mapit->second;
if (!mi.hitWall() && mi.needUpdateLoc(M->curTime())) {
Loc preX(mi.xloc());
Loc preY(mi.yloc());
mi.updateMissileLoc(M->curTime());
if(!mi.hitWall()){
showMissile(mi.xloc(), mi.yloc(), mi.dir(), preX, preY, true);