2015-02-05 66 views
0

我想學習如何使用graphics.h和conio.h庫。我正在開發一個圖形程序,我需要在鍵盤input.ex後移動一個矩形:如果玩家按右鍵,矩形應該右移。問題是我不知道如何獲得用戶輸入。我需要獲得用戶輸入內循環連續。這裏是我的code.Any幫助表示讚賞(關鍵字,函數名稱等)在c中使用conio.h獲取鍵盤輸入

#include <stdio.h> 
#include <conio.h> 
#include <graphics.h> 
#include <math.h> 

void drawrect(int left,int top,int right,int bot); 

int main() 
{ 
    int gd = DETECT, gm; 
    initgraph(&gd, &gm, "C:\\TC\\BGI"); 
    drawrect(5,400,40,450); // default start position 
    firsttime=1;//counter for if its first time in for loop 
    int currentl=5; 
    int currentt=400; 
    int currentr=40; 
    int currentb=450; 
     if(firsttime==1) 
     { 
       //get user input and drawrectangle with new inputs 
       //if player press right add 5 to currentl and current r and 
       //redraw the rectangle 
     } 


    getch(); 
    closegraph(); 
} 

void drawrect(int left,int top,int right,int bot) 
{ 
rectangle(left,top,right,bot); 
} 
+0

循環在哪裏? – Ashish 2015-02-05 18:06:41

+0

if if子句做一個無限的while循環(類似於true)給一些調用,如果循環.. Else循環獲取輸入..調用函數..(記住清除屏幕或可能重畫)給一些退出循環關鍵字或關鍵字 – Ashish 2015-02-05 18:10:26

+0

如果(第一次== 1),我會把一個無限循環,但哪些funchtions應該用來從鍵盤獲得輸入,我如何檢測它們 – user3524633 2015-02-05 20:07:50

回答

0

您可以使用getch()_getch()來讀取密鑰代碼並對其作出反應。但有些事情你應該考慮。

1)在您的程序中需要循環執行連續操作。

2)諸如「向左箭頭」,「向上箭頭」等的鍵由getch()作爲兩個代碼給出 - 第一個-32和第二個依賴於鍵。

使用以下PROGRAMM看到循環示例,並找到代碼鍵:

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

int main(void) 
{ 
    char ch; 
    printf("Press 'q' to exit prom program\n"); 
    do{ 
     ch = _getch(); 
     printf("%c (%d)\n", ch, ch); 
    } while(ch != 'q'); 
} 
0

它解決了這個代碼工作感謝您的幫助

的#include 的#include

void drawrect(int left,int top,int right,int bot); 

int main() 
{ 
    int gd = DETECT, gm; 
    initgraph(&gd, &gm, "C:\\TC\\BGI"); 

    int firsttime=1;//counter for if its first time in for loop 
    int currentl=5; 
    int currentt=400; 
    int currentr=40; 
    int currentb=450; 

    char ch; 
    settextstyle(0, HORIZ_DIR, 1); 
    outtextxy(20, 20, "To start press 'S'"); 
    ch = getch(); 
    cleardevice(); 
    drawrect(5,400,40,450); // default start position 

     while(ch!='q') 
     { 
     ch = getch(); 
     switch (ch) 
     { 
     case KEY_RIGHT:currentr=currentr+5; 
         currentl=currentl+5; 
         break; 
     case KEY_LEFT:currentr=currentr-5; 
         currentl=currentl-5; 
         break; 
     } 
     cleardevice(); 
     drawrect(currentl,currentt,currentr,currentb); 
     } 




    getch(); 
    closegraph(); 
} 

void drawrect(int left,int top,int right,int bot) 
{ 
rectangle(left,top,right,bot); 
}