21根火柴游戏【C语言实现】

题目

21根火柴游戏。现有21根火柴,两人轮流取,每人每次可以取1至4根,不可多取(假如多取或者取走的数量不在合法的范围内,则要求重新输入),也不能不取,谁取最后一根火柴谁输。请编写一个程序进行人机对弈,要求人先取,计算机后取;请设计一种计算机取走火柴的规则,使得计算机一方为常胜将军。
**输入格式要求:“%d” 提示信息:“Game begin:\n” “How many sticks do you wish to take (1~%d)?”
**输出格式要求:" %d sticks left in the pile.\n" " You have taken the last sticks.\n"
" ***You lose!\nGame Over.\n" “Computer take %d sticks.\n”
程序运行示例如下:
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.

实现

思路:电脑为后手,其输入只需和人类输入之和凑够5即可,经过4轮之后,最后一个自然落在了人类手上。

#include <stdio.h>
#define N 4
int main(){
    printf("Game begin:\n");
    int left = 21;
    while(left > 0){
        int numA, numB;
        int len = left > N ? N : left;
        printf("How many sticks do you wish to take (1~%d)?", len);
        scanf("%d", &numA);
        while(numA < 1 || numA > len){
            printf("How many sticks do you wish to take (1~%d)?", len);
            scanf("%d", &numA);
        }
        left -= numA;
        if(left > 0){
            printf(" %d sticks left in the pile.\n", left);
        }
        if(left > 1){
            switch (numA) {
                case 1:
                    numB = 4;
                    break;
                case 2:
                    numB = 3;
                    break;
                case 3:
                    numB = 2;
                    break;
                case 4:
                    numB = 1;
                    break;
            }
            left -= numB;
            printf("Computer take %d sticks.\n", numB);
            printf(" %d sticks left in the pile.\n", left);
            fflush(stdout);
        } else{   //left == 1
            left--;
            printf("You have taken the last sticks.\n");
            printf(" ***You lose!\nGame Over.\n");
        }
    }
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值