簡體   English   中英

在C中使用kbhit來控制機器人的BGI繪圖

[英]Using kbhit in C to control a BGI drawing of a robot

我一直在嘗試if和do while語句的各種組合,但無法使其正常工作。 我們使用Visual Studio 2015並使用C代碼。 該代碼的一般目的是使用BGI圖形來模擬2D機器人(一個圓圈和一條線來指示方向)並使其執行各種任務。 我被告知要;

修改程序,以便用鍵盤控制機器人。

為此,您應該將初始速度初始化為0並向程序添加適當的語句,以便根據按下的鍵來修改速度。 例如,你可以

  • 按下UP鍵時,增加固定常數的v
  • 按下DOWN鍵時,減去固定常數的v
  • 按下RIGHT鍵時,按固定常量減小w
  • 按下LEFT鍵時,增加一個固定常量的w
  • 使用另一把鑰匙來停止機器人
#include <graphics.h> // includes BGI functions
#include <conio.h>
#include <math.h>
#include <stdio.h>

int main()
{
// this is a line of comment
// initialise a 500 X 300 pixels viewport (2D graphic window)
// don't modify the following lines of code
int gd, gm;
gd = CUSTOM;
gm = CUSTOM_MODE(500, 300);
initgraph(&gd, &gm, "");
int kbhit(), c = 0;
float c1, c2, c3, c4, alpha, theta;
int x, y, radius = 40, A, B;
int xvTL = 0, yvTL = 0, xvBR = 500, yvBR = 300;
int xTL = 0, yTL = 0, xBR = 50, yBR = 50;
int xv, yv, W, H; 
float v, w, dt, beta, sigma;
printf("Pixels of graph window (Bottom Right) = 500, 300. World coordinates (Bottom Right) set to 50, 50 \n");                 
printf("Enter a number for x: \n");
scanf("%d", &x);
printf("Enter a number for y: \n");
scanf("%d", &y);
W = xBR - xTL;
H = yTL - yBR;
xv = (x - xTL) * (500 / W);
yv = (yTL - y) * (300 / H);
printf("Coordinates(in viewport) = %d, %d \n", xv, yv);
printf("Enter an angle (in degrees) : \n");
scanf("%f", &alpha);
theta = (float)alpha * 3.1416 / 180;
printf("Angle (in radians) = %f \n", theta);
A = cos(theta) * radius;
B = sin(theta) * radius;
if ((alpha = 90), (0 < alpha < 90), (90 < alpha < 180), (180 < alpha < 270), (alpha = 270), (270 < alpha < 360))
    (B = sin(theta) * -radius);
else
    (B = sin(theta) * radius);
circle(xv, yv, radius);
line(xv, yv, xv + A, yv + B);
v = 0;
w = 0;
do {
    clearviewport();
    dt = 2;
    xv = xv + v * dt * cos(theta);
    yv = yv + v * dt * sin(theta);
    sigma = theta + dt * w; 
    beta = sigma * 180 / 3.1416;
    A = cos(sigma) * radius;
    B = sin(sigma) * radius;
    if ((beta = 90), (0 < beta < 90), (90 < beta < 180), (180 < beta < 270), (beta = 270), (270 < beta < 360))
        (B = sin(sigma) * -radius);
    else
        (B = sin(sigma) * radius);
    circle(xv, yv, radius);
    line(xv, yv, xv + A, yv + B); 
    delay(200);
    if (_kbhit()) {
        (c = _getch());
    }
    if (_kbhit()) {
        c1 = ++v;
        v = c1;
    }
    if (_kbhit()) {
        c2 = --v;
        v = c2;
    }
    if (_kbhit()) {
        c3 = ++w;
        w = c3;
    }
    if (_kbhit()) {
        c4 = --w;
        w = c4;
    }
} while (c != KEY_ESCAPE); (c1 = KEY_UP); (c2 = KEY_DOWN); (c3 = KEY_LEFT);  (c4 = KEY_RIGHT);

return 0;
}

你想要一個kbhit()的調用。 假設傳統功能,它會告訴您在通話時是否按下了鍵。 所以你想在循環中只調用一次。

if(kbhit())
{
   ./* action to alter robot */
}
else
{
   /* no user moves, maybe robot still has momentum */
}

嘗試將一些邏輯移出main()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM