#include <stdio.h>

int next(void);
int getrange(void);
int getnumber(int limit);

int main() {
    int m, unknown, guess;

    if ((m = getrange()) < 0) return 1; /* 给范围时出错次数太多 */
    ++m; /* m作为取模的数，应该比最大的数大一 */
    do {
        unknown = rand()%m;

        while (1) {
            if ((guess = getnumber(m)) < 0) {
                printf("Too many errors. Stop!");
                return 2; /* 猜数时出错次数太多 */
            }
            if (guess > unknown) printf("Too big!\n");
            else if (guess < unknown) printf("Too small!\n");
            else {
                printf("Congratulation! You win!");
                break;
            }
        }
    } while (next());

    printf("Game over.\n");
    return 0;
}

enum { ERRORNUM = 5 };

int getrange(void) {
    int i, n;

    for (i = 0; i < ERRORNUM; ++i) {
        printf("Choose a range [0, n]. Input n: ");
        if (scanf("%d", &n) != 1 || n < 2 || n > 32767) {
            printf("Wrong number. Need a number in 2~32767.\n");
            while (getchar() != '\n')
                ;
        }
        else return n;
    }

    return -1;
}

int getnumber(int m) {
    int i, n;

    for (i = 0; i < ERRORNUM; ++i) {
        printf("Your guess: ");
        if (scanf("%d", &n) != 1 || n < 0 || n >= m) {
            printf("Wrong number. Need a number in 0~%d.\n", m-1);
            while (getchar() != '\n')
                ;
        }
        else return n;
    }

    return -1;
}

int next(void) {
    int c;

    printf("Next game? (y/n): ");
    while (isspace(c = getchar()))
        ;

    if (c == 'y') return 1;
    else return 0;
}


