Head song 21 matchsticks game (ever victorious general)

match game

21 sticks game. There are currently 21 matches, and two people take turns to take them. Each person can take 1 to 4 matches at a time. It is not allowed to take more (if you take more or the number taken is not within the legal range, you will be required to re-enter), and you must not take it. , whoever takes the last match loses. Please write a program for human-computer games, requiring the human to take first, and the computer to take later; please design a rule for the computer to take away the match, so that the computer is always victorious.

For example 1, the example of the player's running results is as follows:

Game begin:
How many sticks do you wish to take (1~4)?6↙
How many sticks do you wish to take (1~4)?3↙
18 sticks left in the pile.
Computer take 2 sticks.
16 sticks left in the pile.
How many sticks do you wish to take (1~4)?3↙
13 sticks left in the pile.
Computer take 2 sticks.
11 sticks left in the pile.
How many sticks do you wish to take (1~4)?3↙
8 sticks left in the pile.
Computer take 2 sticks.
6 sticks left in the pile.
How many sticks do you wish to take (1~4)?3↙
3 sticks left in the pile.
Computer take 2 sticks.
1 sticks left in the pile.
How many sticks do you wish to take (1~1)?2↙
How many sticks do you wish to take (1~1)?1↙
You have taken the last sticks.
***You lose!
Game Over.

My code is as follows:

#include<stdio.h>
int main(void)
{
    int a = 21, i;
    printf("Game begin:\n");
    while (a > 0)
    {
        do{
            printf("How many sticks do you wish to take (1~%d)?",a > 4 ? 4 : a);
            scanf("%d", &i);
        }while (i>4 || i<1 || i>a);
        /*************** Begin ***************/
      
      if(a==1)
        {printf("You have taken the last sticks.\n***You lose!\nGame Over.\n");
        break;}
        a=a-i;
        printf("%d sticks left in the pile.\n",a);

        printf("Computer take 2 sticks.\n");

        a=a-2;
         printf("%d sticks left in the pile.\n",a);


    }
    return 0;  
}

Guess you like

Origin blog.csdn.net/wyulian/article/details/128962044