应该都玩过猜数字的游戏,即由系统生成一个1到100的随机数,用户猜测一个数,用键盘输入,系统会提示偏大还是偏小或猜测正确。
这里稍加改良,主要包括:
1、输入检测:用户输入必须为纯数字,否则要求重新输入。
2、单局猜测次数限制:限制为10次,若未使用二分法,超出次数结束游戏,由用户选择另开一局游戏还是退出。
3、多局成功率统计:选择退出时,对已经玩过的多局游戏进行成功率的统计显示。
程序如下:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
typedef unsigned char u8;
typedef enum {
FLASE=0,
TRUE=1,
}RESULT;
typedef enum{
TRY_AGAIN,
EXIT_GAME,
}STATE;
#define Random(x) (rand()%x)
#define GUESS_TIME_MAX 10
#define GUESS_NUM_MAX 100
int get_int()
{
char numString[100];
u8 N=0,i=0;
int ret=0;
while(1)
{
scanf("%s",numString);
N=strlen(numString);
for(i=0;i<N;i++)
{
if(numString[i]<48||numString[i]>58)//字符"0-9"的ASCII码从48-58
{
printf("not a number , input again\r\n");
ret=-1;
continue;
}
}
if(0==ret)
{
break;
}
else
{
ret=0;
}
}
ret = atoi(numString);//将字符串转换成数字
return ret;
}
RESULT app_guess_num()
{
u8 guess_time=0;
int num_ran=0,num_get=0;
srand((int)time(0));
num_ran=Random(GUESS_NUM_MAX)+1;
printf("\r\n*There is a random num from 1 to 100\r\n*Please input your guess\r\n*You have ten opportunities to use it\r\n\r\n");
while(1)
{
num_get=get_int();
guess_time++;
if(num_get==num_ran)
{
printf("Congratulation! You found the right answer and used it %d times\r\n\r\n",guess_time);
return TRUE;
}
else if(num_get<num_ran)
{
printf(" %d is smaller than answer \r\n",num_get);
}
else
{
printf(" %d is greater than answer \r\n",num_get);
}
if(GUESS_TIME_MAX==guess_time)
{
printf("\r\nGameover ,Ten chances are gone \r\nwhy are you so cute ╮(╯﹏╰)╭ \r\n\r\n");
return FLASE;
}
}
}
STATE app_check_result(RESULT ret)
{
int num_get=0;
printf("\r\n\r\nand now,Enter 1 or 2 to select one of the following two items:\r\n");
printf(" 1-->try again\r\n 2-->exit the game\r\n\r\n");
while(1)
{
num_get=get_int();
if(1==num_get)
{
if(TRUE==ret)
{
printf("good job, again\r\n");
}
else
{
printf("take it ez,just try again\r\n");
}
return TRY_AGAIN;
}
else if(2==num_get)
{
printf("exit game,good luck\r\n");
return EXIT_GAME;
}
else
{
printf("Please enter 1 or 2 to select\r\n");
}
}
}
int main()
{
RESULT ret;
STATE sta;
u8 time_true=0,time_flase=0;
float percent_t=0;
printf("*******************(C) COPYRIGHT 2018 *******************\r\n");
printf("* *\r\n");
printf("* Guess Num Game *\r\n");
printf("* Ver 2.0 *\r\n");
printf("* *\r\n");
printf("*******************(C) COPYRIGHT 2018 *******************\r\n");
while(1)
{
ret=app_guess_num();
if(TRUE==ret)
{
time_true++;
}
else
{
time_flase++;
}
sta=app_check_result(ret);
if(EXIT_GAME==sta)
{
percent_t=time_true*(1.0)/(time_true+time_flase);
printf("guess right time: %d \r\n",time_true);
printf("guess mistake time: %d \r\n",time_flase);
printf("correct: %.0f%%\r\n",percent_t*100);
break;
}
}
return 0;
}