C趣味程序百例(29)搶30

字號:

89.搶 30
     這是中國民間的一個游戲。兩人從1開始輪流報數(shù),每人每次可報一個數(shù)或兩個連續(xù)的數(shù),誰先報到30,誰就為勝方。
    *問題分析與算法設(shè)計
     本題與上題類似,算法也類似,所不同的是,本誰先走第一步是可選的。若計算機走第一步,那么計算機一定是贏家。若人先走一步,那么計算機只好等待人犯錯誤,如果人先走第一步且不犯錯誤,那么人就會取勝;否則計算機會抓住人的一次錯誤使自己成為勝利者。
    *程序與程序注釋
    #include
    #include
    #include
    int input(int t);
    int copu(int s);
    void main()
    {
     int tol=0;
     printf("\n* * * * * * * *catch thirty* * * * * * * \n");
     printf("Game Begin\n");
     randomize(); /*初始化隨機數(shù)發(fā)生器*/
     if(random(2)==1) /*取隨機數(shù)決定機器和人誰先走第一步*/
     tol=input(tol); /*若為1,則余元走第一步*/
     while(tol!=30) /*游戲結(jié)束條件*/
     if((tol=copu(tol))==30) /*計算機取一個數(shù),若為30則機器勝利*/
     printf("I lose! \n");
     else
     if((tol=input(tol))==30) /*人取一個數(shù),若為30則人勝利*/
     printf("I lose! \n");
     printf(" * * * * * * * *Game Over * * * * * * * *\n");
    }
    int input(int t)
    {
     int a;
     do{
     printf("Please count:");
     scanf("%d",&a);
     if(a>2||a<1||t+a>30)
     printf("Error input,again!");
     else
     printf("You count:%d\n",t+a);
     }while(a>2||a<1||t+a>30);
     return t+a; /*返回當前的已經(jīng)取走的數(shù)累加和*/
    }
    int copu(int s)
    {
     int c;
     printf("Computer count:");
     if((s+1)%3==0) /*若剩余的數(shù)的模為1,則取1*/
     printf(" %d\n",++s);
     else if((s+2)%3==0)
     {
     s+=2; /*若剩余的數(shù)的模為2,則取2*/
     printf(" %d\n",s);
     }
     else
     {
     c=random(2)+1; /*否則隨機取1或2*/
     s+=c;
     printf(" %d\n",s);
     }
     return s;
    }