头歌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;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值