I have been doing a school project in which they asked me to create the 2048 game, I created it on the console line as a base, and then I did the graphic design, but when I wanted to implement it I found the problem that checked at the time of starting the application, I started to review, and it turns out that in the cycle in which I ask the user a character "getch ()" is returning me in ascii a "-1", (before installing the filter of events I returned a "-32") so it enters, cycled, and then it does not come out anymore, with what the application ticks me and does not respond.
I would like to know how to capture the arrows on the keyboard, since it is the simplest thing, the other idea that I had was that in a block of text I would capture the letters, but it seems annoying to the end user.
Here is the code of my program:
G2048::G2048(QWidget *parent) :
QMainWindow(parent), ui(new Ui::G2048){
ui->setupUi(this);
EventKeyGame* evento = new EventKeyGame;
ui->pushButton_Start->installEventFilter(evento);
}
void G2048::on_pushButton_Start_clicked(){
int casillaRandom = 0;
char tecla;
int tablero[4][4];
limpiarTablero(tablero);
cargarCasilla(tablero, &casillaRandom);
cargarCasilla(tablero, &casillaRandom);
arriba(tablero);
imprimirTablero(tablero);
do{
tecla = getch();
cout<<(int)tecla<<endl;
switch(tecla){
case 72:
arriba(tablero);
cargarCasilla(tablero, &casillaRandom);
imprimirTablero(tablero);
break;
case 75:
izquierda(tablero);
cargarCasilla(tablero, &casillaRandom);
imprimirTablero(tablero);
break;
case 77:
derecha(tablero);
cargarCasilla(tablero, &casillaRandom);
imprimirTablero(tablero);
break;
case 80:
abajo(tablero);
cargarCasilla(tablero, &casillaRandom);
imprimirTablero(tablero);
break;
default:
break;
}
}while(true);
}
And the event filter that is installed on the button is this:
bool EventKeyGame::eventFilter(QObject *obj, QEvent *event){
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down || keyEvent->key() == Qt::Key_Left || keyEvent->key() == Qt::Key_Right){
qDebug("Valid Key");
}
return true;
} else {
return QObject::eventFilter(obj, event);
}
}
What about the event filter I saw in these links:
Captures keystrokes with QT and C ++
Try also to capture with Open GL, but I can not know if my teacher will have the header.
Another idea I had was to make use of graphic buttons, but it is still a bit annoying to move the mouse, besides that passing the variable board to each button would be long to program.