打印本文 打印本文  关闭窗口 关闭窗口  
C趣味程序百例(29)抢30
作者:佚名  文章来源:不详  点击数  更新时间:2008/4/18 13:59:13  文章录入:杜斌  责任编辑:杜斌

89.抢 30
   这是中国民间的一个游戏。两人从1开始轮流报数,每人每次可报一个数或两个连续的数,谁先报到30,谁就为胜方。
*问题分析与算法设计
   本题与上题类似,算法也类似,所不同的是,本谁先走第一步是可选的。若计算机走第一步,那么计算机一定是赢家。若人先走一步,那么计算机只好等待人犯错误,如果人先走第一步且不犯错误,那么人就会取胜;否则计算机会抓住人的一次错误使自己成为胜利者。
*程序与程序注释
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int input(int t);
int copu(int s);
void main()
{
   int tol=0;
   printf("\n* * * * * * * *catch thirty* * * * * * * \n");
   printf("Game Begin\n");
   randomize();                /*初始化随机数发生器*/
   if(random(2)==1)      /*取随机数决定机器和人谁先走第一步*/
      tol=input(tol);    /*若为1,则余元走第一步*/
   while(tol!=30)        /*游戏结束条件*/
      if((tol=copu(tol))==30)       /*计算机取一个数,若为30则机器胜利*/
         printf("I lose! \n");
      else
         if((tol=input(tol))==30)     /*人取一个数,若为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;        /*返回当前的已经取走的数累加和*/
}
int copu(int s)
{
   int c;
   printf("Computer count:");
   if((s+1)%3==0)          /*若剩余的数的模为1,则取1*/
      printf(" %d\n",++s);
   else if((s+2)%3==0)
   {
      s+=2;     /*若剩余的数的模为2,则取2*/
      printf(" %d\n",s);
   }
   else
   {
      c=random(2)+1;     /*否则随机取1或2*/
      s+=c;
      printf(" %d\n",s);
   }
   return s;
}
*运行示例



*思考题
   巧夺偶数。桌子上有25颗棋子,游戏双方轮流取子,每人每次最少取走一颗棋子,最多可取走3颗棋子。双方照这样取下去,直到取光所有的棋子。于是双方手中必然一方为偶数,一方为奇数,偶数方为胜者。请编程实现人机游戏。
打印本文 打印本文  关闭窗口 关闭窗口