C语言编程——抢火柴游戏开发

//抢火柴游戏,有30根火柴,甲乙两人去拿,一次拿一根或者两根,谁先拿到最后一根谁赢。
考虑游戏公平性,我们可以找到策略:要抢到30,先抢到27,要抢到27,先抢到24,要抢到24,先抢到21,,,,,类推可知拿到3的倍数谁就赢,针对本题,先拿者不利;
//1代表人拿,0代表机器拿,将游戏规则映射为机器语言,代码如下;

//抢火柴游戏,有30根火柴,甲乙两人去拿,一次拿一根或者两根,谁先拿到最后一根谁赢
//1代表人拿,0代表机器拿
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{  // srand((unsigned)time(NULL));//rand()随机函数种子定义
    int youfirst,getnum,totalnum=30,computergetnum;
    do
    {
        printf("\n who begins get? you(1),computer(0)");
        scanf_s("%d",&youfirst);
    }
    while(1!=youfirst&&0!=youfirst);//决定谁先开始语句,(1)代表人先拿,(0)代表机器先拿

    while(1)//死循环,由break语句跳出
    {
        if(youfirst==1)//人先拿
        {
            do
            {
                printf("\n the remain is %d please input how many sticks do you get",totalnum);//打印还剩几根,输入你要拿几根
                scanf_s("%d",&getnum);
            }
            while(getnum<0||getnum>2||getnum>totalnum);
            totalnum-=getnum;//拿完总数发生变化

            if(totalnum==0){printf("you win\n");break;}

            if(totalnum%3==0){computergetnum=rand()%2+1;}
            else{computergetnum=totalnum%3;}
            totalnum-=computergetnum;
            printf("\n computer get %d ",computergetnum);
            if(totalnum==0){printf("computer win");break;}
        }
        else//计算机先拿
        {
            if(totalnum%3==0){computergetnum=rand()%2+1;}
            else{computergetnum=totalnum%3;}
            totalnum-=computergetnum;
            printf("\ncomputer get %d ",computergetnum);
            if(totalnum==0){printf("computer win");break;}

            do
            {
                printf("\nthe remain is %d please input how many sticks do you get",totalnum);
                scanf_s("%d",&getnum);
            }
            while(getnum<0||getnum>2||getnum>totalnum);
            totalnum-=getnum;
            if(totalnum==0){printf("you win");break;}

        }

    }
    return 0;
}

结果如下;
这里写图片描述

猜你喜欢

转载自blog.csdn.net/KXL_888/article/details/82290483
今日推荐