Skip to content

Commit

Permalink
#110: update snake controller
Browse files Browse the repository at this point in the history
  • Loading branch information
lilyshiomitsu committed Oct 23, 2024
1 parent 86366fa commit bb13843
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
4 changes: 3 additions & 1 deletion NERODevelopment/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ set(PROJECT_SOURCES

find_package(Qt6 REQUIRED COMPONENTS Core Gui Qml Quick Network Mqtt Protobuf Widgets)

qt_add_executable(NEROApp ${PROJECT_SOURCES})
qt_add_executable(NEROApp ${PROJECT_SOURCES}
src/controllers/snakecontroller.h
src/controllers/snakecontroller.cpp)

qt_add_resources(NEROApp "configuration"
PREFIX "/"
Expand Down
46 changes: 46 additions & 0 deletions NERODevelopment/src/controllers/snakecontroller.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include "snakecontroller.h"

SnakeController::SnakeController(Model *model, QObject *parent)
: ButtonController{model, 6, parent} {
// this->m_debounceOffset = 150;
}

void SnakeController::handleKeyPress(int key) {
int newDirection = m_currentDirection;

switch (key) {
case Qt::Key_Up:
newDirection = 0;
break;

case Qt::Key_Right:
newDirection = 1;
break;

case Qt::Key_Down:
newDirection = 2;
break;

case Qt::Key_Left:
newDirection = 3;
break;

default:
return;
}

if (!isOppositeDirection(newDirection)) {
m_currentDirection = newDirection;
emit directionChanged(m_currentDirection);
}
}

bool SnakeController::isOppositeDirection(int newDirection) {
return (m_currentDirection + 2) % 4 == newDirection;
}

void SnakeController::saveScore(int score) {
QString topic = "NERO/SNAKE/SCORE";
QString message = QString::number(score);
m_model->sendMessage(topic, message);
}
25 changes: 25 additions & 0 deletions NERODevelopment/src/controllers/snakecontroller.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#ifndef SNAKECONTROLLER_H
#define SNAKECONTROLLER_H

#include "buttoncontroller.h"
#include <QObject>

class SnakeController : public ButtonController {
Q_OBJECT

public:
explicit SnakeController(Model *model, QObject *parent = nullptr);

public slots:
void handleKeyPress(int key);
void saveScore(int);

signals:
void directionChanged(int newDirection);

private:
int m_currentDirection;
bool isOppositeDirection(int newDirection);
};

#endif // SNAKECONTROLLER_H

0 comments on commit bb13843

Please sign in to comment.