-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain-multi.c
More file actions
1436 lines (1245 loc) · 41.7 KB
/
main-multi.c
File metadata and controls
1436 lines (1245 loc) · 41.7 KB
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
#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define DEBUG false
// windows.h 기본 설정
#define stdHandle GetStdHandle(STD_OUTPUT_HANDLE)
#define isPressed(K) (GetAsyncKeyState(K)&0x8000)
// winsock2.h 기본 설정
#define DLL_NAME "ws2_32.dll"
#define RESOLVE(fn) (fn##_t)GetProcAddress(hMod, #fn)
// 로컬 스토리지 저장 파일명
#define LOCAL_STORAGE_FILE "1428_local_storage.json"
// --------- winsock2.h 직접 재정의 ---------
#undef htons
#undef htonl
bool online = false;
char *name;
static HMODULE hMod;
typedef int (WINAPI *WSAStartup_t)(WORD, LPWSADATA);
typedef int (WINAPI *WSACleanup_t)(void);
typedef int (WINAPI *connect_t)(SOCKET,const struct sockaddr*,int);
typedef SOCKET (WINAPI *socket_t)(int,int,int);
typedef int (WINAPI *send_t)(SOCKET,const char*,int,int);
typedef int (WINAPI *recv_t)(SOCKET,char*,int,int);
typedef int (WINAPI *shutdown_t)(SOCKET,int);
typedef int (WINAPI *closesocket_t)(SOCKET);
typedef int (WINAPI *WSAGetLastError_t)(void);
static WSAStartup_t pWSAStartup;
static WSACleanup_t pWSACleanup;
static socket_t psocket;
static connect_t pconnect;
static send_t psend;
static recv_t precv;
static shutdown_t pshutdown;
static closesocket_t pclosesocket;
static WSAGetLastError_t pWSAGetLastError;
typedef u_short (WINAPI *htons_t)(u_short);
typedef u_long (WINAPI *htonl_t)(u_long);
static htons_t phtons;
static htonl_t phtonl;
// 현재 클라이언트의 고유 식별자
char *clientID;
// 서버와 연결할 소켓
SOCKET s;
// --------- TCP-IP 바이트 헬퍼 ---------
static unsigned short htons16(unsigned short v){ return (v >> 8) | (v << 8); } // 16-bit swap
static unsigned long htonl32(unsigned long v) { return (v>>24)|((v>>8)&0x0000FF00)|((v<<8)&0x00FF0000)|(v<<24);} // 32-bit swap
/// 소켓 통신을 위한 라이브러리가 필요한데 컴파일 옵션을 넣기에는 장치마다 다 세팅을 해줘야 해서 DLL 파일을 직접 다이나믹하게 로딩하기 위해 넣었어요 선생님 진짜 힘들었습니다 ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ
int winsock_dynload(void)
{
hMod = LoadLibraryA(DLL_NAME); /* DLL 적재 */
if (!hMod) { fprintf(stderr,"LoadLibrary failed\n"); return 0; }
pWSAStartup = RESOLVE(WSAStartup);
pWSACleanup = RESOLVE(WSACleanup);
psocket = RESOLVE(socket);
pconnect = RESOLVE(connect);
psend = RESOLVE(send);
precv = RESOLVE(recv);
pshutdown = RESOLVE(shutdown);
pclosesocket = RESOLVE(closesocket);
pWSAGetLastError = RESOLVE(WSAGetLastError);
phtons = RESOLVE(htons);
phtonl = RESOLVE(htonl);
if (!phtons || !phtonl) { fputs("htons/htonl load fail\n", stderr); return 0; }
if (!pWSAStartup||!psocket||!pconnect) {
fprintf(stderr,"GetProcAddress failed\n");
FreeLibrary(hMod);
return 0;
}
WSADATA wsa;
if (pWSAStartup(MAKEWORD(2,2), &wsa)!=0){
fprintf(stderr,"WSAStartup err\n");
FreeLibrary(hMod);
return 0;
}
return 1;
}
void winsock_unload(void)
{
if (pWSACleanup) pWSACleanup();
if (hMod) FreeLibrary(hMod);
}
// 위치를 구조체로 표현
typedef struct Location
{
int x;
int y;
}Location;
// 방향 특화 덱 자료구조 구현체
typedef struct {
int buf[4];
int head, tail;
} DirQ;
void dq_init(DirQ* q){ q->head = q->tail = 0; }
bool dq_empty(DirQ* q){ return q->head == q->tail; }
bool dq_full(DirQ* q){ return ((q->tail+1)&3) == q->head; }
void dq_push(DirQ* q, int d){
if (dq_full(q)) return;
q->buf[q->tail] = d;
q->tail = (q->tail + 1) & 3;
}
int dq_pop(DirQ* q){
int d = q->buf[q->head];
q->head = (q->head + 1) & 3;
return d;
}
// 색 & 방향을 미리 const값으로 정의
const int Right = 0;
const int Left = 1;
const int Up = 2;
const int Down = 3;
const int Black = 0;
const int Blue = 1;
const int Green = 2;
const int BlueGreen = 3;
const int Red = 4;
const int Purple = 5;
const int Yellow = 6;
const int White = 7;
const int Gray = 8;
const int LightBlue = 9;
const int LightGreen = 10;
const int LightBlueGreen = 11;
const int LightRed = 12;
const int LightPurple = 13;
const int LightYellow = 14;
const int LightWhite = 15;
unsigned long dw;
const Location dir[4] = { {1, 0}, {-1, 0}, {0, -1}, {0, 1} };
/// 위치가 범위 밖인지 아닌지 검사하는 함수
bool isOutOfRange(Location here) {
return (here.x <= 0 || here.y <= 0 || here.x > 39 || here.y > 39);
}
/// 콘솔 커서 위치 옮기기
void gotoxy(SHORT x, SHORT y)
{
COORD pos = { x, y };
SetConsoleCursorPosition(stdHandle, pos);
}
/// @brief 맵 기준으로 커서 옮기기
void gotoMapLoc(Location L) {
COORD pos = { L.x*2-1, L.y };
SetConsoleCursorPosition(stdHandle, pos);
}
/// @brief 맵 기준으로 커서 옮기기
void gotoMapXY(SHORT x, SHORT y) {
COORD pos = { x*2-1, y };
SetConsoleCursorPosition(stdHandle, pos);
}
/// 현재 위치에서 바라보고 있는 방향으로 1칸 이동한 위치를 반환
Location DIRtoLOC(Location here, int facing)
{
Location ret = { here.x + dir[facing].x, here.y + dir[facing].y };
return ret;
}
/// 현재 보고 있는 방향의 반대 방향을 반환
int ReverseDirection(int d)
{
switch (d)
{
case 0: // Right
return Left;
case 1: // Left
return Right;
case 2: // Up
return Down;
case 3: // Down
return Up;
}
}
/// from ~ to 사이 난수를 반환
int getRandomNumber(int from, int to) {
return (rand()+time(0)) % (to - from + 1) + from;
}
/// 1 ~ 맵 크기 사이 난수 반환
int getRandom() { return getRandomNumber(1, 39); }
/// 기본 틀 렌더링
void renderBorder()
{
Sleep(10);
gotoxy(0, 0); printf("┌");
gotoxy(40*2-1, 0); printf("┐");
gotoxy(40*2-1, 40); printf("┘");
gotoxy(0, 40); printf("└");
for (int i = 1; i < 40; i++)
{
gotoxy(i*2-1, 0); printf("──");
gotoxy(i*2-1, 40); printf("──");
gotoxy(0, i); printf("│");
gotoxy(40*2-1, i); printf("│");
}
puts("");
}
void setColor(int col)
{
SetConsoleTextAttribute(stdHandle, col);
}
/// 스네이크의 기본 위치에 렌더링
void renderFirstSnake()
{
gotoMapXY(10, 20); setColor(Green); printf("██");
for (int i = 6; i <= 9; i++)
{
setColor(LightGreen);
gotoMapXY(i, 20);
printf("██");
}
setColor(White);
}
typedef struct Node {
Location data;
struct Node* prev;
struct Node* next;
}Node;
// Snake 구조체 구현을 위한 덱 자료구조 구현
typedef struct Deque {
Node* head;
Node* tail;
int size;
void (*push_front)(struct Deque* _d, Location data);
void (*push_back)(struct Deque* _d, Location data);
Location (*front)(struct Deque* _d);
Location (*back)(struct Deque* _d);
void (*pop_front)(struct Deque* _d);
void (*pop_back)(struct Deque* _d);
}Deque;
void _push_front(Deque* d, Location data)
{
Node* n = malloc(sizeof *n);
n->data = data;
n->prev = NULL;
n->next = d->head;
if (d->head)
d->head->prev = n;
else
d->tail = n;
d->head = n;
d->size++;
}
void _push_back(Deque* d, Location data)
{
Node* n = malloc(sizeof *n);
n->data = data;
n->next = NULL;
n->prev = d->tail;
if (d->tail)
d->tail->next = n;
else
d->head = n;
d->tail = n;
d->size++;
}
Location _front(Deque* _d) { return _d->head->data; }
Location _back(Deque* _d) { return _d->tail->data; }
void _pop_front(Deque* _d) {
if (_d->size <= 0) return;
Node* newHead = _d->head->next;
free(_d->head);
_d->head = newHead;
_d->size--;
}
void _pop_back(Deque* _d) {
if (_d->size <= 0) return;
Node* newTail = _d->tail->prev;
free(_d->tail);
_d->tail = newTail;
_d->size--;
}
Deque* newDeque() {
Deque* D = (Deque*)malloc(sizeof(Deque));
D->size = 0;
D->head = NULL;
D->tail = NULL;
D->push_front = _push_front;
D->push_back = _push_back;
D->front = _front;
D->back = _back;
D->pop_back = _pop_back;
D->pop_front = _pop_front;
return D;
}
typedef struct StrNode {
char* data;
struct StrNode* prev;
struct StrNode* next;
}StrNode;
void renderRect(int H, int W, COORD start) {
gotoxy(start.X, start.Y);
printf("┌");
gotoxy(start.X, start.Y+H-1);
printf("└");
for (int i = 1; i < W-1; i++) {
gotoxy(start.X+i*2-1, start.Y);
printf("──");
gotoxy(start.X+i*2-1, start.Y+H-1);
printf("──");
}
gotoxy(start.X+(W - 1)*2-1, start.Y);
printf("┐");
gotoxy(start.X+(W - 1)*2-1, start.Y+H-1);
printf("┘");
for (int i = 1; i < H-1; i++) {
gotoxy(start.X, start.Y + i);
printf("│");
gotoxy(start.X + (W - 1)*2-1, start.Y + i);
printf("│");
}
}
// Snake 구조체 구현을 위한 덱 자료구조 구현
typedef struct StrDeque {
StrNode* head;
StrNode* tail;
int size;
void (*push_front)(struct StrDeque* _d, char* data);
void (*push_back)(struct StrDeque* _d, char* data);
char* (*front)(struct StrDeque* _d);
char* (*back)(struct StrDeque* _d);
void (*pop_front)(struct StrDeque* _d);
void (*pop_back)(struct StrDeque* _d);
int (*find)(struct StrDeque* _d,char* E);
char* (*at)(struct StrDeque* _d,int index);
void (*change)(struct StrDeque* _d,int index,char* E);
}StrDeque;
int _2find(StrDeque* _d, char* E) {
int ret = -1;
StrNode* cur = _d->head;
while (cur != NULL) {
ret++;
if (strcmp(cur->data, E) == 0) return ret;
cur = cur->next;
}
return -1;
}
char* _2at(StrDeque* _d, int index) {
StrNode* cur = _d->head;
for (int i = 0; i < index; i++) {
cur = cur->next;
}
return cur->data;
}
void _2change(StrDeque* _d, int index, char* E) {
StrNode* cur = _d->head;
for (int i = 0; i < index; i++) {
cur = cur->next;
}
cur->data = E;
}
void _2push_front(StrDeque* d, char* data)
{
StrNode* n = malloc(sizeof *n);
n->data = data;
n->prev = NULL;
n->next = d->head;
if (d->head)
d->head->prev = n;
else
d->tail = n;
d->head = n;
d->size++;
}
void _2push_back(StrDeque* d, char* data)
{
StrNode* n = malloc(sizeof *n);
n->data = data;
n->next = NULL;
n->prev = d->tail;
if (d->tail)
d->tail->next = n;
else
d->head = n;
d->tail = n;
d->size++;
}
char* _2front(StrDeque* _d) { return _d->head->data; }
char* _2back(StrDeque* _d) { return _d->tail->data; }
void _2pop_front(StrDeque* _d) {
if (_d->size <= 0) return;
StrNode* newHead = _d->head->next;
free(_d->head);
_d->head = newHead;
_d->size--;
}
void _2pop_back(StrDeque* _d) {
if (_d->size <= 0) return;
StrNode* newTail = _d->tail->prev;
free(_d->tail);
_d->tail = newTail;
_d->size--;
}
StrDeque* newStrDeque() {
StrDeque* D = (StrDeque*)malloc(sizeof(StrDeque));
D->size = 0;
D->head = NULL;
D->tail = NULL;
D->push_front = _2push_front;
D->push_back = _2push_back;
D->front = _2front;
D->back = _2back;
D->pop_back = _2pop_back;
D->pop_front = _2pop_front;
D->find = _2find;
D->at = _2at;
D->change = _2change;
return D;
}
typedef struct Snake {
bool isGameOvered;
Location here;
int facing, score, speed;
int ms_per_block;
Deque block;
DirQ inputQ;
char map[40][40];
void (*addScore)(struct Snake* S, int sc);
void (*addSpeed)(struct Snake* S, int sp);
void (*generateKillTriangle)(struct Snake* S);
void (*setFacing)(struct Snake* S, int facing);
bool (*Move)(struct Snake* S);
void (*generateApple)(struct Snake* S);
}Snake;
void _addScore(Snake* S, int sc) {
S->score += sc;
gotoxy(120, 4);
setColor(LightGreen);
printf("현재 스코어: %d점", S->score);
setColor(White);
}
void _addSpeed(Snake* S, int sp) {
if (S->speed - sp < 10) return;
setColor(LightBlue);
S->speed -= sp;
S->ms_per_block = S->speed;
gotoxy(120, 5);
printf("현재 속도: %d ", S->speed);
setColor(White);
}
void _generateKillTriangle(Snake* S) {
Location R;
do {
R.x = getRandomNumber(1, 39);
R.y = getRandomNumber(1, 39);
} while (S->map[R.y][R.x] != '.');
S->map[R.y][R.x] = 'T';
gotoMapLoc(R);
setColor(LightRed);
printf("▲");
setColor(White);
}
void _setFacing(Snake* S, int newFacing) {
if (ReverseDirection(S->facing) == newFacing) return;
S->facing = newFacing;
}
/// @brief 스네이크의 틱 당 움직임을 처리하는 함수
/// @return 스네이크가 정상적으로 움직임에 성공했으면 true, 벽 등에 충돌한 경우 false
bool _Move(Snake* S) {
Location to = DIRtoLOC(S->here, S->facing);
Location here = S->here;
Deque* block = &(S->block);
setColor(LightGreen);
// 벽에 충돌하는 경우
if (isOutOfRange(to)) return true;
// 만약 가려는 곳에 사과가 있다면
if (S->map[to.y][to.x] == 'A') {
block->push_front(block, to);
S->map[here.y][here.x] = 'o';
S->map[to.y][to.x] = 'O';
// 사과를 먹었으므로 lazy하게 화면 업데이트
gotoMapLoc(here);
printf("██");
gotoMapLoc(to);
printf("██");
setColor(LightGreen);
S->generateApple(S);
S->generateKillTriangle(S);
S->addScore(S, 100);
S->addSpeed(S, 10);
} else if (S->map[to.y][to.x] == '.') {
Location removal = block->back(block);
block->pop_back(block);
block->push_front(block, to);
S->map[removal.y][removal.x] = '.';
S->map[here.y][here.x] = 'o';
S->map[to.y][to.x] = 'O';
gotoMapLoc(removal);
printf(" ");
gotoMapLoc(here);
printf("██");
gotoMapLoc(to);
printf("██");
setColor(LightGreen);
} else {
return true;
}
S->here = to;
S->addScore(S, 1);
setColor(White);
return false;
}
void _generateApple(Snake* S) {
Location R;
do {
R.x = getRandomNumber(1, 39);
R.y = getRandomNumber(1, 39);
} while (S->map[R.y][R.x] != '.');
S->map[R.y][R.x] = 'A';
gotoMapLoc(R);
setColor(Yellow);
printf("★");
setColor(White);
}
Snake* newSnake() {
Snake* newS = (Snake*)malloc(sizeof(Snake));
newS->block = *(newDeque());
Deque* block = &(newS->block);
newS->isGameOvered = false;
newS->score = 0;
newS->speed = 150;
for (int i = 1; i < 40; i++) {
for (int j = 1; j < 40; j++) {
newS->map[i][j] = '.';
}
}
newS->here.x = 10;
newS->here.y = 20;
for (int x = 10; x >= 6; x--) {
Location L = {x, 20};
block->push_back(block, L);
newS->map[20][x] = 'o';
}
newS->map[20][10] = 'O';
newS->addScore = _addScore;
newS->addSpeed = _addSpeed;
newS->setFacing = _setFacing;
newS->Move = _Move;
newS->generateApple = _generateApple;
newS->generateKillTriangle = _generateKillTriangle;
newS->facing = Right;
dq_init(&newS->inputQ);
return newS;
}
Snake* player;
void lobby();
DWORD WINAPI moveSnakeThread(LPVOID lpParam){
player->generateApple(player);
while (!player->isGameOvered){
if (!dq_empty(&player->inputQ)){
int nextDir = dq_pop(&player->inputQ);
player->setFacing(player, nextDir);
}
player->isGameOvered = player->Move(player);
Sleep(player->ms_per_block);
}
return 0;
}
DWORD WINAPI rotateSnakeThread(LPVOID lpParam){
bool prev[4] = {0};
while (!player->isGameOvered){
const int vk[4] = {VK_RIGHT, VK_LEFT, VK_UP, VK_DOWN};
for (int i=0;i<4;i++){
bool now = GetAsyncKeyState(vk[i]) & 0x8000;
if (now && !prev[i]){
if (ReverseDirection(player->facing) != i)
dq_push(&player->inputQ, i);
}
prev[i] = now;
}
}
return 0;
}
/// ----- 멀티 플레이어 지원을 위한 여러 자료구조 및 프로토콜 포맷 설정 -----
/// JSON 포맷 직접 구현, 직렬화 및 역직렬화 구현
typedef struct JSON {
StrDeque* properties;
StrDeque* values;
void (*set)(struct JSON* J, char* _property, char* value);
char* (*get)(struct JSON* J, char* _property);
char* (*toString)(struct JSON* J);
void (*load)(struct JSON* J, char* S);
}JSON;
void _jload(JSON* J, char* S) {
J->properties = newStrDeque();
J->values = newStrDeque();
char *p = S;
while (*p && *p != '{') p++;
if (!*p) return;
p++;
while (*p) {
while (isspace((unsigned char)*p) || *p == ',') p++;
if (*p == '}' || *p == '\0') break;
if (*p != '\"') break;
p++;
char key[128];
int ki = 0;
while (*p && *p != '\"' && ki < (int)(sizeof(key)-1))
key[ki++] = *p++;
key[ki] = '\0';
if (*p == '\"') p++;
while (*p && *p != ':') p++;
if (*p == ':') p++;
while (isspace((unsigned char)*p)) p++;
char val[256];
int vi = 0;
if (*p == '\"') {
// string value
p++;
while (*p && *p != '\"' && vi < (int)(sizeof(val)-1))
val[vi++] = *p++;
if (*p == '\"') p++;
} else {
// non‐string
while (*p && *p != '}' && *p != ',' &&
!isspace((unsigned char)*p) &&
vi < (int)(sizeof(val)-1))
val[vi++] = *p++;
}
val[vi] = '\0';
J->properties->push_back(J->properties, strdup(key));
J->values->push_back(J->values, strdup(val));
}
}
char* _jtoString(JSON* J) {
size_t buf_size = 1024;
char *ret = malloc(buf_size);
if (!ret) return NULL;
strcpy(ret, "{");
StrDeque* properties = J->properties;
StrDeque* values = J->values;
StrNode* curProp = properties->head;
StrNode* curVal = values->head;
while (curProp) {
// Append "key":value
strcat(ret, "\"");
strcat(ret, curProp->data);
strcat(ret, "\":");
strcat(ret, curVal->data);
if (curProp->next) {
strcat(ret, ",");
}
curProp = curProp->next;
curVal = curVal->next;
}
strcat(ret, "}");
return ret;
}
void _jset(JSON* J, char* property, char* value) {
int idx = J->properties->find(J->properties, property);
if (idx == -1) {
J->properties->push_back(J->properties,property);
J->values->push_back(J->values,value);
} else {
J->values->change(J->values, idx, value);
}
}
char* _jget(JSON* J, char* property) {
int idx = J->properties->find(J->properties, property);
if (idx == -1) {
MessageBoxA(NULL, "No such element in JSON", "ERROR", MB_ICONERROR);
exit(0);
} else {
return J->values->at(J->values, idx);
}
}
JSON* newJSON() {
JSON* J = (JSON*)malloc(sizeof(JSON));
J->properties = newStrDeque();
J->values = newStrDeque();
J->set = _jset;
J->get = _jget;
J->toString = _jtoString;
J->load = _jload;
return J;
}
long long lastPing = -1;
long long getNowMS() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000LL + tv.tv_usec;
}
/// source에 F가 몇 개 있는지 세서 반환
int getCountInStr(char* source, char F) {
int len = strlen(source);
int ret = 0;
int i;
for (i = 0; source[i] != ';'; i++)
ret += (source[i] == F);
source[i] = '\0';
return ret;
}
/// !!! HTTP 프로토콜처럼 통신, POST 메서드
JSON* POST(SOCKET S, JSON* J) {
const char *msg = J->toString(J); // '\n' 구분자 필수
long long T1 = getNowMS();
if (psend(S, msg, (int)strlen(msg), 0) == SOCKET_ERROR) {
MessageBoxA(NULL, "send() 실패", "ERROR", MB_ICONERROR);
exit(0);
}
long long T2 = -1;
char buf[1024] = {0};
int total = 0;
while (total < sizeof buf - 1) { // '\n' 올 때까지 모음
int n = precv(S, buf + total, 1, 0); // 1바이트씩 읽기(단순)
if (T2 == -1) T2 = getNowMS();
if (n <= 0) break;
if (buf[total++] == '\n') break;
}
buf[total-1] = '\0';
lastPing = T2-T1;
if ( DEBUG ) {
gotoxy(0, 30); printf("[JSON LOGGER] %s \n", buf);
}
JSON* response = newJSON();
response->load(response, buf);
return response;
}
/// 파일에서 전체 JSON 로드 후 J에 채워넣고 반환
static JSON* loadStorage(void) {
JSON* storage = newJSON();
FILE* fp = fopen(LOCAL_STORAGE_FILE, "r");
if (fp) {
char buf[4096];
size_t n = fread(buf, 1, sizeof(buf) - 1, fp);
buf[n] = '\0';
fclose(fp);
storage->load(storage, buf);
}
return storage;
}
/// JSON을 직렬화해서 파일에 쓰기
static void saveStorage(JSON* storage) {
char* out = storage->toString(storage);
FILE* fp = fopen(LOCAL_STORAGE_FILE, "w");
if (fp) {
fprintf(fp, "%s", out);
fclose(fp);
}
free(out);
}
void saveToLocalStorage(char* property, char* value) {
JSON* storage = loadStorage();
storage->set(storage, property, value);
saveStorage(storage);
}
/// 로컬스토리지에서 프로퍼티 읽기 (없으면 NULL 반환)
char* loadFromLocalStorage(char* property) {
JSON* storage = loadStorage();
// 존재하지 않으면 NULL, 있으면 strdup된 문자열 반환
int idx = storage->properties->find(storage->properties, property);
if (idx == -1) {
return NULL;
}
return strdup(storage->values->at(storage->values, idx));
}
/// 싱글 플레이 전용 게임 오버 스크린
void GameOver() {
COORD T= {0, 0};
FillConsoleOutputCharacter(stdHandle, ' ', 300 * 300, T, &dw);
gotoxy(0, 0);
setColor(Red);
puts(" _______ _______ __ __ _______ _______ __ __ _______ ______ ");
puts("| || _ || |_| || | | || | | || || _ | ");
puts("| ___|| |_| || || ___| | _ || |_| || ___|| | || ");
puts("| | __ | || || |___ | | | || || |___ | |_||_ ");
puts("| || || || || ___| | |_| || || ___|| __ |");
puts("| |_| || _ || ||_|| || |___ | | | | | |___ | | | |");
puts("|_______||__| |__||_| |_||_______| |_______| |___| |_______||___| |_|");
setColor(White);
gotoxy(60, 15);
printf("최종 스코어: ");
int sc = player->score;
int WaitingTime = 200;
for (int i = 0; i <= sc; i++)
{
gotoxy(73, 15);
printf(" ");
gotoxy(73, 15);
printf("%d", i);
WaitingTime -= WaitingTime * 0.1;
Sleep(WaitingTime);
}
gotoxy(0, 9);
if (sc < 300)
{
setColor(Red);
puts(" _______ ");
puts(" | |");
puts(" | ___|");
puts(" | |___ ");
puts(" | ___|");
puts(" | | ");
puts(" |___| ");
}
else if (sc < 700)
{
setColor(Blue);
puts(" _______ ");
puts(" | |");
puts(" | ___|");
puts(" | | ");
puts(" | |___ ");
puts(" | |");
puts(" |_______|");
}
else if (sc < 2000)
{
setColor(BlueGreen);
puts(" _______ ");
puts(" | _ |");
puts(" | |_| |");
puts(" | _|");
puts(" | _ |_ ");
puts(" | |_| |");
puts(" |_______|");
}
else if (sc < 3000)
{
setColor(Green);
puts(" _______ ");
puts(" | _ |");
puts(" | | | |");
puts(" | |_| |");
puts(" | |");
puts(" | _ |");
puts(" |__| |__|");
}
else if (sc < 5000)
{
setColor(LightGreen);
puts(" _______ _ ");
puts(" | _ | _| |_ ");
puts(" | | | ||_ _| ");
puts(" | |_| | |_| ");
puts(" | |");
puts(" | _ |");
puts(" |__| |__|");
}
else if (sc < 10000)
{
setColor(Yellow);
puts(" _______ ");
puts(" | |");
puts(" | _____|");
puts(" | |_____ ");
puts(" |_____ |");
puts(" _____| |");
puts(" |_______|");
}
else
{
setColor(LightYellow);
puts(" _______ _ ");
puts(" | | _| |_ ");
puts(" | _____||_ _| ");
puts(" | |_____ |_| ");
puts(" |_____ |");
puts(" _____| |");
puts(" |_______|");
}
setColor(Yellow);
if (online) {
JSON* ujson = newJSON();
ujson->set(ujson, "to", "'/us'");
char str[20];
char str2[20];
sprintf(str, "'%s'\0", loadFromLocalStorage("clientID"));
sprintf(str2, "%d", sc);
ujson->set(ujson, "cl", str);
ujson->set(ujson, "sc", str2);
POST(s, ujson);
JSON* json = newJSON();
json->set(json, "to", "'/getRankings'");
JSON* rankingResponse = POST(s, json);
//JSON* rankingResponse; rankingResponse->load(rankingResponse, "{status:200,text:'dgffjfkjas, fjfjsdfjgo'");
char* rankingList = rankingResponse->get(rankingResponse, "text");
int rankCount = getCountInStr(rankingList, ',')+1;
char** rankIDList = (char**)malloc(sizeof(char*) * rankCount);
JSON** rankInfoList = (JSON**)malloc(sizeof(JSON*) * rankCount);
int i = 0;
char *ptr = strtok(rankingList,",");
while (ptr != NULL) {
rankIDList[i] = (char*)malloc(sizeof(char)*12);