Fai*_*ght 6 c++ windows input getch conio
for (;;)
{
cout << "You are playing for:" << playtime << "seconds." << endl;
cout << "You have " << bytes << " bytes." << endl;
cout << "You are compiling " << bps << " bytes per second." << endl;
cout << "Press a to buy assembler monkey (produces 1 byte per second)/(cost 10 bytes)" << endl;
switch(getch())
{
case 'a': bytes = bytes - 10; bps++; break;
}
bytes = bytes + bps;
playtime++;
Sleep(1000);
system("cls");
}
Run Code Online (Sandbox Code Playgroud)
假设这是我的增量游戏。我想在 1 秒后刷新我的游戏。如何让 getch() 在不停止所有其他内容的情况下等待输入?
小智 5
使用khbit()函数检测是否按下了某个键:)
就像是:
for (;;)
{
cout << "You are playing for:" << playtime << "seconds." << endl;
cout << "You have " << bytes << " bytes." << endl;
cout << "You are compiling " << bps << " bytes per second." << endl;
cout << "Press a to buy assembler monkey (produces 1 byte per second)/(cost 10 bytes)" << endl;
if(kbhit()){ //is true when a key was pressed
char c = getch(); //capture the key code and insert into c
switch(c)
{
case 'a': bytes = bytes - 10; bps++; break;
}
}
bytes = bytes + bps;
playtime++;
Sleep(1000);
system("cls");
}
Run Code Online (Sandbox Code Playgroud)
您可以使用另一个线程来获取用户输入。
这for (;;)是不必要的,您应该使用while (true).
#include <Windows.h>
#include <iostream>
#include <conio.h>
using namespace std;
DWORD WINAPI SpeedThread(LPVOID lpParam);
int main ()
{
int playtime = 0,
bytes = 0,
bps = 1;
bool bKeyPressed = false;
CreateThread( NULL, 0, SpeedThread, &bKeyPressed, 0, NULL);
while (true)
{
cout << "You are playing for:" << playtime << "seconds." << endl;
cout << "You have " << bytes << " bytes." << endl;
cout << "You are compiling " << bps << " bytes per second." << endl;
cout << "Press a to buy assembler monkey (produces 1 byte per second)/(cost 10 bytes)" << endl;
if (bKeyPressed && bytes >= 10)
{
bytes -= 10;
bps++;
bKeyPressed = false;
}
bytes = bytes + bps;
playtime++;
Sleep(1000);
system("cls");
}
}
DWORD WINAPI SpeedThread (LPVOID lpParam)
{
bool * bKeyPressed = (bool *) lpParam;
while (true)
{
if (_getch () == 'a')
*bKeyPressed = true;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7351 次 |
| 最近记录: |