2013-11-09 9 views
10

C로 콘솔 응용 프로그램을 만들고 있습니다.이 게임은 문자가 떨어지고 사용자가 키보드의 특정 키를 눌러야하는 게임입니다. 내가 떨어지는 문자를 일시 중지하지 않고 사용자가 누른 키를 감지하는 방법을 모르겠습니다. scanf를 사용할 때 프로그램은 입력을 기다리고 모든 것이 일시 중지됩니다. 조만간 도와주세요!연속 키보드 입력 C

+0

이 .. 어떤 대답을 기대 – sukhvir

+0

http://stackoverflow.com/a/13035523/1119701 – ouah

+0

실제로 재미있다 ncurses없이이 작업을 수행 할 수있는 다른 방법 – sukhvir

답변

6

확인합니다. 그래서 당신은 이런 식으로 뭔가 함께 갈 수 :

while (1){ 
    if (_kbhit()) 
     key_code = _getch(); 
     // do stuff depending on key_code 
    else 
     continue; 

이 또한 사용 getch() 또는 버퍼에서 콘솔에서 직접 문자를 읽고하지 _getch. conio.h functions here에 대한 자세한 내용은 원하는 것을 수행하는 데 매우 유용 할 수 있습니다.

참고 : conio.h은 표준 라이브러리가 아니며 구현은 컴파일러마다 다를 수 있습니다.

+0

getch()를 사용하여 게임을 계속 일시 중지하고 입력을 기다립니다. 나는 숯을 입력 한 후에 Enter 키를 누를 필요가 없습니다. 그건 문제가 아니야! – zaingz

+1

@zaingz 그 이유는'if (kbhit())'를 사용해야 만하기 때문에 뭔가가 눌 렸을 때만 "대기"합니다. 그러나 그것은'key_code = getch(); '에서 이미 눌려 졌기 때문에 눌려진 키를 읽습니다. –

+0

고맙습니다 ...이것은 정말로 나를 도왔다. Visual Studio를 사용하는 사람들을위한 팁 중 하나는 모든 conio 기능의 시작 부분에 밑줄 "_"을 추가해야합니다. 즉, _kbhit() 및 _getch() – zaingz

4

당신은 아마 ncurses

의 ncurses (새 저주)를 터미널 독립적 인 방식으로 텍스트 기반의 사용자 인터페이스를 작성하는 프로그래머를 허용하는 API 을 제공하는 프로그래밍 라이브러리는 찾을 수 있습니다. 터미널 에뮬레이터에서 실행되는 "GUI와 유사한" 응용 프로그램 소프트웨어를 개발하기위한 툴킷입니다.

또한 kbhit() 또는 _kbhit 그것은 키를 맞았 여부에 따라 true 또는 false 반환 <conio.h> 라이브러리에라는 기능이 있습니다 C/C++: Capture characters from standard input without waiting for enter to be pressed

#include <conio.h> 

if (kbhit()!=0) { 
    cout<<getch()<<endl; 
} 
+0

ncurses없이 끝낼 수 있습니까? – sukhvir

+0

잘 모르겠지만 그래픽 구현을 위해서는 SDL –

+0

ncurses를 사용할 수 없습니다. windows.h 라이브러리에 어떤 것이 있습니까? – zaingz

1

나는 이것이 비 차단 키보드 입력이라고 생각합니다.

void simple_keyboard_input() //win32 & conio.h 
    { 
     if (kbhit()) 
      { 
       KB_code = getch(); 
       //cout<<"KB_code = "<<KB_code<<"\n"; 

       switch (KB_code) 
       { 

        case KB_ESCAPE: 

         QuitGame=true; 

        break; 
       }//switch 
      }//if kb 
      }//void 

여기에있는 문자는 여기로 내려갑니다. Windows에서 경우에 대한

The Matrix falling numbers

코드 :

/* The Matrix falling numbers */ 

#include <iostream> 
#include <windows.h> 

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <conio.h> 
using namespace std; 


#define KB_UP 72 
#define KB_DOWN 80 
#define KB_LEFT 75 
#define KB_RIGHT 77 
#define KB_ESCAPE 27 
#define KB_F8 66 


/* Variables*/ 

char screen_buffer[2000]={' '}; 
int y_coord[2000]={0}; 
int x=0, y=0,dy=0; 
int XMAX=77; 
int YMAX=23; 
int KB_code=0; 
bool QuitGame=false; 
int platformX=35, platformY=23; 

/* function prototypes*/ 

void gotoxy(int x, int y); 
void clrscr(void); 
void setcolor(WORD color); 
void simple_keyboard_input(); 
void draw_falling_numbers(); 
void draw_platform(); 

/* main */ 

int main(void) 
{ 
    /* generate random seed */ 
    srand (time(NULL)); 

    /* generate random number*/ 
    for(int i=0;i<XMAX;i++) y_coord[i]= rand() % YMAX; 

    while(!QuitGame) 
    { 
     /* simple keyboard input */ 
     simple_keyboard_input(); 

     /* draw falling numbers */ 
     draw_falling_numbers(); 

    } 

    /* restore text color */ 
    setcolor(7); 
    clrscr(); 
    cout<<" \n"; 

    cout<<" \nPress any key to continue\n"; 
    cin.ignore(); 
    cin.get(); 

    return 0; 
} 

/* functions */ 

void draw_falling_numbers() 
{ 

    for(x=0;x<=XMAX;x++) 
    { 
     /* generate random number */ 
     int MatixNumber=rand() % 2 ; 

     /* update falling number */ 
     y_coord[x]=y_coord[x]+1; 

     if (y_coord[x]>YMAX) y_coord[x]=0; 

     /* draw dark color */ 
     setcolor(2); 
     gotoxy(x ,y_coord[x]-1); cout<<" "<<MatixNumber<<" "; 

     /* draw light color */ 
     setcolor(10); 
     gotoxy(x ,y_coord[x]); cout<<" "<<MatixNumber<<" "; 
    } 
    /* wait some milliseconds */ 
    Sleep(50); 
    //clrscr(); 
} 


void draw_platform() 
{ 
    setcolor(7); 
gotoxy(platformX ,platformY);cout<<"  "; 

gotoxy(platformX ,platformY);cout<<"ÜÜÜÜÜÜ"; 
setcolor(7); 
Sleep(5); 
} 




void simple_keyboard_input() 
{ 
    if (kbhit()) 
     { 
      KB_code = getch(); 
      //cout<<"KB_code = "<<KB_code<<"\n"; 

      switch (KB_code) 
      { 

       case KB_ESCAPE: 

        QuitGame=true; 

       break; 

       case KB_LEFT: 
          //Do something 
        platformX=platformX-4;if(platformX<3) platformX=3; 
       break; 

       case KB_RIGHT: 
          //Do something  
        platformX=platformX+4;if(platformX>74) platformX=74; 
       break; 

       case KB_UP: 
          //Do something      
       break; 

       case KB_DOWN: 
          //Do something      
       break; 

      }   

     } 

} 


void setcolor(WORD color) 
{ 
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color); 
    return; 
} 


void gotoxy(int x, int y) 
{ 
    static HANDLE hStdout = NULL; 
    COORD coord; 

    coord.X = x; 
    coord.Y = y; 

    if(!hStdout) 
    { 
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    } 

    SetConsoleCursorPosition(hStdout,coord); 
} 


void clrscr(void) 
{ 
    static HANDLE hStdout = NULL;  
    static CONSOLE_SCREEN_BUFFER_INFO csbi; 
    const COORD startCoords = {0,0}; 
    DWORD dummy; 

    if(!hStdout)    
    { 
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    GetConsoleScreenBufferInfo(hStdout,&csbi); 
    } 

    FillConsoleOutputCharacter(hStdout, 
          ' ', 
          csbi.dwSize.X * csbi.dwSize.Y, 
          startCoords, 
          &dummy);  
    gotoxy(0,0); 
}