From 971b4523cceaf7b4972301cea203375137790986 Mon Sep 17 00:00:00 2001 From: Steffen Ritter Date: Wed, 10 Jul 2019 10:38:55 +0200 Subject: Handle special keys --- src/mainwindow.cpp | 17 +++++++++++++++++ src/mainwindow.h | 4 +++- src/snake.cpp | 19 ++++++++++++++++--- src/snake.h | 6 +++++- 4 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 5bc38b9..1e08f0f 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -151,6 +151,23 @@ void MainWindow::mouseDoubleClickEvent(QMouseEvent *) } } +void MainWindow::keyPressEvent(QKeyEvent *event) +{ + switch (event->key()) { + case Qt::Key_Escape: + if (m_Snake != nullptr) { + delete m_Snake; + m_Snake = nullptr; + } + break; + case Qt::Key_Pause: + if (m_Snake != nullptr) { + m_Snake->pauseAndResume(); + } + break; + } +} + QSize MainWindow::createLogo(QRect max) { QSize retval(0, 0); diff --git a/src/mainwindow.h b/src/mainwindow.h index ec153b7..8f9245e 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -58,8 +58,10 @@ protected: virtual void mouseDoubleClickEvent(QMouseEvent *); + virtual void keyPressEvent(QKeyEvent *); + public slots: - void showStandby(); + void showStandby(); void updateClock(); private: diff --git a/src/snake.cpp b/src/snake.cpp index 5246a3c..9c7fefa 100644 --- a/src/snake.cpp +++ b/src/snake.cpp @@ -126,10 +126,10 @@ GameCore::GameCore(QWidget *widget) } qDebug() << "Field:" << _width << _height; addFood(); - QTimer *t = new QTimer(widget); - t->start(15); + _t = new QTimer(widget); + _t->start(15); // GAME - QTimer::connect(t, &QTimer::timeout, [this]() { + QTimer::connect(_t, &QTimer::timeout, [this]() { // static int tick = 0; ++tick; @@ -392,6 +392,10 @@ GameCore::GameCore(QWidget *widget) GameCore::~GameCore() { free(_field); + if(_t->isActive()) { + _t->stop(); + } + _widget->update(); } void GameCore::scanDir(Snake *snake, int dx, int dy, const Cell* &what, int &dist) @@ -453,6 +457,15 @@ void GameCore::initField() _widget->update(); } +void GameCore::pauseAndResume() +{ + if(_t->isActive()) { + _t->stop(); + } else { + _t->start(); + } +} + void GameCore::addFood() { for (int i = 0; i < 10; ++i) { diff --git a/src/snake.h b/src/snake.h index dfa58cc..3adc301 100644 --- a/src/snake.h +++ b/src/snake.h @@ -3,6 +3,7 @@ #include #include +#include class QWidget; class QPaintEvent; @@ -16,7 +17,8 @@ struct Paddle; class GameCore { private: - QWidget *_widget; + QWidget *_widget; + QTimer *_t; int _width, _height; QList _snakes; QList _balls; @@ -44,6 +46,8 @@ public: void addSnake(); void initField(); + + void pauseAndResume(); }; #endif -- cgit v1.2.3-55-g7522