我不明白为什么if(kbhit())被执行两次

时间:2019-07-28 12:50:33

标签: c kbhit

我编写了一段简单的代码,根据所按的键在屏幕上移动了一个“ X”角色。但是,if语句执行了两次,我也不知道为什么。有人可以解释,甚至给我解决方案吗?在该程序中这不是问题,但是在我编写的其他代码中却很烦人。

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <time.h>

#include <windows.h>


void gotoxy(int x, int y)
{
    COORD c;

    c.X = x;
    c.Y = y;

    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}

void textcolor(int color)
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}


int main(int argc, char *argv[])
{
    int fin=0, res, x, y;
    const int TX=20, TY=15;  //where the player is allowed to move in the screen

    srand(time(NULL));
    x = rand() % TX;
    y = rand() % TY;

    textcolor(12);
    gotoxy(x, y);
    putchar('X');

    int c=0, d;

    while(!fin)
    {
        if (kbhit())
        {
            c++ //counts the number of time the if is executed

            gotoxy(x, y);
            putchar(' ');  //erasing the caracter

            res = getch();

            switch(res)  //changing its coordinates according to the arrow hit
            {
                case 72: y--; break;
                case 77: x++; break;
                case 80: y++; break;
                case 75: x--; break;
                case 224: break;
                default: fin = 1; break;
            }

            if(x<0)   //so it doesn't get out of the screen
                x = TX;
            if(x>TX)
                x = 0;
            if(y<0)
                y = TY;
            if(y>TY)
                y = 0;

            gotoxy(x, y);  //and then placing it
            putchar('X');


                gotoxy(2, 25);  //It shows that the code is executed twice
                printf("%d", c);

        }
    }

    return 0;
}

0 个答案:

没有答案