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");
}
Допустим, это моя пошаговая игра. Я хочу обновить свою игру через 1 секунду. Как я могу заставить getch () ждать ввода, не останавливая все остальное?
использование 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");
}
Вы можете использовать другой поток, чтобы получить пользовательский ввод.
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;
}
}