[C++ 언어-기초실습-18] gotoxy()함수로 커서 이동하기?
- 다운 사이트 : https://sourceforge.net/projects/orwelldevcpp/
- 웹컴파일러 : https://www.tutorialspoint.com/compile_c_online.php
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 <iostream>
#include <conio.h>
#include <windows.h>
#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;
}
[결과]
마무리
결과 이미지는 커서가 정지된 한컷의 이미지라서 잘 확인이 안되실 수 있지만 위 소스를 컴파일해서 실행 시키면 콘솔창이 뜨고 키보드의 커서키를 누르면 커서가 이동되는 것을 보실 수 있을 거에요. 이 이동 동작 원리가 게임 코딩을 하기 위한 첫 단추입니다. 복습차원으로 다시 만들어 봤어요
신기하네요! 게임 코딩..! 플레이 하기만 하던 게임을 직접 만들다니 굉장하네요!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
감사합니다.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Thank you for your continued support towards JJM. For each 1000 JJM you are holding, you can get an additional 1% of upvote. 10,000JJM would give you a 11% daily voting from the 700K SP virus707 account.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Thank you
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit