Home > Mobile >  Why does my fruit respawn outside of the boundaries in snake game?
Why does my fruit respawn outside of the boundaries in snake game?

Time:12-05

I'm trying to make a snake game in which if the snake eats the first fruit and in 2 seconds eats the second fruit then it's score multiplied by 2. If the snake eats the second fruit in 1 second then the score is multiplied by 3. If the snake eats the second fruit in 3 seconds then the score is increased just by 1 and so on ... But after the snake eats about 5-6 fruits the 7th fruit respawns outside of the boundaries. This the "drawing" function

void make_stage() {
score = 0;
int x = 9, y = 9;
int x1 = 8, y1 = 9;
int x2 = 7, y2 = 9;
int x3 = 6, y3 = 9;
int x4 = 5, y4 = 9;
char dir = 'd';
char input = 'e';
gotoxy(x, y);
printf("a");
gotoxy(x1, y1);
printf("*");
gotoxy(x2, y2);
printf("*");
gotoxy(x3, y3);
printf("*");
gotoxy(x4, y4);
printf("*");
for (int i = 1; i <= 17; i  ) {
    gotoxy(i, 1);
    printf("#");
    gotoxy(1, i);
    printf("#");
    gotoxy(17, i);
    printf("#");
    gotoxy(i, 17);
    printf("#");
}
srand(time(NULL));
fruitx = rand() % 17;
fruity = rand() % 17;
gotoxy(fruitx, fruity);
printf("@");
}

And this is the logic function:

void snake_move() {
int x = 9, y = 9;
int x1 = 8, y1 = 9;
int x2 = 7, y2 = 9;
int x3 = 6, y3 = 9;
int x4 = 5, y4 = 9;
char dir = 'd';
char input = 'e';
while (1) {
    srand(time(NULL));
    if (x == fruitx && y == fruity) {
        fruitx = rand() % 17;
        fruity = rand() % 17;
        score  = 1;
        gotoxy(fruitx, fruity);
        printf("@");
    }
    input = _getch();
    if ((dir == 'w' && input != 's') || (dir == 'a' && input != 'd') || (dir == 's' && input != 'w') || (dir == 'd' && input != 'a')) {
        if (input == 'w') {
            gotoxy(x4, y4);
            printf(" ");
            x4 = x3; x3 = x2; x2 = x1; x1 = x;
            y4 = y3; y3 = y2; y2 = y1; y1 = y;
            y = y - 1;
            if (y == 1) {
                gameover();
                break;
            }
            if (x == x4 && y == y4) {
                gameover();
                break;
            }
            gotoxy(x, y);
            printf("a");
            gotoxy(x1, y1);
            printf("*");
            gotoxy(x2, y2);
            printf("*");
            gotoxy(x3, y3);
            printf("*");
            gotoxy(x4, y4);
            printf("*");
            dir = 'w';
        }
        if (input == 'a') {
            gotoxy(x4, y4);
            printf(" ");
            x4 = x3; x3 = x2; x2 = x1; x1 = x;
            y4 = y3; y3 = y2; y2 = y1; y1 = y;
            x = x - 1;
            if (x == 1) {
                gameover();
                break;
            }
            if (x == x4 && y == y4) {
                gameover();
                break;
            }
            gotoxy(x, y);
            printf("a");
            gotoxy(x1, y1);
            printf("*");
            gotoxy(x2, y2);
            printf("*");
            gotoxy(x3, y3);
            printf("*");
            gotoxy(x4, y4);
            printf("*");
            dir = 'a';
        }
        if (input == 's') {
            gotoxy(x4, y4);
            printf(" ");
            x4 = x3; x3 = x2; x2 = x1; x1 = x;
            y4 = y3; y3 = y2; y2 = y1; y1 = y;
            y = y   1;
            if (y == 17) {
                gameover();
                break;
            }
            if (x == x4 && y == y4) {
                gameover();
                break;
            }
            gotoxy(x, y);
            printf("a");
            gotoxy(x1, y1);
            printf("*");
            gotoxy(x2, y2);
            printf("*");
            gotoxy(x3, y3);
            printf("*");
            gotoxy(x4, y4);
            printf("*");
            dir = 's';
        }
        if (input == 'd') {
            gotoxy(x4, y4);
            printf(" ");
            x4 = x3; x3 = x2; x2 = x1; x1 = x;
            y4 = y3; y3 = y2; y2 = y1; y1 = y;
            x = x   1;
            if (x == 17) {
                gameover();
                break;
            }
            if (x == x4 && y == y4) {
                gameover();
                break;
            }
            gotoxy(x, y);
            printf("a");
            gotoxy(x1, y1);
            printf("*");
            gotoxy(x2, y2);
            printf("*");
            gotoxy(x3, y3);
            printf("*");
            gotoxy(x4, y4);
            printf("*");
            dir = 'd';
        }
    }
    if (input == 'p') {
        gameover();
        break;
    }
}
}

and this is the entire source code just in case!

    #include<stdio.h>
    #include<windows.h>
    #include<conio.h>
    #include<time.h>
    #include<stdlib.h>
    #include<process.h>
    int height = 17, width = 17;
    typedef struct RECORD {
        char name[100];
        int score;
        int minute;
        int sec;
    }record; //이름, 점수, 시간을 저장할 구조체
    int score;
    int fruitx, fruity;
    record nowrec;
    
    int over = 0;
    
void gotoxy(int x, int y);          //Input location
void make_stage();                  //stage
int getCommand();                   // Keyboard input
void gameover();                    //Gameover screen
void startscr();                    //Start screen
void snake_move();                  //Snake movements
void rank_call();                   //Displaying rank
void rankrecord();                  //personal records
    void cursor(int i);             //
    void stopwatch();               //stop watch 
    
    int main(void) {
        startscr();
        return 0;
    }
    
    void gotoxy(int x, int y) {
        COORD pos = { 30   x * 2, 10   y };
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
    }
    
    void make_stage() {
        score = 0;
        int x = 9, y = 9;
        int x1 = 8, y1 = 9;
        int x2 = 7, y2 = 9;
        int x3 = 6, y3 = 9;
        int x4 = 5, y4 = 9;
        char dir = 'd';
        char input = 'e';
        gotoxy(x, y);
        printf("a");
        gotoxy(x1, y1);
        printf("*");
        gotoxy(x2, y2);
        printf("*");
        gotoxy(x3, y3);
        printf("*");
        gotoxy(x4, y4);
        printf("*");
        for (int i = 1; i <= 17; i  ) {
            gotoxy(i, 1);
            printf("#");
            gotoxy(1, i);
            printf("#");
            gotoxy(17, i);
            printf("#");
            gotoxy(i, 17);
            printf("#");
        }
        srand(time(NULL));
        fruitx = rand() % 17;
        fruity = rand() % 17;
        gotoxy(fruitx, fruity);
        printf("@");
    }
    
    int getCommand() {
        if (_kbhit()) {
            return _getch();
        }
        return -1;
    }
    
    void cursor(int i) {
        CONSOLE_CURSOR_INFO cursorInfo = { 0, };
        cursorInfo.dwSize = 1;
        cursorInfo.bVisible = i;
        SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
    }
    
    void rank_call() {
        FILE* rank;
        char reading[100];
        if (fopen_s(&rank, "rank.txt", "r") != 0) printf("no record\n");
        else {
            printf("\n");
            while ((fgets(reading, 100, rank) != NULL)) printf("%s", reading);
            fclose(rank);
            printf("\n");
        }
    
    }
    
    void rankrecord() {
        printf("\npress enter to proceed...\n");
        while (getchar() != '\n');
        printf("\n\n\n\n\n\npress r to record your ranking...\n");
        char input = _getch();
        if (input == 'r') {
            FILE* rank;
            fopen_s(&rank, "rank.txt", "a");
        rerun:
            printf("enter your name: ");
            gets_s(nowrec.name, sizeof(nowrec.name));
            if (strlen(nowrec.name) < 3) {
                printf("name must be at least 3 words...\n\n");
                goto rerun;
            }
            while (1) {
                printf("your name is %s.\nyour score is %d.\nyour clear time is %d : %d.\n\n", nowrec.name, nowrec.score, nowrec.minute, nowrec.sec);
                printf("if your name is incorrect, press n to correct\nif not, press y to continue...\n\n");
                input = _getch();
                if (input == 'n') goto rerun;
                else if (input == 'y') break;
                else printf("wrong input\n\n");
            }
            fprintf(rank, "%s %d %d : %d\n", nowrec.name, nowrec.score, nowrec.minute, nowrec.sec);
            fclose(rank);
            printf("saved!\n");
        }
    }
    
    void startscr()
    {
    
        system("mode con cols=100 lines=40");
    start:
    
        system("cls");
        printf("   ******   **    *       *      *    *  ******           ******      *        **    **    ******   \n");
        printf("   *        * *   *      * *     *   *   *                *          * *      *  *  *  *   *        \n");
        printf("   ******   *  *  *     *****    ****    ******           *  ***    *****     *  *  *  *   ******   \n");
        printf("        *   *   * *    *     *   *   *   *                *    *   *     *   *    **    *  *        \n");
        printf("   ******   *    **   *       *  *    *  ******           ******  *       *  *    **    *  ******   \n");
        printf("\npress s to start game\n");
        printf("press r to see ranking\n");
        printf("press x to exit\n:");
        char input = _getch();
        if (input == 's') {
            system("cls");
            cursor(0);
            make_stage();
            HANDLE thread1 = _beginthreadex(NULL, 0, (_beginthreadex_proc_type)stopwatch, NULL, 0, NULL);
            Sleep(1);
            HANDLE thread2 = _beginthreadex(NULL, 0, (_beginthreadex_proc_type)snake_move, NULL, 0, NULL);
            WaitForSingleObject(thread2, INFINITE);
    
        }
        else if (input == 'r') {
            rank_call();
            printf("press enter to continue...");
            while (getchar() != '\n');
            goto start;
        }
        else if (input == 'x') exit(0);
        else {
            printf("wrong input\n");
            printf("press enter to continue...");
            while (getchar() != '\n');
            goto start;
        }
    }
    
    void gameover() {
        over = 1;
        system("cls");
        printf("\n\n\n\n\n\n\n\n\n\n");
        printf("        ******      *        **    **    ******            ****   *       *  ******   *****         \n");
        printf("        *          * *      *  *  *  *   *                *    *   *     *   *        *    *        \n");
        printf("        *  ***    *****     *  *  *  *   ******           *    *    *   *    ******   *****         \n");
        printf("        *    *   *     *   *    **    *  *                *    *     * *     *        *    *        \n");
        printf("        ******  *       *  *    **    *  ******            ****       *      ******   *     *      \n");
        cursor(1);
        rankrecord();
        printf("press any key to back to title...");
        _getch();
        startscr();
    }
    
    void snake_move() {
        int x = 9, y = 9;
        int x1 = 8, y1 = 9;
        int x2 = 7, y2 = 9;
        int x3 = 6, y3 = 9;
        int x4 = 5, y4 = 9;
        char dir = 'd';
        char input = 'e';
        while (1) {
            srand(time(NULL));
            if (x == fruitx && y == fruity) {
                fruitx = rand() % 17;
                fruity = rand() % 17;
                score  = 1;
                gotoxy(fruitx, fruity);
                printf("@");
            }
            input = _getch();
            if ((dir == 'w' && input != 's') || (dir == 'a' && input != 'd') || (dir == 's' && input != 'w') || (dir == 'd' && input != 'a')) {
                if (input == 'w') {
                    gotoxy(x4, y4);
                    printf(" ");
                    x4 = x3; x3 = x2; x2 = x1; x1 = x;
                    y4 = y3; y3 = y2; y2 = y1; y1 = y;
                    y = y - 1;
                    if (y == 1) {
                        gameover();
                        break;
                    }
                    if (x == x4 && y == y4) {
                        gameover();
                        break;
                    }
                    gotoxy(x, y);
                    printf("a");
                    gotoxy(x1, y1);
                    printf("*");
                    gotoxy(x2, y2);
                    printf("*");
                    gotoxy(x3, y3);
                    printf("*");
                    gotoxy(x4, y4);
                    printf("*");
                    dir = 'w';
                }
                if (input == 'a') {
                    gotoxy(x4, y4);
                    printf(" ");
                    x4 = x3; x3 = x2; x2 = x1; x1 = x;
                    y4 = y3; y3 = y2; y2 = y1; y1 = y;
                    x = x - 1;
                    if (x == 1) {
                        gameover();
                        break;
                    }
                    if (x == x4 && y == y4) {
                        gameover();
                        break;
                    }
                    gotoxy(x, y);
                    printf("a");
                    gotoxy(x1, y1);
                    printf("*");
                    gotoxy(x2, y2);
                    printf("*");
                    gotoxy(x3, y3);
                    printf("*");
                    gotoxy(x4, y4);
                    printf("*");
                    dir = 'a';
                }
                if (input == 's') {
                    gotoxy(x4, y4);
                    printf(" ");
                    x4 = x3; x3 = x2; x2 = x1; x1 = x;
                    y4 = y3; y3 = y2; y2 = y1; y1 = y;
                    y = y   1;
                    if (y == 17) {
                        gameover();
                        break;
                    }
                    if (x == x4 && y == y4) {
                        gameover();
                        break;
                    }
                    gotoxy(x, y);
                    printf("a");
                    gotoxy(x1, y1);
                    printf("*");
                    gotoxy(x2, y2);
                    printf("*");
                    gotoxy(x3, y3);
                    printf("*");
                    gotoxy(x4, y4);
                    printf("*");
                    dir = 's';
                }
                if (input == 'd') {
                    gotoxy(x4, y4);
                    printf(" ");
                    x4 = x3; x3 = x2; x2 = x1; x1 = x;
                    y4 = y3; y3 = y2; y2 = y1; y1 = y;
                    x = x   1;
                    if (x == 17) {
                        gameover();
                        break;
                    }
                    if (x == x4 && y == y4) {
                        gameover();
                        break;
                    }
                    gotoxy(x, y);
                    printf("a");
                    gotoxy(x1, y1);
                    printf("*");
                    gotoxy(x2, y2);
                    printf("*");
                    gotoxy(x3, y3);
                    printf("*");
                    gotoxy(x4, y4);
                    printf("*");
                    dir = 'd';
                }
            }
            if (input == 'p') {
                gameover();
                break;
            }
        }
    }
    void stopwatch() {
        clock_t s, n;
        s = clock();
        while (1) {
            n = clock();
            cursor(0);
            gotoxy(14, 0);
            printf(" %d : %d", ((n - s) / 1000) / 60, ((n - s) / 1000) % 60);
            if (over == 1) {
                break;
            }
            Sleep(1000);
        }
        gotoxy(14, 0);
        printf(" ****  ");
        nowrec.minute = ((n - s) / 1000) / 60;
        nowrec.sec = ((n - s) / 1000) % 60;
        return;
    }

CodePudding user response:

Remember that

rand() % x

will give you values in the range [0, x-1].

With this in mind, let's look at

fruitx = rand() % 17;
fruity = rand() % 17;
gotoxy(fruitx, fruity);
printf("@");

When you feed rand() % 17 into gotoxy() like this, you can expect that goto(0, 0) is possible.

I modified the above code to look like this

fruitx = rand() % 17;
fruity = rand() % 17;
gotoxy(0, 0);
printf("@");

to see what would happen, and the fruit turned up outside the field in the top left.

void gotoxy(int x, int y) {
    COORD pos = { 30   x * 2, 10   y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}

The problem is that your definition of gotoxy() is such that feeding it (0, 0) as coordinates puts the cursor outside the boundary to begin with. Furthermore, passing (1, 1) puts it in the corner, making it apart of the wall, which is also illegal I'm guessing.

To fix this, you either need to adjust your mathematics in gotoxy() or make a new function that transforms your field coordinates into global coordinates. This way, (0, 0) would correspond to the actual upper left (just inside the boundary) and so on.

The easiest fix is just to modify it like so

    fruitx = 2   rand() % 15;
    fruity = 2   rand() % 15;
    gotoxy(fruitx, fruity);
    printf("@");

This should happen everywhere you're spawning fruit.

  •  Tags:  
  • c
  • Related