Guess the number game --- C language

Table of contents

Foreword: 

Guess the number game:

1. Print Options

2. Player Input Options

3. Select based on the value entered by the player

4. Realization of repeated games

5. Realization of game function

6. Optimization


❤ Blogger CSDN: Ah Su wants to learn

  ▶Column classification: C language

  The learning of C language is to lay a solid foundation for us to learn other languages ​​in the future, and C produces everything!

  Let's start our journey of C language!


Foreword: 

  After learning the loop and branch statements, we can use the knowledge we have learned to complete a small game of guessing numbers and practice our hands.

Guess the number game:

1. Print Options

  Information needs to be printed on the screen to let the player know what the game is, how to play it, and what the player needs to do . Our approach here is to pack a menu function.

#include <stdio.h>

void menu()
{
    printf("这是一个猜数字游戏\n");
    printf("请做出以下选择:> 1.play  0.exit\n");
    printf("请选择:>");
}

int main()
{
    menu();
    return 0;
}

2. Player Input Options

  We need to allow the player to input a number, which is an integer, so we know that we need to create an integer variable to use the scanf input function .

#include <stdio.h>

void menu()
{
    printf("这是一个猜数字游戏\n");
    printf("请做出以下选择:> 1.play  0.exit\n");
    printf("请选择:>");
}

int main()
{
    int input = 0;//C语言创建变量要在代码块最前面定义
    menu();
    scanf("%d", &input);//打印菜单后,输入数字
    return 0;
}

3. Select based on the value entered by the player

  Players may enter 0, 1, or other illegal values. How to deal with this kind of multi-branch and can handle the situation with illegal values? Thinking about it in our minds, at this time we think that the switch can meet our needs very well .

#include <stdio.h>

void menu()
{
    printf("这是一个猜数字游戏\n");
    printf("请做出以下选择:> 1.play  0.exit\n");
    printf("请选择:>");
}

int main()
{
    int input = 0;
    menu();
    scanf("%d", &input);
    switch(input)//根据输入值选择入口
    {
    //玩游戏
    case 1:
        game();
        break;
    //退出游戏
    case 0:
        printf("退出游戏\n");
        break;
    //重新输入
    default:
        printf("输入错误,请重新输入\n");
        break;//最后加上break是个好习惯
    }
    return 0;
}

 The case of case 1 is to play games, we use the game() function to realize the process of playing games .

4. Realization of repeated games

  By the way, when everyone is playing games, such as playing minesweeper and the game of backgammon. If you are not satisfied with the game, you can play another game, if you are not satisfied, you can play another game, keep playing until you don't want to play, then quit. How to implement this logic? First of all, if you don't get enough of it, play another round until it's enough, what does it sound like, a loop, right? Second, is it equivalent to jumping out of this cycle if you quit the game after enjoying yourself, that is to say, to make the judgment condition false . Considering these two points, there is the following ingenious approach:

#include <stdio.h>

void menu()
{
    printf("这是一个猜数字游戏\n");
    printf("请做出以下选择:> 1.play  0.exit\n");
    printf("请选择:>");
}

int main()
{
    int input = 0;
    //使用do while循环
    do
    {
        menu();
        scanf("%d", &input);
        switch(input)
        {
        case 1:
            game();
            break;
        case 0:
            printf("退出游戏\n");
            break;
        default:
            printf("输入错误,请重新输入\n");
            break;
        }
    }while(input)//使用input控制循环
    return 0;
}

  The characteristic of the do while loop is to execute it once first. First print the menu, enter the corresponding branch according to the value entered by the player, and finally judge whether to recycle . The effect of using input as a do while judgment condition is that when we input 1 or an illegal value, the judgment condition is still true, and the menu is printed again for you to choose. And when we input 0 to choose to exit the game, the judgment expression happens to be false, so exit . This logic can be obtained. 

5. Realization of game function

  The next step is to implement the game function, to do a guessing game. If there is a number for us to guess, this number must have random characteristics to be fun ; when guessing, you need to interact with the corresponding player, for example, if the guessed number is larger than the random number, there must be a hint, and the same is true for guessing small numbers, keep guessing, Don't stop until you guess right . If you guess correctly, the game is over, and you can choose to play again or quit the game .

void game()
{
    //1.生成随机数
    int rom = rand();
    //2.一直猜数字,直到猜对,游戏结束
    int guess = 0;
    while(1)
    {
        printf("请猜数字:>");
        scanf("%d", &guess);
        if(guess > rom)
        {
             printf("猜大了\n");
        }
        else if(guess < rom)
        {
             printf("猜小了\n");
        }
        else
        {
             printf("恭喜,猜对了,随机数是%d\n", rom);
             break;//猜对了,跳出循环以结束游戏
        }
    }
    return 0;
}

  Generating random numbers is to use the rand() function and store them in a variable ; create another variable to store the value we input to compare with the random value ;

6. Optimization

  At this time, you think that this small game should be finished. In fact, there are still some problems in it, and we need to optimize it. rand() generates random numbers, if you do not use the srand() function, it will not work; the range of random numbers generated by rand() is too large, from 0-32767, it is fun to narrow the range, otherwise you will feel your scalp numb.

  • srand is a generator of a random number starting point . When a random number needs to be used, the srand function is called once.
int main()
{
    int input = 0;
    //srand()的参数要一个时刻会变的数
    //时间是一直在变的,我们使用time函数获取系统时间
    //time的参数要一个指针。我们传过去一个空指针NULL
    //time返回值是time_t,是long(长整型)的一个重命名。
    //我们强制转换成无符号int类型,因为srand要的是无符号整型当参数
    srand((unsigned int)time(NULL));
    //使用do while循环
    do
    {
        menu();
        scanf("%d", &input);
        switch(input)
        {
        case 1:
            game();
            break;
        case 0:
            printf("退出游戏\n");
            break;
        default:
            printf("输入错误,请重新输入\n");
            break;
        }
    }while(input)//使用input控制循环
    return 0;
}
  • rand()%100+1;  The random number generated by rand() is modulo 100, and the result is between 0-99 (remainder), plus 1, the value range is between 1-100, The playability is high. 
void game()
{
    int rom = rand()%100+1;
    int guess = 0;
    while(1)
    {
        printf("请猜数字:>");
        scanf("%d", &guess);
        if(guess > rom)
        {
             printf("猜大了\n");
        }
        else if(guess < rom)
        {
             printf("猜小了\n");
        }
        else
        {
             printf("恭喜,猜对了,随机数是%d\n", rom);
             break;//猜对了结束游戏
        }
    }
    return 0;
}

  Supplement: The header file of the rand() and srand() functions is <stdlib.h>, and the header file of the time() function is the <time.h> function. 

  Once these optimized points are changed, you can play~

  Summary: I believe that readers can feel from this article that we are writing what we need according to our needs. There is a term that specifically describes this kind of thinking, TDD (test driven development) test-driven development, according to the need, type out the code for testing, this process is driving us to develop .

  The knowledge that readers hope to gain from this blog post is: a module that repeatedly prints menus to choose to play games , rand() and srand() work with time() to generate random numbers , and consolidate loops and selection statements. The last is to improve the ability to type code .


Conclusion: I hope readers will gain something after reading it! On the way to learn C, wish us more and more C!✔

  Readers who do not understand this article, or find that there are errors in the content of the article, please leave a message in the comment area below to tell the blogger ~, and you can also give some suggestions for article improvement to the blogger, thank you very much! last of the last!

  ❤Please like, please pay attention, your likes are the driving force for my update, let's work hard to make progress together.

Guess you like

Origin blog.csdn.net/muwithxi/article/details/130313584