神探阿航 2023-07-01 15:17 采纳率: 0%
浏览 21

飞机大战,圆的移动,键盘交互

求解答: 为什么我在VS中运行这段代码,无法实现圆移动方向的改变?(已安装easyx)

#include<easyx.h>
#include<stdio.h>
#include<conio.h>

#define PI 3.14
int main()
{
    initgraph(800, 600);
    setorigin(400, 300);
    setaspectratio(1, -1);
    setbkcolor(RGB(164, 225, 202));
    cleardevice();
    setfillcolor(WHITE);

    int x = -400, y = 0;
    int dx = 5, dy = 0;
    solidcircle(x, y, 50);

    while (1)
    {
        cleardevice();
        solidcircle(x, y, 50);
        Sleep(40);
        if (_kbhit() != 0)
        {
            char c = _getch();
            switch (c)
            {
            case'w':
                dx = 0;
                dy = 5;
                break;
            case 's':
                dx = 0;
                dy = -5;
                break;
            case'a':
                dx = -5;
                dy = 0;
                break;
            case'd':
                dx = 5;
                dy = 0;

            }    
        }
        x += dx;
        y += dy;
    }

    getchar();
    closegraph();
    return 0;

}

  • 写回答

2条回答 默认 最新

  • 盒子猫君 2023-07-01 15:39
    关注

    根据您提供的代码,我注意到在改变圆形移动的方向时,您使用的是_getch()函数来检测键盘输入。然而,在使用easyx库时,_getch()函数可能无法及时读取到键盘输入。相反,您可以尝试使用GetAsyncKeyState()函数来检测键盘输入。

    下面是修改后的代码:

    #include <easyx.h>
    #include <conio.h>
    
    #define PI 3.14
    int main()
    {
    initgraph(800, 600);
    setorigin(400, 300);
    setaspectratio(1, -1);
    setbkcolor(RGB(164, 225, 202));
    cleardevice();
    setfillcolor(WHITE);
    
    int x = -400, y = 0;
    int dx = 5, dy = 0;
    solidcircle(x, y, 50);
    
    while (1)
    {
    cleardevice();
    solidcircle(x, y, 50);
    Sleep(40);
    
    if (GetAsyncKeyState('W') & 0x8000)
    {
    dx = 0;
    dy = 5;
    }
    else if (GetAsyncKeyState('S') & 0x8000)
    {
    dx = 0;
    dy = -5;
    }
    else if (GetAsyncKeyState('A') & 0x8000)
    {
    dx = -5;
    dy = 0;
    }
    else if (GetAsyncKeyState('D') & 0x8000)
    {
    dx = 5;
    dy = 0;
    }
    
    x += dx;
    y += dy;
    }
    
    closegraph();
    return 0;
    }
    
    

    修改后的代码使用GetAsyncKeyState()函数来检测键盘输入。在每次循环中,首先检查W、S、A和D键是否被按下,如果按下则更改dx和dy的值来改变圆形的移动方向。

    请注意,此代码仅解决了无法通过_getch()函数实现圆形移动方向改变的问题。如果还有其他问题,可能需要进一步检查和调试您的代码和配置。

    评论

报告相同问题?

问题事件

  • 创建了问题 7月1日