打字游戏

这篇博客介绍了如何使用C++编写一个简单的游戏,玩家需要根据屏幕上随机生成的字符串输入字符,统计正确率并测量游戏耗时。通过_getch()函数获取用户输入并与预设字符串进行匹配,展示了rand()和srand()在生成随机字符序列中的应用。
摘要由CSDN通过智能技术生成
#if 1
#include <iostream>
#include <conio.h>
#include <time.h>

const int MAX = 51;

using namespace std;

int main(){
	char str[MAX];
	char ch;

	while (1){
		cout << "*** game start ***" << endl;
		cout << "press any key to start game" << endl;
		ch = _getch();
		if (ch == 27)
			break;
		
		//generate str
		srand((unsigned)time(NULL));
		for (int i = 0; i < MAX - 1; i++)
			str[i] = rand() % 26 + 'a';
		str[MAX - 1] = '\0';
		cout << str << endl;

		//game start
		int count = 0;
		time_t t_start, t_end;
		t_start = time(NULL);
		for (int i = 0; i < MAX - 1; i++){
			ch = _getch();
			if (ch == str[i]){
				count++;
				cout << ch;
			}
			else
				cout << '_';

			if (ch == 27)
				break;
		}
		t_end = time(NULL);
		cout << endl << endl << "*** game stop ***" << endl;
		cout << "正确率: " << (count*1.0/50*100) << endl;
		cout << "耗时: " << (t_end - t_start) << endl;
		if (ch == 27)
			break;
	}

	return 0;
}

#endif

 

参考链接:关于rand()和srand()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值