头歌21根火柴游戏(常胜将军)

火柴游戏

21 根火柴游戏。现有 21 根火柴,两人轮流取,每人每次可以取 1 至 4 根,不可多取(假如多取或者取走的数量不在合法的范围内,则要求重新输入),也不能不取,谁取最后一根火柴谁输。请编写一个程序进行人机对弈,要求人先取,计算机后取;请设计一种计算机取走火柴的规则,使得计算机一方为常胜将军。

例如1,玩家的运行结果示例如下:

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.

我的代码如下:

#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;  
}

猜你喜欢

转载自blog.csdn.net/wyulian/article/details/128962044