2008年12月2日 星期二

Simulation: The Tortoise and the Hare

1.格子 1 ~ 70
2.起始位置為 1
3.每秒動一回合,先到達或超過 70 者算贏。
4.若是位置在 1 仍往後則為 1
5.烏龜位置用"T"表示;兔子位置用"H"表示;重疊則用"OUCH!!!"表示
6.一開始要印出 "BANG !!!!!"
"AND THEY'RE OFF !!!!!"
7.烏龜贏印出"TORTOISE WINS!!! YAY!!!";兔子贏印出"HARE WINS!!! YAY!!!"
8.若是同時到達終點則算是烏龜贏
9.烏龜跟兔子的步伐如下:






/* Simulation: The Tortoise and the Hare */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* function prototypes */
void moveTortoise( int *turtlePtr );
void moveHare( int *rabbitPtr );
void printCurrentPositions( int *snapperPtr, int *bunnyPtr );

/* tutle and rabbit movements */
int T_move[10]={3,3,3,3,3,-6,-6,1,1,1};
int H_move[10]={0,0,9,9,-12,1,1,1,2,2};

int main()
{
srand((unsigned)time(NULL));

/* set up the initial position */
int T_square=1,H_square=1,i;

for( ; T_square<70&&H_square<70 ; )
{
/* delay 1 second per round */
clock_t start_time;
start_time = clock();
while((clock() - start_time) < 1 * CLOCKS_PER_SEC){}

  /* move and show real-time condition */
moveTortoise(&T_square);
moveHare(&H_square);
printCurrentPositions(&T_square,&H_square);
}

 /* determine who's winner */
(T_square>=70)?printf("TORTOISE WINS!!! YAY!!!\n"):printf("HARE WINS!!! YAY!!!\n");

system("PAUSE");
return 0;
}

void moveTortoise( int *turtlePtr )
{
*turtlePtr+=T_move[rand()%10];
if(*turtlePtr<=0)
*turtlePtr=1;
}

void moveHare( int *rabbitPtr )
{
*rabbitPtr+=H_move[rand()%10];
if(*rabbitPtr<=0)
*rabbitPtr=1;
}

void printCurrentPositions( int *snapperPtr, int *bunnyPtr )
{
/* redraw thw competition */
system("CLS");
printf("BANG !!!!!\n");
printf("AND THEY'RE OFF !!!!!\n");
int i;
printf(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
for(i=1;i<=80;i++)
{
if(i==*snapperPtr&&i==*bunnyPtr)
{
printf("OUCH!!!");
i+=6;
}
else if(i==*snapperPtr)
printf("T");
else if(i==*bunnyPtr)
printf("H");
else
printf(" ");
}
printf(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
}

沒有留言: