我試圖用控制檯獲得快速時間事件類型的交互,並設法使用conio庫獲取它。可悲的是,我正在開發的這個項目需要在Windows和Linux上編譯代碼,我無法找到一種方法來改變它。有沒有辦法在標準C中替換kbhit()和getch()函數?
有什麼我可以做得到理想的效果還是應該放棄這個概念?以下是我創建的函數的代碼。
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
void battle(int x) {
srand(time(0));
printf("Use Q to dodge projectile attacks, E to block melee attacks and W to attack when the boss is stunned. Button mashing will not work! Press any key to start the battle.\n\nYou face Brutus, Lord Incarcerator!\n\n");
getchar();
bool ok;
int dealt = 0 ,recieved = 0 , state, prev = 0;
time_t start, end;
double elapsed;
while(dealt < 5 && recieved < 3)
{
do
{
state = rand() % 3 + 1;
}
while(prev == state);
prev = state;
time(&start);
switch(state)
{
case(1):
ok = 1;
printf("Brutus uses Hook Attack!\n\n");
do
{
time(&end);
elapsed = difftime(end, start);
if(kbhit())
{
if(getchar() == 'q')
{
printf("Dodged!\n\n");
ok = 0;
break;
}
else
{
break;
}
}
}
while(elapsed < 3);
if(ok)
{
printf("You took damage!\n\n");
recieved++;
break;
}
break;
case(2):
ok = 1;
printf("Brutus is stunned!\n\n");
do
{
time(&end);
elapsed = difftime(end, start);
if(kbhit())
{
if(getchar() == 'w')
{
printf("You dealt damage!\n\n");
dealt++;
ok = 0;
break;
}
else
{
break;
}
}
}
while(elapsed < 3);
if(ok)
{
printf("Too slow!\n\n");
break;
}
break;
case(3):
ok = 1;
printf("Brutus uses Blood Slam!\n\n");
do
{
time(&end);
elapsed = difftime(end, start);
if(kbhit())
{
if(getchar() == 'e')
{
printf("Blocked!\n\n");
ok = 0;
break;
}
else
{
break;
}
}
}
while(elapsed < 3);
if(ok)
{
printf("You took damage!\n\n");
recieved++;
break;
}
break;
}
}
if(recieved >= 3)
{
printf("Battle lost; you will now respawn in town.");
getchar();
}
else
{
printf("Battle won!");
getchar();
}
}
int main()
{
battle(2);
}
你的標題,但代碼C]說 「標準C」 ++? – crashmstr
您應該使用_kbhit()。 kbhit自1994年以來已被棄用。在標準C中沒有等價物。請查看http://cboard.cprogramming.com/c-programming/63166-kbhit-linux.html以瞭解相應的Linux。 – cup