输出像游戏描述窗口?



我想做的是在有某个句子时输出文本,并给它一个特定的时间间隔,以便它像打字一样输出。这是通过在打印字符串时使用Sleep()函数处理的。但是,当在打印句子时按下空格键(或任何键)时,我希望立即输出剩余的句子,没有时间延迟。因为有些人想要快速阅读文本。(我正在制作一款基于文本的游戏。)从下一个句子开始,字符串应该以一段时间间隔返回到原始字符串。因此,我编写的代码如下所示,但是如果我按一次空格键,它后面的所有句子都将立即打印出来,没有时间间隔。我的猜测是,一旦空格键被按下,它就会像空格键被连续按下一样工作。我怎么解决这个问题?

#include <stdio.h>
#include <Windows.h>
#include <conio.h>
#include <iostream>
using namespace std;
bool space;
void type(string str)
{
for (int i = 0; str[i] != ''; i++) {//Print until  appears
printf("%c", str[i]);
if (GetAsyncKeyState(VK_SPACE) & 0x8000) {//When the user presses the spacebar
space = true;//Turn AABSD into true
}
if (space) {//If the space bar is pressed
Sleep(0);//Print all the letters of a sentence without a break
}
else {//If the space bar is not pressed
Sleep(500);//Print at 0.5 second intervals per character
}
}
space = false;
}
int main(void)
{
space = false;
type("Hello, World!n");
type("Hello, World!n");
type("Hello, World!n");
type("Hello, World!n");
type("Hello, World!n");
type("Hello, World!n");
return 0;
}

type的末尾,您可以循环直到看到空间被释放:

void type(string str) {
...
while (space) {
space = (GetAsyncKeyState(VK_SPACE) & 0x8000);
Sleep(10);
}
}

每次休眠10毫秒可防止按空格键导致计算机过热。

最新更新