我正在制作一个你必须破解系统的游戏:键入你在屏幕上看到的数字:1034秒内的12345。我想知道如何在10秒钟后警告玩家,比如在屏幕上打印"太慢!!!!!!"。我尝试了sleep()
函数,但是当sleep()
函数正在运行时它会停止程序!
规则: 当您启动该程序时,屏幕上会显示:
Enter code: Hack 1.
如果输入1并且输入显示随机数,则必须覆盖。如果出现故障:
Hacking failed!!!!!!!!.
如果你的速度太慢,则会出现:
Too slow!!!!!!!
但那件事"太慢!!!!!!"只在程序结束时才会发生!
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
time_t start, end;
double need;
int i;
double number;
int t = 15;
z:
printf("Enter the code: Hack 1 :");
scanf("%d", &i);
if(i == 123456789)
{
printf("Enter the room.");
}
if(i == 1)
{
printf("You've got %d seconds. Press 1 to start hacking the system:", t);
scanf("%d", &i);
if(i == 1)
{
//Appears a random number and time starts counting
time (&start);
srand(time(NULL));
double rn = (rand() % 1000000000000000000);
printf("%f type here: ", rn);
scanf("%lf", &number);
if(number == rn)
{
//Time ends
time (&end);
//Calculate elapsed time
need = difftime (end, start);
//If you're too late
if(need > t)
{
printf("Too late!!!!!!!!!!!");
}
else
{
//If you success
printf("System hacked. Enter the room. ");
t--;
goto z;
}
}
else
{
//If you fail
printf("Hacking failed!!!!!!!!!!");
}
}
}
}
答案 0 :(得分:1)
这是一种方法,但需要conio.h
,这通常在Windows和DOS之外无法使用。它还检查键盘输入,同时查看计时器。
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TIMEOUT 10
int main(void)
{
int code;
int entry;
int key;
time_t mark;
time_t now;
mark = time(NULL);
srand((unsigned)mark);
code = rand();
printf("The code is %d\n", code);
printf("Enter the code\n");
entry = 0;
while (entry < code) {
while (!_kbhit()) {
now = time(NULL);
if (now - mark > TIMEOUT) {
printf("\nTimeout failure!\n");
exit (1);
}
}
key = _getche();
entry = entry * 10 + key - '0';
}
if (entry == code)
printf("\nSuccess\n");
else
printf("\nIncorrect code\n");
return 0;
}
节目输出:
The code is 19911
Enter the code
1984
Timeout failure!
更多节目输出:
The code is 20326
Enter the code
29881
Incorrect code
再次:
The code is 20156
Enter the code
20156
Success
答案 1 :(得分:0)
在类似Unix的操作系统(如Linux)上,您可以使用alarm()
设置计时器,然后从标准输入读取。计时器过去后,将传递SIGALRM
并且read
系统调用被中断。您可以通过查看read
的结果和errno
的值来观察这种情况。以下是如何执行此操作的粗略示例:
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
void handle_alrm(int signo) {}
/* ... */
ssize_t count;
char linebuf[81];
signal(SIGALRM, handle_alrm); /* establish a signal handler */
alarm(10); /* schedule a SIGALRM in 10 seconds */
count = read(STDIN_FILENO, linebuf, 80);
if (count > 0)
remaining_time = alarm(0); /* turn off the alarm */
linebuf[count] = '\0';
printf("You took %d seconds\n", remaining_time);
/* do something here ... */
else if (errno = EINTR) { /* assume the alarm was delivered
puts("You were too slow!");
/* do something here ... */
} else {
/* some other error occured */
/* do something here ... */
}
signal(SIGALRM, SIG_DFL);
如果您使用fgets()
代替read()
,这可能也有效。
另一种不涉及信号的方法是使用select()
函数。它允许您在指定超时的文件描述符上等待数据准备就绪。这可能更适合您的任务,因为它不涉及信号处理。此函数来自BSD套接字API,可能在Windows上不可用。它可能是Winsockets的一部分。