<토이프로젝트>/[C언어 게임]

[C언어 게임] 뱀 게임 (Snake Game with C)

BlockDMask 2017. 7. 4. 16:25
반응형

안녕하세요. BlockDMask입니다.

설명하기 전에, 플레이 영상먼저 보겠습니다.

제 유튜브에 가면 초기 버전부터 점점 발전해 오는 모습의 영상을 보실수 있습니다.

Play List

현재 보시는 영상은 마지막 영상으로서 v3.3 최신 버전입니다.

Stage4가 가장 어려운데, 도전해보실분은 아래 파일 다운로드 하셔서 즐겨보세요~!

댓글 남겨주시기 바랍니다.

자막을 키면 아래 설명이 나옵니다.


1. Intro

이름 : mySnake Game / C언어 뱀게임

요약 : C언어로 만든 뱀 게임입니다. 콘솔 환경에서만 돌아갑니다. (.exe파일)

기간 : 2017년 05월 18일 ~ 2017년 05월 26일  + 5월 30일. (8일 - 주말제외)

(퇴근하고 개발하고 자고, 퇴근하고 집에가서 개발하고 자고, 퇴근하고 여친만나고... 주말에도 여친만나고....그래서 주말엔 안?못?했습니다)

(5/30일에 색 입히는 방법을 알게되어서 추가로 색을 입혔습니다.)

인원 : 본인 한명

코드 : 글 하단에 링크 걸었습니다.

실행파일 : EXE 파일은 글 하단에 첨부했습니다.! zip파일인데 바이러스는 없습니다! (하하..)

영상 : 유튜브 <- 클릭

비고 : 처음으로 만든 C언어 게임, C언어 콘솔 게임입니다. 많이 부족합니다. 좋은 지적 부탁드립니다.

+ gotoxy, 키보드 방향 입력 받는것 등 window 함수만 인터넷에서 찾아보고 나머지는 0에서부터 혼자서 구현했습니다.

+ 자료구조를 써서 구현해보려고 했습니다. (Queue 사용했습니다)


<MAP>

- 맵은 2차원 배열을 이용해서 구현했습니다. 

- 2차원 배열(=맵) 에서 WALL인 부분, EMPTY인 부분을 구분해서 출력해줍니다.

- gotoxy 함수를 이용하여 앞쪽에서(실제 user에게 보여지는) 출력을 해주고, 그것에 대한 데이터를 뒤에서(2차원 배열) 저장해주는 방식으로 구현했습니다.



<Snake>

- 뱀은 뱀의 머리와, 꼬리로 구분을 했습니다.

- 꼬리부분은 계속 출력이 되는데, 이때 Enqueue를 통해서 출력되는 꼬리를 저장해 두었다가, Dequeue를 통해서 삭제를 하는 방식으로 진행했습니다. 맵에서 계속 꼬리를 출력하고, 과일(별사탕)을 먹을때 마다 Dequeue를 한번 쉬고 하는 방식으로 꼬리를 하나씩 늘려서(delay해서?) 지웠습니다.

- 뱀의 방향은 좌->우, 우->좌, 상->하, 하->상 으로 바로 가지 못하도록 구현했습니다.



<기능>

0. 방향키(↑, ↓, ←, →)로 방향 조절합니다.

1. Score가 기록이 됩니다. 과일 하나를 먹을때마다 +5점.

2. Best Score 는 기록이 되어서, exe와 같은 폴더 내에 "score.txt" 파일로 저장이 됩니다. 파일 입출력을 이용하여서, exe파일이 시작 될때 "score.txt" 파일의 내용을 불러와서, Best Score를 기록합니다.

3. 4가지의 스테이지가 존재합니다. 1~4번 버튼을 누르면 해당 스테이지에서 게임이 시작됩니다.

4. 벽에 부딪히거나, 꼬리와 부딪히게 되면 현재 점수를 출력하고 게임이 종료됩니다. 

(좌측위에 hit : ㅁㅁㅁ 로그가 죽음의이유 출력됩니다.)

5. 게임중 't | T' 를 누르면 현재 스코어를 저장하지 않고 메인화면으로 이동합니다.

6. 게임중 'p | P'를 누르면 일시정지 하게됩니다. 다시 'p | P'를 누르면 개임이 다시 시작 됩니다.

7. 메인화면에서 't | T'를 누르면 프로그램이 종료됩니다.



2. 소스코드


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
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <Windows.h>
#include <time.h>
 
#define DEFAULT_X 0
#define DEFAULT_Y 0
 
#define UP 72
#define LEFT 75
#define RIGHT 77
#define DOWN 80
#define MAP_SIZE 22
 
#define WALL 1
#define EMPTY 0
#define HEAD 2
#define TAIL 3
#define FRUIT 5
#define COLLISION 10
 
#define TRUE 1
#define FALSE 0
 
#define NORMAL 10
 
 
typedef int MData;
 
typedef struct _fruitxy {
    int x;
    int y;
    int numOfFruit;
} FruitPos;
 
typedef struct _snakexp {
    int x;
    int y;
} SnakePos;
 
 
///////////////////////////QUEUE//////////////////////////////////////////
 
//typedef int QData;
typedef struct _mynode {
    SnakePos data;
    struct _mynode *next;
} Node;
 
typedef struct _myqueue {
    Node * rear;
    Node * front;
} MyQueue;
typedef MyQueue Queue;
 
void QueueInit(Queue * pq) {
    pq->rear = NULL;
    pq->front = NULL;
}
int isEmpty(Queue * pq) {
    if (pq->front == NULL)
        return TRUE;
    else
        return FALSE;
}
void Enqueue(Queue * pq, SnakePos data) {
    Node * newNode = (Node *)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    if (pq->front == NULL) {
        pq->rear = newNode;
        pq->front = newNode;
    }
    else {
        pq->rear->next = newNode;
        pq->rear = newNode;
    }
}
SnakePos Dequeue(Queue * pq) {
    Node * delNode;
    SnakePos delData = { 0,0 };
    if (isEmpty(pq)) {
        return delData;
    }
    delNode = pq->front;
    delData = delNode->data;
    pq->front = pq->front->next;
    free(delNode);
    return delData;
}
SnakePos Peek(Queue * pq) {
    return pq->front->data;
}
///////////////////////////////////////////////////////////////////////////
 
//keyboard input
int getKeyDown() {
    if (_kbhit()) return _getch();
    return -1;
}
 
//move cursor
void gotoxy(int x, int y) {
    COORD Pos;
    Pos.X = 2 * x;
    Pos.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);
}
 
void hidecursor() {
    HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO info;
    info.dwSize = 100;
    info.bVisible = FALSE;
    SetConsoleCursorInfo(consoleHandle, &info);
}
 
 
//show start menu
int drawStartMenu() {
    HANDLE hand = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hand, 13);
    gotoxy(DEFAULT_X, DEFAULT_Y);
    printf("============================================");
    SetConsoleTextAttribute(hand, 14);
    printf("================ Snake Game ================");
    SetConsoleTextAttribute(hand, 11);
    printf("============================================");
    SetConsoleTextAttribute(hand, 15);
    gotoxy(DEFAULT_X, DEFAULT_Y + 4);
    printf("> Key  : up, down, left, right,");
    gotoxy(DEFAULT_X, DEFAULT_Y + 5);
    printf("> Exit : 't'");
 
    gotoxy(DEFAULT_X + 11, DEFAULT_Y + 14);
    printf("<Made by BlockDMask.>");
    gotoxy(DEFAULT_X + 11, DEFAULT_Y + 15);
    printf("<BlockDMask@gmail.com>");
 
 
    SetConsoleTextAttribute(hand, 14);
    while (1) {
        int keyDown = getKeyDown();
        if (keyDown == 's' || keyDown == 'S') {
            SetConsoleTextAttribute(hand, 7);
            return TRUE;
        }
        if (keyDown == 't' || keyDown == 'T') {
            SetConsoleTextAttribute(hand, 7);
            return FALSE;
        }
        gotoxy(DEFAULT_X + 5, DEFAULT_Y + 9);
        printf("-- press 's' to start --");
        Sleep(1000 / 3);
        gotoxy(DEFAULT_X + 5, DEFAULT_Y + 9);
        printf("                         ");
        Sleep(1000 / 3);
    }
 
}
//show stage Menu and score;
int drawSpeedMenu(int * scoreArr) {
    HANDLE hand = GetStdHandle(STD_OUTPUT_HANDLE);
 
    int i;
    FILE * rfp, *wfp;
    rfp = fopen("score.txt""r");
    SetConsoleTextAttribute(hand, 11);
    gotoxy(DEFAULT_X, DEFAULT_Y);
    printf("============================================");
    SetConsoleTextAttribute(hand, 14);
    gotoxy(DEFAULT_X, DEFAULT_Y + 1);
    printf("================ BEST SCORE ================");
    SetConsoleTextAttribute(hand, 13);
    gotoxy(DEFAULT_X, DEFAULT_Y + 2);
    printf("============================================");
    SetConsoleTextAttribute(hand, 15);
    if (rfp == NULL) {
        wfp = fopen("score.txt""w");
        fprintf(wfp, "%d %d %d %d", scoreArr[0], scoreArr[1], scoreArr[2], scoreArr[3]);
        for (i = 0; i < 4; i++) {
            gotoxy(DEFAULT_X, DEFAULT_Y + (i + 4));
            printf(" Stage [%d] : %d", i + 1, scoreArr[i]);
        }
        fclose(wfp);
    }
    fscanf(rfp, "%d %d %d %d"&scoreArr[0], &scoreArr[1], &scoreArr[2], &scoreArr[3]);
    for (i = 0; i < 4; i++) {
        gotoxy(DEFAULT_X, DEFAULT_Y + (i + 4));
        printf(" Stage [%d] : %d", i + 1, scoreArr[i]);
    }
 
    fclose(rfp);
 
    while (1) {
        int keyDown = getKeyDown();
        if (keyDown == '1') {
            SetConsoleTextAttribute(hand, 7);
            return 1;
        }
        if (keyDown == '2') {
            SetConsoleTextAttribute(hand, 7);
            return 2;
        }
        if (keyDown == '3') {
            SetConsoleTextAttribute(hand, 7);
            return 3;
        }
        if (keyDown == '4') {
            SetConsoleTextAttribute(hand, 7);
            return 4;
        }
        SetConsoleTextAttribute(hand, 14);
        gotoxy(DEFAULT_X, DEFAULT_Y + 9);
        printf(">> Choose Stage : 1, 2, 3, 4");
        Sleep(1000 / 3);
        gotoxy(DEFAULT_X, DEFAULT_Y + 9);
        printf(">>                          ");
        Sleep(1000 / 3);
    }
 
}
 
//////////////////////////////////////STAGE MAP SETTING////////////////////////////////
void stageClear(MData map[MAP_SIZE][MAP_SIZE]) {
    int i, j;
    for (i = 0; i <= MAP_SIZE; i++) {
        for (j = 0; i <= MAP_SIZE; j++) {
            map[i][j] = EMPTY;
        }
    }
}
 
void stageOneInit(MData map[MAP_SIZE][MAP_SIZE]) {
    int i, j;
    for (i = 0; i < MAP_SIZE; i++) {
        if (i == 0 || i == MAP_SIZE - 1) {
            for (j = 0; j < MAP_SIZE; j++) {
                map[i][j] = WALL;
            }
        }
        else {
            for (j = 0; j < MAP_SIZE; j++) {
                if (j == 0 || j == MAP_SIZE - 1)
                    map[i][j] = WALL;
                else
                    map[i][j] = EMPTY;
            }
        }
 
    }
}
 
void stageTwoInit(MData map[MAP_SIZE][MAP_SIZE]) {
    int i, j;
    for (i = 0; i < MAP_SIZE; i++) {
        for (j = 0; j < MAP_SIZE; j++) {
            if (i == (int)MAP_SIZE / 2 || j == 0 || j == MAP_SIZE - 1) {
                map[i][j] = WALL;
            }
            else {
                map[i][j] = EMPTY;
            }
        }
 
    }
}
void stageThreeInit(MData map[MAP_SIZE][MAP_SIZE]) {
    int i, j;
    for (i = 0; i < MAP_SIZE; i++) {
        for (j = 0; j < MAP_SIZE; j++) {
            if (i == MAP_SIZE / 2 || j == MAP_SIZE / 2) {
                map[i][j] = WALL;
            }
            else {
                map[i][j] = EMPTY;
            }
        }
    }
}
 
void stageFourinit(MData map[MAP_SIZE][MAP_SIZE]) {
    int i, j;
    for (i = 0; i < MAP_SIZE; i++) {
        for (j = 0; j < MAP_SIZE; j++) {
            if (i == j || i + j == MAP_SIZE - 1) {
                if (i == MAP_SIZE / 2 - 1 || i == MAP_SIZE / 2)
                    map[i][j] = EMPTY;
                else
                    map[i][j] = WALL;
 
            }
            else {
                map[i][j] = EMPTY;
            }
        }
    }
}
 
//////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// D R A W ////////////////////////////////////////
 
//draw game map
void drawMainMap(MData map[MAP_SIZE][MAP_SIZE]) {
    HANDLE hand = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hand, 15);
 
    int i, j;
    for (i = 0; i < MAP_SIZE; i++) {
        for (j = 0; j < MAP_SIZE; j++) {
            if (map[i][j] == WALL) {
                gotoxy(i, j);
                printf("□");
            }
            else if (map[i][j] == EMPTY) {
                gotoxy(i, j);
                printf(" ");
            }
        }
    }
    SetConsoleTextAttribute(hand, 7);
}
 
 
void drawSubMap(int score, int best, int stage) {
    HANDLE hand = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hand, 15);
 
    gotoxy(DEFAULT_X, MAP_SIZE + 1);
    printf(" Stage[%d] Best Score : %4d", stage, best);
    gotoxy(DEFAULT_X, MAP_SIZE + 2);
    printf(" Stage[%d] Your Score : %4d", stage, score);
    gotoxy(DEFAULT_X + 8, MAP_SIZE + 5);
    printf("[Exit - 't' / Pause - 'p']\n");
    SetConsoleTextAttribute(hand, 7);
 
 
}
/////////////////////////////////////////////////////////////////////////////////////
 
int setFruit(MData map[MAP_SIZE][MAP_SIZE], FruitPos * fp) {
    // i,j >0  &&  i,j < MAP_SIZE-1i
    HANDLE  hand = GetStdHandle(STD_OUTPUT_HANDLE);
    int i, j;
    srand((unsigned int)time(NULL));
    while (1) {
        i = rand() % (MAP_SIZE - 2+ 1;
        j = rand() % (MAP_SIZE - 2+ 1;
        if (map[i][j] == EMPTY) {
            map[i][j] = FRUIT;
            fp->= i;
            fp->= j;
            (fp->numOfFruit)++;
            SetConsoleTextAttribute(hand, 10);
            gotoxy(i, j);
            printf("★");
            SetConsoleTextAttribute(hand, 7);
 
            return 1;
        }
    }
}
 
int setBonusFruit(MData map[MAP_SIZE][MAP_SIZE], FruitPos * fp) {
    int i, j, numOfFruit = 0;
    for (i = 0; i < MAP_SIZE - 1; i++) {
        for (j = 0; j < MAP_SIZE; j++) {
            if (map[i][j] == EMPTY) {
                map[i][j] = FRUIT;
                numOfFruit++;
            }
        }
    }
    return numOfFruit;
}
 
void setSnakeTail(MData map[MAP_SIZE][MAP_SIZE], int snake_x, int snake_y) {
    HANDLE hand = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hand, 14);
    gotoxy(snake_x, snake_y);
    //printf("Θ");
    printf("ㆁ");
    map[snake_x][snake_y] = TAIL;
    SetConsoleTextAttribute(hand, 7);
 
}
 
void setSnake(MData map[MAP_SIZE][MAP_SIZE], int snake_x, int snake_y) {
    HANDLE hand = GetStdHandle(STD_OUTPUT_HANDLE);
    gotoxy(snake_x, snake_y);
    SetConsoleTextAttribute(hand, 14);
    printf("●");
    SetConsoleTextAttribute(hand, 7);
    map[snake_x][snake_y] = HEAD;
}
 
void removeSnake(MData map[MAP_SIZE][MAP_SIZE], int snake_x, int snake_y) {
    gotoxy(snake_x, snake_y);
    printf(" ");
    map[snake_x][snake_y] = EMPTY;
}
 
 
int rotate(int xy, int way) {
    if (way == UP || way == LEFT) {
        if (xy - 1 == -1) {
            xy = MAP_SIZE - 1;
        }
        else {
            --(xy);
        }
        return xy;
    }
    if (way == DOWN || way == RIGHT) {
        if (xy + 1 == MAP_SIZE) {
            xy = 0;
        }
        else {
            ++xy;
        }
        return xy;
    }
    return FALSE;
}
 
 
 
int colWithTail(MData map[MAP_SIZE][MAP_SIZE], SnakePos * sp, int way) {
    if (way == UP) {
        if (map[sp->x][rotate(sp->y, way)] == TAIL)
            return TRUE;
    }
    if (way == DOWN) {
        if (map[sp->x][rotate(sp->y, way)] == TAIL)
            return TRUE;
    }
    if (way == LEFT) {
        if (map[rotate(sp->x, way)][sp->y] == TAIL)
            return TRUE;
    }
    if (way == RIGHT) {
        if (map[rotate(sp->x, way)][sp->y] == TAIL)
            return TRUE;
    }
    return FALSE;
}
 
int colWithWall(MData map[MAP_SIZE][MAP_SIZE], SnakePos * sp, int way) {
    if (way == UP) {
        if (map[sp->x][rotate(sp->y, way)] == WALL)
            return TRUE;
    }
    if (way == DOWN) {
        if (map[sp->x][rotate(sp->y, way)] == WALL)
            return TRUE;
    }
    if (way == LEFT) {
        if (map[rotate(sp->x, way)][sp->y] == WALL)
            return TRUE;
    }
    if (way == RIGHT) {
        if (map[rotate(sp->x, way)][sp->y] == WALL)
            return TRUE;
    }
    return FALSE;
}
 
 
//get snake x, y and move snake
int moveSnakeHead(MData map[MAP_SIZE][MAP_SIZE], SnakePos * snake, int way) {
    removeSnake(map, snake->x, snake->y);
    if (colWithWall(map, snake, way) == TRUE) {
        gotoxy(11);
        printf("> Hit : wall");
        return COLLISION;
    }
    if (colWithTail(map, snake, way) == TRUE) {
        gotoxy(11);
        printf("> Hit : tail");
        return COLLISION;
    }
 
    if (way == UP) {
        if (snake->- 1 == -1) {
            snake->= MAP_SIZE - 1;
        }
        else {
            --(snake->y);
        }
        setSnake(map, snake->x, (snake->y));
        return UP;
    }
    if (way == DOWN) {
        if (snake->+ 1 == MAP_SIZE) {
            snake->= 0;
        }
        else {
            ++(snake->y);
        }
        setSnake(map, snake->x, (snake->y));
        return DOWN;
    }
    if (way == LEFT) {
        if (snake->- 1 == -1) {
            snake->= MAP_SIZE - 1;
        }
        else {
            --(snake->x);
        }
        setSnake(map, (snake->x), snake->y);
        return LEFT;
    }
    if (way == RIGHT) {
        if (snake->+ 1 == MAP_SIZE) {
            snake->= 0;
        }
        else {
            ++(snake->x);
        }
        setSnake(map, snake->x, snake->y);
        return RIGHT;
    }
    return way;
}
 
int overlap(int savedKey, int key) {
    if (savedKey == UP && key == DOWN)
        return TRUE;
    if (savedKey == DOWN && key == UP)
        return TRUE;
    if (savedKey == LEFT && key == RIGHT)
        return TRUE;
    if (savedKey == RIGHT && key == LEFT)
        return TRUE;
 
    return FALSE;
}
 
int colWithFruit(SnakePos * sp, FruitPos * fp) {
    //meet;->x == fp->x
    if ((sp->== fp->&& sp->== fp->y)) {
        return TRUE;
    }
    return FALSE;
}
 
int isCollision(int state) {
    if (state == COLLISION) return TRUE;
    return FALSE;
}
void GameOver(int score, int best, Queue *pq, int stage, int * scoreArr) {
    FILE * wfp;
    HANDLE hand = GetStdHandle(STD_OUTPUT_HANDLE);
    if (score >= best) {
        scoreArr[stage - 1= score;
    }
    else {
        scoreArr[stage - 1= best;
    }
    wfp = fopen("score.txt""w");
    fprintf(wfp, "%d %d %d %d", scoreArr[0], scoreArr[1], scoreArr[2], scoreArr[3]);
    fclose(wfp);
    SetConsoleTextAttribute(hand, 14);
    gotoxy(MAP_SIZE / 2 - 4, MAP_SIZE / 2 - 5);
    printf("===<GAME OVER>===\n");
    gotoxy(MAP_SIZE / 2 - 3, MAP_SIZE / 2 - 3);
    printf("Your Score : %d\n", score);
    gotoxy(DEFAULT_X + 8, MAP_SIZE + 5);
    printf("\n");
    SetConsoleTextAttribute(hand, 7);
 
    while (!isEmpty(pq)) {
        Dequeue(pq);
    }
}
 
void GameStart(MData map[MAP_SIZE][MAP_SIZE], int stage, int * scoreArr) {
    int best = scoreArr[stage - 1];
    int score = 0;
    int key, savedKey = 0;
    Queue queue;
    QueueInit(&queue);
    SnakePos snake = { MAP_SIZE / 4 - 2, MAP_SIZE / 4 + 1 };
    SnakePos snakeSecond;
    SnakePos snakeTail;
    int time = FALSE;
    FruitPos fruit;
    fruit.numOfFruit = 0;
 
    if (stage == 1) {
        stageOneInit(map);
    }
    else if (stage == 2) {
        stageTwoInit(map);
    }
    else if (stage == 3) {
        stageThreeInit(map);
    }
    else {
        stageFourinit(map);
    }
 
    drawMainMap(map);
    setSnake(map, snake.x, snake.y);
 
    while (1) {
 
        Sleep(1000 / (DWORD)NORMAL);             // snake speed
        if (fruit.numOfFruit == 0) {          // draw fruit
            setFruit(map, &fruit);
        }
        drawSubMap(score, best, stage);
 
        if (colWithFruit(&snake, &fruit) == TRUE) {
            (fruit.numOfFruit)--;
            time = FALSE;
            score += 5;
        }
 
        if (_kbhit()) {
            key = _getch();
            if (key == 't' || key == 'T') {     //exit
                return;
            }
            if (key == 'p' || key == 'P') {
                system("pause");
                gotoxy(DEFAULT_X, MAP_SIZE + 6);
                printf("                                            ");
                gotoxy(DEFAULT_X, DEFAULT_Y);
            }
 
            if (key == 224 || key == 0) {
                key = _getch();
                if (overlap(savedKey, key) == TRUE) {
                    key = savedKey;
                }
                snakeSecond = snake;
                savedKey = moveSnakeHead(map, &snake, key);
                Enqueue(&queue, snakeSecond);
                setSnakeTail(map, snakeSecond.x, snakeSecond.y);
                if (time == TRUE) {
                    snakeTail = Dequeue(&queue);
                    removeSnake(map, snakeTail.x, snakeTail.y);
                }
                else {
                    time = TRUE;
                }
                if (isCollision(savedKey)) { GameOver(score, best, &queue, stage, scoreArr); return; }
            }
        }
        else {
            snakeSecond = snake;
            savedKey = moveSnakeHead(map, &snake, savedKey);
            Enqueue(&queue, snakeSecond);
            setSnakeTail(map, snakeSecond.x, snakeSecond.y);
            if (time == TRUE) {
                snakeTail = Dequeue(&queue);
                removeSnake(map, snakeTail.x, snakeTail.y);
            }
            else {
                time = TRUE;
            }
            if (isCollision(savedKey)) { GameOver(score, best, &queue, stage, scoreArr); return; }
 
        }
    }
}
 
int main() {
    MData map[MAP_SIZE][MAP_SIZE];
    system("color 7");
    hidecursor();
    int stage;
    int scoreArr[4= { 0 };
    while (1) {
        system("mode con: cols=44 lines=30");   //console size
        if (drawStartMenu() == FALSE) break;
        system("cls");
        stage = drawSpeedMenu(scoreArr);
        system("cls");
        GameStart(map, stage, scoreArr);
        system("pause");
    }
    return 0;
}
cs



3. download game

> Download : mySnake.zip

> 소스코드 : https://github.com/BlockDMask/Snake_Game


+궁시렁 : 2달전에 만든 것 인데, 지금 올리게 되었습니다. (티스토리를 이제시작해서..)

+궁시렁 : 사실 유튜브올리면 막 조회수 쫙쫙 오를줄 알았습니다. (;;;;;;)

+궁시렁 : 스테이지 4.... 진짜 헷갈립니다.;;;;해보실분..? (.exe 보내드릴게요 댓글로 메일주소 남겨주세요.)

+궁시렁 : 개인적으로 스테이지 3이 제일 재미있습니다. (나중에 앱으로 만들어서 올려야지)

+궁시렁 : 솔직히 점수는 txt파일 고치면되는데,,,(암호화 안해서) 점수인증은 그럼 막 부딪혔을때 캡쳐하는거로.

+궁시렁 : 다음엔,,,, 제가 만든 콘솔 테트리스를 포스트 하겠습니다.

+궁시렁 : 솔직히 이렇게 정성들인 포스트는 ........ 하트 한번만 꾹 .. 부탁드립니다.

반응형