From 3cdc77bc7d1da312a0c7ae9c734f6a33f1c49ecf Mon Sep 17 00:00:00 2001 From: totycro Date: Tue, 5 Apr 2011 18:19:03 +0200 Subject: added key handling --- pacman-c++/mainwidget.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ pacman-c++/mainwidget.h | 14 ++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/pacman-c++/mainwidget.cpp b/pacman-c++/mainwidget.cpp index 9d7fb14..743b57e 100644 --- a/pacman-c++/mainwidget.cpp +++ b/pacman-c++/mainwidget.cpp @@ -6,7 +6,10 @@ #include "constants.h" MainWidget::MainWidget() + : currentKey(0) { + setFocusPolicy(Qt::StrongFocus); + QVBoxLayout *layout = new QVBoxLayout(this); QHBoxLayout *m_scoreLayout = new QHBoxLayout(); @@ -172,3 +175,40 @@ QPoint MainWidget::mapPositionToCoord(unsigned int x, unsigned int y) return QPoint(x * field_size[0], y * field_size[1]); } +transmission::field_t MainWidget::translateKey(int key) +{ + switch(key) { + case Qt::Key_Up: + return transmission::direction_up; + break; + case Qt::Key_Down: + return transmission::direction_down; + break; + case Qt::Key_Left: + return transmission::direction_left; + break; + case Qt::Key_Right: + return transmission::direction_right; + break; + default: + return 0; + } +} + +void MainWidget::keyPressEvent(QKeyEvent* event) +{ + QWidget::keyPressEvent(event); + currentKey = translateKey( event->key() ); +} + +void MainWidget::keyReleaseEvent(QKeyEvent* event) +{ + QWidget::keyReleaseEvent(event); + transmission::field_t releasedKey = translateKey(event->key()); + if (releasedKey == currentKey) { + // current key got released + // if this is false, a key got released which has already + // been replaced by a different key, so this case is disregarded + currentKey = 0; + } +} diff --git a/pacman-c++/mainwidget.h b/pacman-c++/mainwidget.h index dc20d75..f7113a5 100644 --- a/pacman-c++/mainwidget.h +++ b/pacman-c++/mainwidget.h @@ -3,6 +3,7 @@ #include "constants.h" #include +#include class Actor; @@ -14,6 +15,11 @@ class MainWidget public: MainWidget(); +protected: + // handling of current key + virtual void keyPressEvent(QKeyEvent* ); + virtual void keyReleaseEvent(QKeyEvent* ); + private: void loadDummyMap(); @@ -22,10 +28,18 @@ private: // data conversion QPoint mapPositionToCoord(unsigned int x, unsigned int y); + // GUI elements needed in the progress of the game QList m_playerScoreLayouts; QGraphicsScene *m_scene; + // map of actors in order to keep track of those instances QMap m_actors; + + // key currently pressed by user + transmission::field_t currentKey; + + // translate Qt::Key to our key format + transmission::field_t translateKey(int); }; #endif // MAINWIDGET_H -- cgit v1.2.3