今天是物联网开发学习第二天 2/5
今天完善了昨天的打字游戏
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <termios.h>
#include <unistd.h>
void prepare();
void words(int);
char mygetch();
void start(char*);
char mygetch()
{
struct termios oldt, newt;
char ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
//这里是封装好的mygetch代码,可以用于无回显输入,头文件只能用在linux系
//统,还有一个<conio.h>只能用在windows系统,因为用的是老师的linux云服
//务器所以用封装好的片段
int end()
{
char ch;
printf("按下esc退出,按下空格继续\n");
ch = mygetch();
if(ch == 32)
{
return 1;
}
else if(ch == 27)
{
return 0;
}
else
{
end();
}
}
//结束时判断是退出还是再来一遍
void start(char*word)
{
int ts,te;
int i,count = 0;
char a;
for(i = 0; i < 20; i++)
{
a = mygetch();
if(a == word[i])
{
printf("%c",a);
count++;
}
else
{
printf("_");
}
if(i == 0)
{
ts = time(NULL);
}
else if(i == 19)
{
te = time(NULL);
}
}
printf("已完成\n");
printf("用时:%d\n",te - ts);
printf("正确个数:%d\n",count);
}
//游戏开始后的内容
void prepare()
{
char a;
printf("按下任意键开始,按下首字母开始计时,正确原样输出、错误_\n");
a = mygetch();
if (a)
{
system("clear");
}
}
void words(int a)
{
int i,j;
char word[20] = "";
srand(time(NULL));//设置随机数种子
for (i = 0; i < a; ++i)
{
j = rand()%2;//用来随机大小写字母
if(j==1)
word[i] = rand()%26+"a";
else
word[i] = rand()%26+65;
}
puts(word);
start(word);
}
int main(int argc, char const *argv[])
{
int i = 1;
while(i)
{
system("clear");
prepare();
words(20);
i = end();
}
return 0;
}