천간 avatar

[C++ 언어-기초실습-18] gotoxy()함수로 커서 이동하기?

codingman

Published: 12 Jul 2019 › Updated: 12 Jul 2019[C++ 언어-기초실습-18] gotoxy()함수로 커서 이동하기?

[C++ 언어-기초실습-18] gotoxy()함수로 커서 이동하기?

[C++ 언어-기초실습-18] gotoxy()함수로 커서 이동하기?



C언어에서 실습했던 내용인데 간단히 복습차원으로 화살표 커서를 움직이는 실습을 해보도록 하겠습니다.

1. 화살표 커서 값 얻기


while(1){
  if(kbhit()){
    key_val=getch();
    cout<<key_val<<endl;
  }
}

위와 같이 코딩을 하면 콘솔창에서 키를 누르게 되면 해당 키가 어떤 값인지 읽어오게 됩니다.

왼쪽 : 224 75
오른쪽 : 224 77
위쪽 : 224 72
아래쪽 : 224 80

위와 같은 키 값을 읽어오게 되는데 아래와 같이 상수로 정의를 내릴 수 있습니다.

#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77

이 값을 gotoxy()함수로 해서 커서를 이동시키면 됩니다.

2. gotoxy() 함수


void gotoxy(int x, int y){
    COORD posXY={x,y};  
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),posXY);
}

이동한 좌표 x,y를 이 함수를 통해 콘솔창에서 해당 x,y 위치로 이동시키게 됩니다. 이동된 위치에서부터 커서가 멈춰 있습니다.

3. 실습


[전체소스]

#include 
#include 
#include 

#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77

using namespace std;
void gotoxy(int x, int y){
    COORD posXY={x,y};  
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),posXY);
}
int main(int argc, char** argv) {
    
    int x=5;
    int y=5;
    int key_val;
    
    gotoxy(5,5);        
    
    while(1){
     if(kbhit()){
         key_val=getch();
         switch(key_val){           
             case UP: y--; break;
             case DOWN: y++; break;
             case LEFT: x--; break;
             case RIGHT: x++; break;
         }      
         gotoxy(x,y);
        
    }   
    }
    
    return 0;
}

[결과]
a1.jpg

마무리


결과 이미지는 커서가 정지된 한컷의 이미지라서 잘 확인이 안되실 수 있지만 위 소스를 컴파일해서 실행 시키면 콘솔창이 뜨고 키보드의 커서키를 누르면 커서가 이동되는 것을 보실 수 있을 거에요. 이 이동 동작 원리가 게임 코딩을 하기 위한 첫 단추입니다. 복습차원으로 다시 만들어 봤어요


Sponsored ( Powered by dclick )

dclick-imagead

Leave [C++ 언어-기초실습-18] gotoxy()함수로 커서 이동하기? to:

Written by

나는 소망한다 내게 주어진 모든것들을

Read more #kr-dev posts


Best Posts From 천간

We have not curated any of codingman's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From 천간