C语言实现简单打字游戏

我们实现这样一道编程题,简单的打字游戏,在程序启动后,随机生成一段英文字母,然后用户输入英文字母,输入完毕后,显示用户打字时间和正确率。

代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include 
#include 
extern void before_game();
extern void start_game(char*,int);
extern void creat_word(int);
/*
游戏开始前提示
*/
void before_game()
{
	printf("****************************************\n");
	printf("*输入过程中无法退出,输入出错则按*表示!*\n");
	printf("*按任意键开始测试,按下首字母开始计时! *\n");
	printf("****************************************\n");
	creat_word(30);
}
/*
生成随机英文字母字符串
*/
void creat_word(int n)
{
	int num = n + 1;//多一个\0结束字符
	char* words = (char*)malloc(num);
	memset(words, 0, num);
	srand((unsigned int)time(NULL));//设置随机数种子
	for (size_t i = 0; i < n; i++)
	{
		char c = 'a' + rand() % 26;//生成随机字母
		words[i] = c;
	}
	char str = _getch();
	if(str)
	{ 
		system("cls");
	}
	puts(words);
	start_game(words,n);
	free(words);
}
/*
开始游戏
字符按下不能回退,打错用*替换
*/
void start_game(char* ch,int n)
{
	time_t start_time = 0;
	time_t end_time = 0;
	while (1)
	{
		char str;
		int count = 0;
		for (size_t i = 0; i < n; i++)
		{
			str = _getch();

			if (str == ch[i])
			{
				count++;
				printf("%c", str);
			}
			else
			{
				printf("*");
			}
			if (i == 0)
				start_time = time(NULL);
			if (i == n-1)
				end_time = time(NULL);

		}
		printf("\n");
		printf("打字时间:%d秒\n", end_time - start_time);
		printf("准确率为:%.2f%%\n", count*1.0 / n * 100);
		printf("退出请按Esc,继续请按任意键\n");
		str = _getch();
		if (str == 27)//Esc的ASCII为27 ,退出游戏
		{
			break;
		}
		system("cls");
		before_game();//重新开始游戏
		break;
	}
}

int main(int argc, char *argv[])
{
	before_game();
	return 0;
}
程序比较简单,主要是有以下几个注意点:

1、随机字母采用随机生成字母的ascii 编码 然后在强转回字符类型。

2、输入字符不用按回车。

    如果是Windows平台,WINAPI自带类似功能函数

    char ch = _getch(); //需要头文件#include

3、时间的一个计算

获取当前系统时间:

    time_t start_time = time(NULL); //需要头文件#include

效果截图:

C语言实现简单打字游戏_第1张图片



你可能感兴趣的:(【Language_C】)