From 07e984319a08bf00326d3865ed464801ffe06d0b Mon Sep 17 00:00:00 2001 From: KloopRE <100780612+KloopRE@users.noreply.github.com> Date: Wed, 6 Dec 2023 13:42:09 +0300 Subject: [PATCH 1/8] =?UTF-8?q?=D0=B2=D0=BE=D0=BF=D1=80=D0=BE=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Почему по нажатию кнопок управления ничего не происходит? возможно, что-то блокирует обработку событий клавиш --- Pacman.pro | 9 ++- mainwindow.cpp | 184 ++++++++++++++++++++++++++++++++++++++++++++++--- mainwindow.h | 35 +++++++--- mainwindow.ui | 56 ++++++++++----- player.cpp | 22 ++++++ player.h | 20 ++++++ puckman.png | Bin 0 -> 279 bytes resource.qrc | 5 ++ 8 files changed, 294 insertions(+), 37 deletions(-) create mode 100644 player.cpp create mode 100644 player.h create mode 100644 puckman.png create mode 100644 resource.qrc diff --git a/Pacman.pro b/Pacman.pro index b915c09..c576355 100644 --- a/Pacman.pro +++ b/Pacman.pro @@ -10,10 +10,12 @@ CONFIG += c++17 SOURCES += \ main.cpp \ - mainwindow.cpp + mainwindow.cpp \ + player.cpp HEADERS += \ - mainwindow.h + mainwindow.h \ + player.h FORMS += \ mainwindow.ui @@ -22,3 +24,6 @@ FORMS += \ qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target + +RESOURCES += \ + resource.qrc diff --git a/mainwindow.cpp b/mainwindow.cpp index 7e184b2..ab13062 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -1,15 +1,183 @@ #include "mainwindow.h" #include "ui_mainwindow.h" -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent) - , ui(new Ui::MainWindow) -{ - ui->setupUi(this); +#include +#include + +MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { + ui->setupUi(this); + setFocusPolicy(Qt::StrongFocus); + + tableWidget_ = ui->tableWidget; + + tableWidget_->setRowCount(rows_); + tableWidget_->setColumnCount(cols_); + + tableWidget_->verticalHeader()->setDefaultSectionSize(32); + tableWidget_->horizontalHeader()->setDefaultSectionSize(32); + + tableWidget_->verticalHeader()->setVisible(false); + tableWidget_->horizontalHeader()->setVisible(false); + + tableWidget_->setVisible(true); + + // Выделите память для gameGrid + gameGrid_ = new int*[rows_]; + for (int i = 0; i < rows_; ++i) { + gameGrid_[i] = new int[cols_]; + } + generateRandomGameGrid(); + setupGameGrid(); } -MainWindow::~MainWindow() -{ - delete ui; +MainWindow::~MainWindow(){ + for (int i = 0; i < rows_; ++i) { + delete[] gameGrid_[i]; + } + delete[] gameGrid_; + + delete ui; } +void MainWindow::generateRandomGameGrid() { + // Сбросим генератор случайных чисел + std::srand(std::time(0)); + + // Количество единиц в gameGrid + int onesCount = std::rand() % ((rows_ * cols_) / 5) + 1; + + // Создадим пустую gameGrid + for (int i = 0; i < rows_; ++i) { + for (int j = 0; j < cols_; ++j) { + gameGrid_[i][j] = 0; + } + } + + // Расставим единицы случайным образом + for (int k = 0; k < onesCount; ++k) { + int randomRow = std::rand() % rows_; + int randomCol = std::rand() % cols_; + + // Проверим, что выбранная ячейка еще не содержит 1 + while (gameGrid_[randomRow][randomCol] == 1) { + randomRow = std::rand() % rows_; + randomCol = std::rand() % cols_; + } + + gameGrid_[randomRow][randomCol] = 1; + } + + // Расставим одну двойку + int randomRow = std::rand() % rows_; + int randomCol = std::rand() % cols_; + + gameGrid_[randomRow][randomCol] = 2; + player_.setX(randomCol); + player_.setY(randomRow); + qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; +} + +void MainWindow::setupGameGrid() { + // Установите размер ячеек + +// Заполните ячейки таблицы значениями из игровой сетки + for (int i = 0; i < rows_; ++i) { + for (int j = 0; j < cols_; ++j) { + QTableWidgetItem* item = new QTableWidgetItem; + item->setTextAlignment(Qt::AlignCenter); + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + tableWidget_->setItem(i, j, item); + + switch (gameGrid_[i][j]) { + case 0: // Empty space + item->setBackground(QColor(Qt::white)); + break; + case 1: // Wall + item->setBackground(QColor(Qt::darkGray)); + break; + case 2: // player + item->setIcon(QIcon(":resource/puckman.png").pixmap(QSize(64, 64))); + break; + } + } + } + + QSize tablesize = tableWidget_->sizeHint(); + this->resize(tablesize); +} + +void MainWindow::keyPressEvent(QKeyEvent *event) { + switch (event->key()) { + case Qt::Key_W: + qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; + movePlayerUp(); + break; + case Qt::Key_S: + qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; + movePlayerDown(); + break; + case Qt::Key_A: + movePlayerLeft(); + break; + case Qt::Key_D: + movePlayerRight(); + break; + default: + QMainWindow::keyPressEvent(event); + break; + } +} + +void MainWindow::movePlayerUp() { + if(gameGrid_[player_.getY()-1][player_.getX()] != 1) + { + if (player_.getY() > 0) { + gameGrid_[player_.getY()][player_.getX()] = 0; + gameGrid_[player_.getY()-1][player_.getX()] = 2; + player_.setY(player_.getY() - 1); + setupGameGrid(); + qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; + } + } +} + +void MainWindow::movePlayerDown() { + int rowCount = tableWidget_->rowCount(); + if(gameGrid_[player_.getY()+1][player_.getX()] != 1) + { + if (player_.getY()+1 < rowCount) { + gameGrid_[player_.getY()][player_.getX()] = 0; + gameGrid_[player_.getY()-1][player_.getX()] = 2; + player_.setY(player_.getY() - 1); + setupGameGrid(); + qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; + } + } +} + +void MainWindow::movePlayerLeft() { + if(gameGrid_[player_.getY()][player_.getX()-1] != 1) + { + if (player_.getX() > 0) { + gameGrid_[player_.getY()][player_.getX()] = 0; + gameGrid_[player_.getY()][player_.getX()-1] = 2; + player_.setX(player_.getX() - 1); + setupGameGrid(); + qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; + } + } +} + +void MainWindow::movePlayerRight() { + int columnCount = tableWidget_->columnCount(); + if(gameGrid_[player_.getY()][player_.getX()+1] != 1) + { + if (player_.getX() < columnCount) { + gameGrid_[player_.getY()][player_.getX()] = 0; + gameGrid_[player_.getY()][player_.getX()+1] = 2; + player_.setX(player_.getX() + 1); + setupGameGrid(); + qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; + } + } +} diff --git a/mainwindow.h b/mainwindow.h index dbe42ab..fe6cbec 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -1,21 +1,40 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H +#include "player.h" + +#include #include QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE -class MainWindow : public QMainWindow -{ - Q_OBJECT +class MainWindow : public QMainWindow { +Q_OBJECT + +public: + MainWindow(QWidget *parent = nullptr); + ~MainWindow(); + + void generateRandomGameGrid(); + void setupGameGrid(); // Объявление функции setupGameGrid - public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); +protected: + void keyPressEvent(QKeyEvent *event) override; + +private: + Ui::MainWindow *ui; + QTableWidget* tableWidget_; + const int rows_ = 5; + const int cols_ = 5; + int **gameGrid_; + Player player_; + void movePlayerUp(); + void movePlayerDown(); + void movePlayerLeft(); + void movePlayerRight(); - private: - Ui::MainWindow *ui; }; + #endif // MAINWINDOW_H diff --git a/mainwindow.ui b/mainwindow.ui index b232854..c1bcffa 100644 --- a/mainwindow.ui +++ b/mainwindow.ui @@ -1,22 +1,40 @@ - MainWindow - - - - 0 - 0 - 800 - 600 - - - - MainWindow - - - - - - - +MainWindow + + + + 0 + 0 + 800 + 600 + + + + MainWindow + + + + + + 5 + 5 + + + + + + + + 0 + 0 + 800 + 21 + + + + + + + diff --git a/player.cpp b/player.cpp new file mode 100644 index 0000000..1e1762b --- /dev/null +++ b/player.cpp @@ -0,0 +1,22 @@ +// player.cpp +#include "player.h" + +// Реализация конструктора по умолчанию +Player::Player() : x_(0), y_(0) {} + +// Геттеры и сеттеры +int Player::getX() const { + return x_; +} + +int Player::getY() const { + return y_; +} + +void Player::setX(int newX) { + x_ = newX; +} + +void Player::setY(int newY) { + y_ = newY; +} diff --git a/player.h b/player.h new file mode 100644 index 0000000..0586fc5 --- /dev/null +++ b/player.h @@ -0,0 +1,20 @@ +// player.h +#ifndef PLAYER_H +#define PLAYER_H + +class Player { +private: + int x_; // Координата x + int y_; // Координата y + +public: + // Конструктор по умолчанию + Player(); + + int getX() const; + int getY() const; + void setX(int newX); + void setY(int newY); +}; + +#endif // PLAYER_H diff --git a/puckman.png b/puckman.png new file mode 100644 index 0000000000000000000000000000000000000000..5398c1cef7979c8333420ddae6f8908855ae27a3 GIT binary patch literal 279 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1SJ1Ryj={W7>k44ofy`glX(f`u%tWsIx;Y9 z?C1WI$O`0h7I;J!GcfQS24TkI`72U@f@?fo978<3-}VOb9ai9RuKxe{8xzl#X-&zK zw=BN8FkY7y z literal 0 HcmV?d00001 diff --git a/resource.qrc b/resource.qrc new file mode 100644 index 0000000..882755d --- /dev/null +++ b/resource.qrc @@ -0,0 +1,5 @@ + + + puckman.png + + From eed13040e7a45b60a0364b8ca8a02cfeac859c5c Mon Sep 17 00:00:00 2001 From: KloopRE <100780612+KloopRE@users.noreply.github.com> Date: Thu, 7 Dec 2023 19:31:08 +0300 Subject: [PATCH 2/8] =?UTF-8?q?=D0=9F=D0=BE=D0=BC=D0=BE=D0=B3=D0=B8=D1=82?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit В чём ошибка? D:\Pacman-task\hostile.cpp:143: ошибка: undefined reference to `Hostile::Hostile(std::vector >, std::allocator > > >&)' D:\Pacman-task\mainwindow.cpp:90: ошибка: undefined reference to `Hostile::Hostile()' --- Pacman.pro | 2 + hostile.cpp | 162 +++++++++++++++++++++++++++++ hostile.h | 37 +++++++ hostile.png | Bin 0 -> 416 bytes mainwindow.cpp | 275 ++++++++++++++++++++++++++++++++++--------------- mainwindow.h | 23 ++++- mainwindow.ui | 4 - resource.qrc | 1 + 8 files changed, 412 insertions(+), 92 deletions(-) create mode 100644 hostile.cpp create mode 100644 hostile.h create mode 100644 hostile.png diff --git a/Pacman.pro b/Pacman.pro index c576355..9f1bce2 100644 --- a/Pacman.pro +++ b/Pacman.pro @@ -9,11 +9,13 @@ CONFIG += c++17 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ + hostile.cpp \ main.cpp \ mainwindow.cpp \ player.cpp HEADERS += \ + hostile.h \ mainwindow.h \ player.h diff --git a/hostile.cpp b/hostile.cpp new file mode 100644 index 0000000..4cf222b --- /dev/null +++ b/hostile.cpp @@ -0,0 +1,162 @@ +#include "hostile.h" + +using namespace std; + +struct Node { + Point point; + int distance; + + Node(Point _point, int _distance) : point(_point), distance(_distance) {} + + // Перегрузка оператора "больше" для приоритетной очереди + bool operator>(const Node& other) const { + return distance > other.distance; + } +}; + +bool Hostile::isValid(int x, int y) { + int rows = matrix_.size(); + int cols = matrix_[0].size(); + return x >= 0 && x < cols && y >= 0 && y < rows && matrix_[y][x] != 1; +} + +vector getMoveDirections(const Point& start, const Point& end) { + int dx = end.x - start.x; + int dy = end.y - start.y; + + vector directions; + + if (dx > 0) { + directions.push_back('R'); // Вправо + } else if (dx < 0) { + directions.push_back('L'); // Влево + } + + if (dy > 0) { + directions.push_back('D'); // Вниз + } else if (dy < 0) { + directions.push_back('U'); // Вверх + } + + return directions; +} + +vector Hostile::getPath(const Point& end) { + int rows = matrix_.size(); + int cols = matrix_[0].size(); + + vector directions; + + vector> distance(rows, vector(cols, INT_MAX)); + vector> path(rows, vector(cols, Point(-1, -1))); + priority_queue, greater> pq; + + pq.push(Node(position_, 0)); + distance[position_.y][position_.x] = 0; + + // Возможные смещения влево, вправо, вверх и вниз + int dx[] = {-1, 1, 0, 0}; + int dy[] = {0, 0, -1, 1}; + + while (!pq.empty()) { + Node current = pq.top(); + pq.pop(); + + if (current.point.x == end.x && current.point.y == end.y) { + // Мы достигли конечной точки + vector pathPoints; + Point currentPoint = end; + + while (!(currentPoint.x == position_.x && currentPoint.y == position_.y)) { + pathPoints.push_back(currentPoint); + currentPoint = path[currentPoint.y][currentPoint.x]; + } + + reverse(pathPoints.begin(), pathPoints.end()); + + for (const Point& point : pathPoints) { + int dx = point.x - currentPoint.x; + int dy = point.y - currentPoint.y; + + if (dx == -1) { + directions.push_back('L'); + } else if (dx == 1) { + directions.push_back('R'); + } else if (dy == -1) { + directions.push_back('U'); + } else if (dy == 1) { + directions.push_back('D'); + } + + currentPoint = point; + } + cout << endl; + + return directions; + } + + for (int i = 0; i < 4; ++i) { + int nextX = current.point.x + dx[i]; + int nextY = current.point.y + dy[i]; + + if (isValid(nextX, nextY)) { + int newDistance = current.distance + 1; // Вес каждого шага равен 1 + + if (newDistance < distance[nextY][nextX]) { + distance[nextY][nextX] = newDistance; + path[nextY][nextX] = current.point; + pq.push(Node(Point(nextX, nextY), newDistance)); + } + } + } + } + + // Если конечная точка недостижима, возвращаем пустой путь + return vector(); +} + +void Hostile::setPosition(Point& pos) +{ + position_ = pos; +} + +void Hostile::setMatrix(std::vector > &inputMatrix) +{ + matrix_ = inputMatrix; +} + +Point Hostile::getPosition() +{ + return position_; +} + +int Primer() { + // Пример использования + vector> inputMatrix = { + {0, 0, 0, 0, 0}, + {0, 1, 0, 1, 0}, + {0, 1, 0, 0, 1}, + {0, 1, 1, 0, 1}, + {1, 0, 0, 0, 0} + }; + + Hostile hostileObject(inputMatrix); + + Point start(4, 0); + Point end(0, 3); + + hostileObject.setPosition(start); + vector pathDirections = hostileObject.getPath(end); + + if (pathDirections.empty()) { + cout << "No path found." << endl; + } else { + cout << "Shortest Path Directions: "; + for (char direction : pathDirections) { + cout << direction << " "; + } + cout << endl; + } + + return 0; +} diff --git a/hostile.h b/hostile.h new file mode 100644 index 0000000..a6cd4f6 --- /dev/null +++ b/hostile.h @@ -0,0 +1,37 @@ +// hostile.h +#ifndef HOSTILE_H +#define HOSTILE_H + +#include +#include +#include +#include +#include + +struct Point { + int x, y; + + Point(int _x, int _y) : x(_x), y(_y) {} +}; + +class Hostile { + +private: + std::vector> matrix_; + + bool isValid(int x, int y); + Point& position_; + +public: + Hostile(); + Hostile(std::vector>& inputMatrix); + + std::vector getPath(const Point& end); + void setPosition(Point& pos); + void setMatrix(std::vector>& inputMatrix); + Point getPosition(); + int temp = 0; + +}; + +#endif // HOSTILE_H diff --git a/hostile.png b/hostile.png new file mode 100644 index 0000000000000000000000000000000000000000..6deb889ce4b5650c54a86d9e9a82e389ea0a81b0 GIT binary patch literal 416 zcmV;R0bl-!P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!2kdb!2!6DYwZ940X0cPK~z{r?UliD zgD?<7A)k<3d+h)JPH^;#=n)IGgm^j^4JCLMpa)+AQXvnp};)2DHq=m2duVEZRYKrGV&M0B7Gq8Xn znBzKJPcvKtSBx>_0xWS2R5t{KOPp7m;&h64U&INQ$a9kckhgvYm30)E&teK@`MB_- zxb_DFd+tD>NscB`2k4G73b~;2pV%EE%XJ*ZwWJ z$Mc-?c!?yOA0&t)ra~(23aN(173Qpp#pQyUpxe`!vbBE#!|)4nIN>oB;oLO<0000< KMNUMnLSTZv8o5&d literal 0 HcmV?d00001 diff --git a/mainwindow.cpp b/mainwindow.cpp index ab13062..e0da9c6 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -1,35 +1,50 @@ #include "mainwindow.h" #include "ui_mainwindow.h" +#include "hostile.h" + +#include +#include +#include +#include #include #include -MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), ui(new Ui::MainWindow) { + ui->setupUi(this); setFocusPolicy(Qt::StrongFocus); - tableWidget_ = ui->tableWidget; + scene = new QGraphicsScene(this); + view = new QGraphicsView(scene, this); - tableWidget_->setRowCount(rows_); - tableWidget_->setColumnCount(cols_); + int uiWidth = (cols_+1) * gridSize_; + int uiHeight = (rows_+1) * gridSize_; - tableWidget_->verticalHeader()->setDefaultSectionSize(32); - tableWidget_->horizontalHeader()->setDefaultSectionSize(32); + this->setFixedSize(uiWidth, uiHeight); + setCentralWidget(view); - tableWidget_->verticalHeader()->setVisible(false); - tableWidget_->horizontalHeader()->setVisible(false); + gameTimer_ = new QTimer(this); + gameTimer_->start(250); + connect(gameTimer_, SIGNAL(timeout()), this, SLOT(updateGameTime())); - tableWidget_->setVisible(true); - - // Выделите память для gameGrid gameGrid_ = new int*[rows_]; for (int i = 0; i < rows_; ++i) { gameGrid_[i] = new int[cols_]; } + generateRandomGameGrid(); setupGameGrid(); } +void MainWindow::updateGameTime() { + gameTime_ += 0.5; + isKeyTime_ = true; + moveHostile(); + setupGameGrid(); +} + MainWindow::~MainWindow(){ for (int i = 0; i < rows_; ++i) { delete[] gameGrid_[i]; @@ -43,8 +58,7 @@ void MainWindow::generateRandomGameGrid() { // Сбросим генератор случайных чисел std::srand(std::time(0)); - // Количество единиц в gameGrid - int onesCount = std::rand() % ((rows_ * cols_) / 5) + 1; + // Создадим пустую gameGrid for (int i = 0; i < rows_; ++i) { @@ -53,20 +67,6 @@ void MainWindow::generateRandomGameGrid() { } } - // Расставим единицы случайным образом - for (int k = 0; k < onesCount; ++k) { - int randomRow = std::rand() % rows_; - int randomCol = std::rand() % cols_; - - // Проверим, что выбранная ячейка еще не содержит 1 - while (gameGrid_[randomRow][randomCol] == 1) { - randomRow = std::rand() % rows_; - randomCol = std::rand() % cols_; - } - - gameGrid_[randomRow][randomCol] = 1; - } - // Расставим одну двойку int randomRow = std::rand() % rows_; int randomCol = std::rand() % cols_; @@ -75,81 +75,191 @@ void MainWindow::generateRandomGameGrid() { player_.setX(randomCol); player_.setY(randomRow); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; + + int element = 1; + int count = 5; + generateRandomElements(element,count); + + element = 3; + count = 2; + generateRandomElements(element,count); + } -void MainWindow::setupGameGrid() { - // Установите размер ячеек +void MainWindow::generateRandomElements(int element, int count) { + Hostile newHostile; + Point p(0,0); + if(element == 3){ + std::vector> matrix; + for (int i = 0; i < rows_; ++i) { + std::vector row; + for (int j = 0; j < cols_; ++j) { + row.push_back(gameGrid_[i][j]); + } + matrix.push_back(row); + } -// Заполните ячейки таблицы значениями из игровой сетки - for (int i = 0; i < rows_; ++i) { - for (int j = 0; j < cols_; ++j) { - QTableWidgetItem* item = new QTableWidgetItem; - item->setTextAlignment(Qt::AlignCenter); - item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - tableWidget_->setItem(i, j, item); - - switch (gameGrid_[i][j]) { - case 0: // Empty space - item->setBackground(QColor(Qt::white)); - break; - case 1: // Wall - item->setBackground(QColor(Qt::darkGray)); - break; - case 2: // player - item->setIcon(QIcon(":resource/puckman.png").pixmap(QSize(64, 64))); - break; + // Вывод матрицы + for (const auto& row : matrix) { + for (const auto& element : row) { + std::cout << element << " "; + } + std::cout << std::endl; + } + newHostile.setMatrix(matrix); + } + for (int k = 0; k < count; ++k) { + int randomRow = std::rand() % rows_; + int randomCol = std::rand() % cols_; + // Проверим, что выбранная ячейка еще не содержит 1 + while (gameGrid_[randomRow][randomCol] != 0) { + randomRow = std::rand() % rows_; + randomCol = std::rand() % cols_; + } + if(element == 3) + { + p.x = randomCol; + p.y = randomRow; + newHostile.setPosition(p); + hostiles_.push_back(newHostile); + } + gameGrid_[randomRow][randomCol] = element; + } +} + +void MainWindow::setupGameGrid() { + // Очистите сцену перед обновлением + scene->clear(); + QGraphicsPixmapItem* puckmanItem; + QGraphicsPixmapItem* hostileItem; + // Заполните сцену значениями из игровой сетки + for (int i = 0; i < rows_; ++i) { + for (int j = 0; j < cols_; ++j) { + switch (gameGrid_[i][j]) { + case 0: // Empty space + scene->addRect(j * gridSize_, i * gridSize_, gridSize_, gridSize_, QPen(Qt::black), QBrush(Qt::white)); + break; + case 1: // Wall + scene->addRect(j * gridSize_, i * gridSize_, gridSize_, gridSize_, QPen(Qt::black), QBrush(Qt::darkGray)); + break; + case 2: // player + puckmanItem = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(gridSize_, gridSize_)); + puckmanItem->setX(j * gridSize_); + puckmanItem->setY(i * gridSize_); + break; + case 3: // hostile + hostileItem = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(gridSize_, gridSize_)); + hostileItem->setX(j * gridSize_); + hostileItem->setY(i * gridSize_); + break; + } } } + + // Установите размер сцены + view->setSceneRect(0, 0, cols_ * gridSize_, rows_ * gridSize_); + + // Перерисовать сцену + view->update(); +} + +void MainWindow::moveHostile() +{ + if (hostiles_.empty()) { + qDebug() << "No hostiles found."; + return; } + std::vector direction; + Point playerPoint(player_.getX(), player_.getY()); + Point hostilePosition(0,0); - QSize tablesize = tableWidget_->sizeHint(); - this->resize(tablesize); + for (Hostile& currentHostile : hostiles_) { + direction = currentHostile.getPath(playerPoint); + if(direction[0] == 'L') + { + hostilePosition = currentHostile.getPosition(); + gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; + currentHostile.temp = gameGrid_[hostilePosition.y][hostilePosition.x-1]; + hostilePosition.x = hostilePosition.x - 1; + gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + currentHostile.setPosition(hostilePosition); + } + if(direction[0] == 'R') + { + hostilePosition = currentHostile.getPosition(); + gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; + currentHostile.temp = gameGrid_[hostilePosition.y][hostilePosition.x+1]; + hostilePosition.x = hostilePosition.x + 1; + gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + currentHostile.setPosition(hostilePosition); + } + if(direction[0] == 'U') + { + hostilePosition = currentHostile.getPosition(); + gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; + currentHostile.temp = gameGrid_[hostilePosition.y-1][hostilePosition.x]; + hostilePosition.y = hostilePosition.y - 1; + gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + currentHostile.setPosition(hostilePosition); + } + if(direction[0] == 'D') + { + hostilePosition = currentHostile.getPosition(); + gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; + currentHostile.temp = gameGrid_[hostilePosition.y+1][hostilePosition.x]; + hostilePosition.y = hostilePosition.y + 1; + gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + currentHostile.setPosition(hostilePosition); + } + } } void MainWindow::keyPressEvent(QKeyEvent *event) { - switch (event->key()) { - case Qt::Key_W: - qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; - movePlayerUp(); - break; - case Qt::Key_S: - qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; - movePlayerDown(); - break; - case Qt::Key_A: - movePlayerLeft(); - break; - case Qt::Key_D: - movePlayerRight(); - break; - default: - QMainWindow::keyPressEvent(event); - break; + if(isKeyTime_) + { + switch (event->key()) { + case Qt::Key_W: + movePlayerUp(); + isKeyTime_ = false; + break; + case Qt::Key_S: + movePlayerDown(); + isKeyTime_ = false; + break; + case Qt::Key_A: + movePlayerLeft(); + isKeyTime_ = false; + break; + case Qt::Key_D: + movePlayerRight(); + isKeyTime_ = false; + break; + default: + QMainWindow::keyPressEvent(event); + break; + } } } void MainWindow::movePlayerUp() { - if(gameGrid_[player_.getY()-1][player_.getX()] != 1) - { - if (player_.getY() > 0) { + if (player_.getY() > 0) { + if(gameGrid_[player_.getY()-1][player_.getX()] != 1) + { gameGrid_[player_.getY()][player_.getX()] = 0; gameGrid_[player_.getY()-1][player_.getX()] = 2; player_.setY(player_.getY() - 1); - setupGameGrid(); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } } } void MainWindow::movePlayerDown() { - int rowCount = tableWidget_->rowCount(); - if(gameGrid_[player_.getY()+1][player_.getX()] != 1) - { - if (player_.getY()+1 < rowCount) { + if (player_.getY()+1 < rows_) { + if(gameGrid_[player_.getY()+1][player_.getX()] != 1) + { gameGrid_[player_.getY()][player_.getX()] = 0; - gameGrid_[player_.getY()-1][player_.getX()] = 2; - player_.setY(player_.getY() - 1); - setupGameGrid(); + gameGrid_[player_.getY()+1][player_.getX()] = 2; + player_.setY(player_.getY() + 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } } @@ -162,21 +272,18 @@ void MainWindow::movePlayerLeft() { gameGrid_[player_.getY()][player_.getX()] = 0; gameGrid_[player_.getY()][player_.getX()-1] = 2; player_.setX(player_.getX() - 1); - setupGameGrid(); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } } } void MainWindow::movePlayerRight() { - int columnCount = tableWidget_->columnCount(); - if(gameGrid_[player_.getY()][player_.getX()+1] != 1) - { - if (player_.getX() < columnCount) { + if (player_.getX()+1 < cols_) { + if(gameGrid_[player_.getY()][player_.getX()+1] != 1) + { gameGrid_[player_.getY()][player_.getX()] = 0; gameGrid_[player_.getY()][player_.getX()+1] = 2; player_.setX(player_.getX() + 1); - setupGameGrid(); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } } diff --git a/mainwindow.h b/mainwindow.h index fe6cbec..d5e2414 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -2,9 +2,12 @@ #define MAINWINDOW_H #include "player.h" +#include "hostile.h" -#include +#include +#include #include +#include QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } @@ -25,15 +28,27 @@ Q_OBJECT private: Ui::MainWindow *ui; - QTableWidget* tableWidget_; - const int rows_ = 5; - const int cols_ = 5; + QTimer* gameTimer_; + float gameTime_; + const int rows_ = 10; + const int cols_ = 10; int **gameGrid_; + int gridSize_ = 64; + bool isKeyTime_ = true; Player player_; + std::vector hostiles_; void movePlayerUp(); void movePlayerDown(); void movePlayerLeft(); void movePlayerRight(); + void moveHostile(); + QGraphicsScene *scene; + QGraphicsView *view; + void generateRandomElements(int element, int count); + +private slots: + void updateGameTime(); + void handleKeyRepeat(); }; diff --git a/mainwindow.ui b/mainwindow.ui index c1bcffa..74d8304 100644 --- a/mainwindow.ui +++ b/mainwindow.ui @@ -16,10 +16,6 @@ - - 5 - 5 - diff --git a/resource.qrc b/resource.qrc index 882755d..15ecf95 100644 --- a/resource.qrc +++ b/resource.qrc @@ -1,5 +1,6 @@ puckman.png + hostile.png From d494c3c9ff551e4ceaec32a0b89adc50f6660b01 Mon Sep 17 00:00:00 2001 From: KloopRE <100780612+KloopRE@users.noreply.github.com> Date: Sun, 10 Dec 2023 02:57:19 +0300 Subject: [PATCH 3/8] =?UTF-8?q?=D0=95=D1=89=D0=B5=20=D0=B2=D0=BE=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit У меня проблема с событием перемещения мыши. Когда я вожу по краям своей формы ui, то событие срабатывает и выводятся координаты, но когда я вожу по его внутренней составляющей он не срабатывает. Я думаю, что проблема в этих строках: scene = new QGraphicsScene(this); view = new QGraphicsView(scene, this); view->setMouseTracking(true); Можете помочь? --- Pacman.pro | 12 ++- coin.png | Bin 0 -> 297 bytes hostile.cpp | 12 ++- hostile.h | 3 +- main.cpp | 3 +- mainwindow.cpp | 90 +++++++++++++++++++- mainwindow.h | 9 +- redactor.cpp | 225 +++++++++++++++++++++++++++++++++++++++++++++++++ redactor.h | 55 ++++++++++++ redactor.ui | 21 +++++ resource.qrc | 2 + startgame.cpp | 36 ++++++++ startgame.h | 29 +++++++ startgame.ui | 56 ++++++++++++ wall.png | Bin 0 -> 157 bytes 15 files changed, 542 insertions(+), 11 deletions(-) create mode 100644 coin.png create mode 100644 redactor.cpp create mode 100644 redactor.h create mode 100644 redactor.ui create mode 100644 startgame.cpp create mode 100644 startgame.h create mode 100644 startgame.ui create mode 100644 wall.png diff --git a/Pacman.pro b/Pacman.pro index 9f1bce2..6302b45 100644 --- a/Pacman.pro +++ b/Pacman.pro @@ -12,15 +12,21 @@ SOURCES += \ hostile.cpp \ main.cpp \ mainwindow.cpp \ - player.cpp + player.cpp \ + redactor.cpp \ + startgame.cpp HEADERS += \ hostile.h \ mainwindow.h \ - player.h + player.h \ + redactor.h \ + startgame.h FORMS += \ - mainwindow.ui + mainwindow.ui \ + redactor.ui \ + startgame.ui # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin diff --git a/coin.png b/coin.png new file mode 100644 index 0000000000000000000000000000000000000000..42f852fca512ff2aa431514caf1994bf4c10bc7f GIT binary patch literal 297 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz#^NA%Cx&(BWL^R}Ea{HEjtmSN z`?>!lvI6;>1s;*b3=Dh+L6~vJ#O${~!F`@Cjv*25Zzl!vwHR=)u4e!6@A(%dsY#Pc zJsZEjlG@DqIapYe=R%lB{^l=}AKkcp(SCn~nVo#;LG7GGmjw=6Hn0kMGN*NG&vg0m zIj>N4(hRW;p2m^>heSUJr75SrU;DS^L>ITmnW+m8tS_rSdYaR};bl+f(y$LK|CK)+ z*)7n<^u~KzPs-joSGXoQFe!>gDj!<-#J@z?zJ=ES3|U>& inputMatrix) : position_(0, 0) { + +} + +Hostile::Hostile() : position_(0, 0) { + +} + struct Node { Point point; int distance; @@ -17,7 +27,7 @@ struct Node { bool Hostile::isValid(int x, int y) { int rows = matrix_.size(); int cols = matrix_[0].size(); - return x >= 0 && x < cols && y >= 0 && y < rows && matrix_[y][x] != 1; + return x >= 0 && x < cols && y >= 0 && y < rows && matrix_[y][x] != 1 && matrix_[y][x] != 3; } vector getMoveDirections(const Point& start, const Point& end) { diff --git a/hostile.h b/hostile.h index a6cd4f6..cd49911 100644 --- a/hostile.h +++ b/hostile.h @@ -20,7 +20,7 @@ class Hostile { std::vector> matrix_; bool isValid(int x, int y); - Point& position_; + Point position_; public: Hostile(); @@ -31,7 +31,6 @@ class Hostile { void setMatrix(std::vector>& inputMatrix); Point getPosition(); int temp = 0; - }; #endif // HOSTILE_H diff --git a/main.cpp b/main.cpp index e9562cc..8faf187 100644 --- a/main.cpp +++ b/main.cpp @@ -1,3 +1,4 @@ +#include "startgame.h" #include "mainwindow.h" #include @@ -5,7 +6,7 @@ int main(int argc, char *argv[]) { QApplication a(argc, argv); - MainWindow w; + StartGame w; w.show(); return a.exec(); } diff --git a/mainwindow.cpp b/mainwindow.cpp index e0da9c6..3e7151c 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -2,6 +2,7 @@ #include "ui_mainwindow.h" #include "hostile.h" +#include "startgame.h" #include #include @@ -9,17 +10,19 @@ #include #include #include +#include MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { + ui->setupUi(this); setFocusPolicy(Qt::StrongFocus); scene = new QGraphicsScene(this); view = new QGraphicsView(scene, this); - int uiWidth = (cols_+1) * gridSize_; + int uiWidth = (cols_+4) * gridSize_; int uiHeight = (rows_+1) * gridSize_; this->setFixedSize(uiWidth, uiHeight); @@ -29,6 +32,10 @@ MainWindow::MainWindow(QWidget *parent) gameTimer_->start(250); connect(gameTimer_, SIGNAL(timeout()), this, SLOT(updateGameTime())); + hostileRunTimer_ = new QTimer(this); + hostileRunTimer_->start(1000); + connect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); + gameGrid_ = new int*[rows_]; for (int i = 0; i < rows_; ++i) { gameGrid_[i] = new int[cols_]; @@ -41,8 +48,19 @@ MainWindow::MainWindow(QWidget *parent) void MainWindow::updateGameTime() { gameTime_ += 0.5; isKeyTime_ = true; - moveHostile(); setupGameGrid(); + if(gameGrid_[player_.getY()][player_.getX()] == 3) + { + gameOver(false); + } + if(countCoins_ == 0) + { + gameOver(true); + } +} + +void MainWindow::updateHostileRunTime() { + moveHostile(); } MainWindow::~MainWindow(){ @@ -54,6 +72,33 @@ MainWindow::~MainWindow(){ delete ui; } +void MainWindow::gameOver(bool isWin) +{ + disconnect(gameTimer_, SIGNAL(timeout()), this, SLOT(updateGameTime())); + disconnect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); + if(isWin) + { + std::string str1 = "You WIN!"; + const char* charArray = str1.c_str(); + QMessageBox::information(this, "WIN", charArray); + } + else + { + std::string str1 = "Game Over, coins left: "; + std::string str2 = std::to_string(countCoins_); + str1.append(str2); + const char* charArray = str1.c_str(); + QMessageBox::information(this, "False", charArray); + } + close(); + handleGameOver(); +} + +void MainWindow::handleGameOver() { + StartGame *SG = new StartGame(); + SG->show(); +} + void MainWindow::generateRandomGameGrid() { // Сбросим генератор случайных чисел std::srand(std::time(0)); @@ -84,6 +129,9 @@ void MainWindow::generateRandomGameGrid() { count = 2; generateRandomElements(element,count); + element = 4; + generateRandomElements(element,countCoins_); + } void MainWindow::generateRandomElements(int element, int count) { @@ -132,6 +180,13 @@ void MainWindow::setupGameGrid() { scene->clear(); QGraphicsPixmapItem* puckmanItem; QGraphicsPixmapItem* hostileItem; + QGraphicsPixmapItem* coinItem; + QGraphicsTextItem* coinsLabel = scene->addText("Coins: "+ QString::number(countCoins_)); + coinsLabel->setDefaultTextColor(Qt::black); + QFont font = coinsLabel->font(); + font.setPointSize(14); // Настройте размер шрифта по вашему желанию + coinsLabel->setFont(font); + coinsLabel->setPos(cols_ * gridSize_ + 10, 10); // Заполните сцену значениями из игровой сетки for (int i = 0; i < rows_; ++i) { for (int j = 0; j < cols_; ++j) { @@ -152,6 +207,11 @@ void MainWindow::setupGameGrid() { hostileItem->setX(j * gridSize_); hostileItem->setY(i * gridSize_); break; + case 4: // hostile + coinItem = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); + coinItem->setX(j * gridSize_); + coinItem->setY(i * gridSize_); + break; } } } @@ -175,6 +235,10 @@ void MainWindow::moveHostile() for (Hostile& currentHostile : hostiles_) { direction = currentHostile.getPath(playerPoint); + if(direction.empty()) + { + return; + } if(direction[0] == 'L') { hostilePosition = currentHostile.getPosition(); @@ -195,20 +259,24 @@ void MainWindow::moveHostile() } if(direction[0] == 'U') { + hostilePosition = currentHostile.getPosition(); gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; currentHostile.temp = gameGrid_[hostilePosition.y-1][hostilePosition.x]; hostilePosition.y = hostilePosition.y - 1; gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + qDebug() << "gameGrid_ Coordinates: (" << hostilePosition.x << ", " << hostilePosition.y << ")"; currentHostile.setPosition(hostilePosition); } if(direction[0] == 'D') { + hostilePosition = currentHostile.getPosition(); gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; currentHostile.temp = gameGrid_[hostilePosition.y+1][hostilePosition.x]; hostilePosition.y = hostilePosition.y + 1; gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + qDebug() << "gameGrid_ Coordinates: (" << hostilePosition.x << ", " << hostilePosition.y << ")"; currentHostile.setPosition(hostilePosition); } } @@ -246,6 +314,10 @@ void MainWindow::movePlayerUp() { if(gameGrid_[player_.getY()-1][player_.getX()] != 1) { gameGrid_[player_.getY()][player_.getX()] = 0; + if(gameGrid_[player_.getY()-1][player_.getX()] == 4) + { + countCoins_--; + } gameGrid_[player_.getY()-1][player_.getX()] = 2; player_.setY(player_.getY() - 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; @@ -258,6 +330,10 @@ void MainWindow::movePlayerDown() { if(gameGrid_[player_.getY()+1][player_.getX()] != 1) { gameGrid_[player_.getY()][player_.getX()] = 0; + if(gameGrid_[player_.getY()+1][player_.getX()] == 4) + { + countCoins_--; + } gameGrid_[player_.getY()+1][player_.getX()] = 2; player_.setY(player_.getY() + 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; @@ -270,6 +346,10 @@ void MainWindow::movePlayerLeft() { { if (player_.getX() > 0) { gameGrid_[player_.getY()][player_.getX()] = 0; + if(gameGrid_[player_.getY()][player_.getX()-1] == 4) + { + countCoins_--; + } gameGrid_[player_.getY()][player_.getX()-1] = 2; player_.setX(player_.getX() - 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; @@ -282,9 +362,13 @@ void MainWindow::movePlayerRight() { if(gameGrid_[player_.getY()][player_.getX()+1] != 1) { gameGrid_[player_.getY()][player_.getX()] = 0; + if(gameGrid_[player_.getY()][player_.getX()+1] == 4) + { + countCoins_--; + } gameGrid_[player_.getY()][player_.getX()+1] = 2; player_.setX(player_.getX() + 1); - qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; + qDebug() << "Player Coordinates: (" << player_.getY() << ", " << player_.getX() << ")"; } } } diff --git a/mainwindow.h b/mainwindow.h index d5e2414..7c4e020 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -8,6 +8,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } @@ -30,10 +31,12 @@ Q_OBJECT Ui::MainWindow *ui; QTimer* gameTimer_; float gameTime_; + QTimer* hostileRunTimer_; const int rows_ = 10; const int cols_ = 10; int **gameGrid_; int gridSize_ = 64; + int countCoins_ = 5; bool isKeyTime_ = true; Player player_; std::vector hostiles_; @@ -45,10 +48,14 @@ Q_OBJECT QGraphicsScene *scene; QGraphicsView *view; void generateRandomElements(int element, int count); + void updateCoinsCount(); + void gameOver(bool isWin); + void handleGameOver(); private slots: void updateGameTime(); - void handleKeyRepeat(); + void updateHostileRunTime(); + void handleKeyRepeat(); }; diff --git a/redactor.cpp b/redactor.cpp new file mode 100644 index 0000000..e5ea874 --- /dev/null +++ b/redactor.cpp @@ -0,0 +1,225 @@ +#include "redactor.h" +#include "ui_redactor.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +Redactor::Redactor(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::Redactor) +{ + setMouseTracking(true); + ui->setupUi(this); + setFocusPolicy(Qt::StrongFocus); + + scene = new QGraphicsScene(this); + view = new QGraphicsView(scene, this); + + view->setMouseTracking(true); + + int uiWidth = (cols_+6) * gridSize_; + int uiHeight = (rows_+1) * gridSize_; + + this->setFixedSize(uiWidth, uiHeight); + setCentralWidget(view); + + gameGrid_ = new int*[rows_]; + for (int i = 0; i < rows_; ++i) { + gameGrid_[i] = new int[cols_]; + } + for (int i = 0; i < rows_; ++i) { + for (int j = 0; j < cols_; ++j) { + gameGrid_[i][j] = 0; + } + } + + setupGameGrid(); + + ui->setupUi(this); +} + +Redactor::~Redactor() +{ + for (int i = 0; i < rows_; ++i) { + delete[] gameGrid_[i]; + } + delete[] gameGrid_; + delete ui; +} + +void Redactor::paintEvent(QPaintEvent *event) { + QPainter painter(this); + dragItem(); +} + +void Redactor::dragItem() { + dragItem_ = new QGraphicsPixmapItem(); + if(dragElement_ == 1) + { + dragItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(gridSize_, gridSize_)); + } + if(dragElement_ == 2) + { + dragItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(gridSize_, gridSize_)); + } + if(dragElement_ == 3) + { + dragItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(gridSize_, gridSize_)); + } + if(dragElement_ == 4) + { + dragItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); + } + dragItem_->setX(center_.x()); + dragItem_->setY(center_.y()); +} + +void Redactor::setupGameGrid() { + // Очистите сцену перед обновлением + scene->clear(); + QGraphicsPixmapItem* puckmanItem; + QGraphicsPixmapItem* hostileItem; + QGraphicsPixmapItem* coinItem; + + // Заполните сцену значениями из игровой сетки + for (int i = 0; i < rows_; ++i) { + for (int j = 0; j < cols_; ++j) { + switch (gameGrid_[i][j]) { + case 0: // Empty space + scene->addRect(j * gridSize_, i * gridSize_, gridSize_, gridSize_, QPen(Qt::black), QBrush(Qt::white)); + break; + case 1: // Wall + scene->addRect(j * gridSize_, i * gridSize_, gridSize_, gridSize_, QPen(Qt::black), QBrush(Qt::darkGray)); + break; + case 2: // player + puckmanItem = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(gridSize_, gridSize_)); + puckmanItem->setX(j * gridSize_); + puckmanItem->setY(i * gridSize_); + break; + case 3: // hostile + hostileItem = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(gridSize_, gridSize_)); + hostileItem->setX(j * gridSize_); + hostileItem->setY(i * gridSize_); + break; + case 4: // hostile + coinItem = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); + coinItem->setX(j * gridSize_); + coinItem->setY(i * gridSize_); + break; + } + } + } + int RETURN = 2; + + wallItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(gridSize_, gridSize_)); + wallItem_->setX((cols_+RETURN) * gridSize_); + wallItem_->setY(1 * gridSize_); + qDebug() << "wallItem Coordinates: (" << wallItem_->x() << ", " << wallItem_->y() << ")"; + + puckmanItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(gridSize_, gridSize_)); + puckmanItem_->setX((cols_+RETURN) * gridSize_); + puckmanItem_->setY(4 * gridSize_); + qDebug() << "puckmanItem Coordinates: (" << puckmanItem_->x() << ", " << puckmanItem_->y() << ")"; + + hostileItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(gridSize_, gridSize_)); + hostileItem_->setX((cols_+RETURN) * gridSize_); + hostileItem_->setY(6 * gridSize_); + qDebug() << "hostileItem Coordinates: (" << hostileItem_->x() << ", " << hostileItem_->y() << ")"; + + coinItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); + coinItem_->setX((cols_+RETURN) * gridSize_); + coinItem_->setY(8 * gridSize_); + qDebug() << "coinItem Coordinates: (" << coinItem_->x() << ", " << coinItem_->y() << ")"; + + // Установите размер сцены + view->setSceneRect(0, 0, cols_ * gridSize_, rows_ * gridSize_); + + // Перерисовать сцену + view->update(); + view->setMouseTracking(true); +} + +int Redactor::getElement() { + QGraphicsItem* item = scene->itemAt(center_.x(), center_.y(), QTransform()); + if(center_.x() < wallItem_->x()+gridSize_ && center_.x() > wallItem_->x()-gridSize_) + { + if(center_.y() < wallItem_->y()+gridSize_ && center_.y() > wallItem_->y()-gridSize_) + { + qDebug() << "you drag item: (" << item << ")"; + return 1; + } + } + if(center_.x() < puckmanItem_->x()+gridSize_ && center_.x() > puckmanItem_->x()-gridSize_) + { + if(center_.y() < puckmanItem_->y()+gridSize_ && center_.y() > puckmanItem_->y()-gridSize_) + { + qDebug() << "you drag item: (" << item << ")"; + return 2; + } + } + if(center_.x() < hostileItem_->x()+gridSize_ && center_.x() > hostileItem_->x()-gridSize_) + { + if(center_.y() < hostileItem_->y()+gridSize_ && center_.y() > hostileItem_->y()-gridSize_) + { + qDebug() << "you drag item: (" << item << ")"; + return 3; + } + } + if(center_.x() < coinItem_->x()+gridSize_ && center_.x() > coinItem_->x()-gridSize_) + { + if(center_.y() < coinItem_->y()+gridSize_ && center_.y() > coinItem_->y()-gridSize_) + { + qDebug() << "you drag item: (" << item << ")"; + return 4; + } + } + qDebug() << "you drag item: (" << item << ")"; + return 0; +} + +void Redactor::setCursorStyle() { + if (isdrawing_) { + setCursor(Qt::CrossCursor); + } else { + setCursor(Qt::ArrowCursor); + } +} + +void Redactor::mousePressEvent(QMouseEvent *event) { + if (event->button() == Qt::LeftButton) { + isdrawing_ = true; + QPoint localMousePos = event->pos(); // Получаем локальные координаты мыши + center_ = view->mapToScene(localMousePos); + center_.setX(center_.x() - gridSize_ / 2); + center_.setY(center_.y() - gridSize_ / 2); + setCursorStyle(); + qDebug() << "cursor Coordinates: (" << center_.x() << ", " << center_.y() << ")"; + dragElement_ = getElement(); + qDebug() << "you drag item: (" << getElement() << ")"; + update(); + } +} + +void Redactor::mouseMoveEvent(QMouseEvent *event) { + if (isdrawing_) { + center_ = event->pos(); + update(); + qDebug() << "cursor Coordinates: (" << center_.x() << ", " << center_.y() << ")"; + } +} + +void Redactor::mouseReleaseEvent(QMouseEvent *event) { + if (event->button() == Qt::LeftButton && isdrawing_) { + isdrawing_ = false; + setCursorStyle(); + scene->removeItem(dragItem_); + delete dragItem_; + setupGameGrid(); + } +} diff --git a/redactor.h b/redactor.h new file mode 100644 index 0000000..dcbc5c8 --- /dev/null +++ b/redactor.h @@ -0,0 +1,55 @@ +#ifndef REDACTOR_H +#define REDACTOR_H + +#include +#include +#include + +#include "mainwindow.h" + +namespace Ui { +class Redactor; +} + +class Redactor : public QMainWindow { + Q_OBJECT + +public: + Redactor(QWidget *parent = nullptr); + ~Redactor(); + +protected: + void paintEvent(QPaintEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + +private: + Ui::Redactor *ui; + MainWindow *MW; + int **gameGrid_; + const int rows_ = 10; + const int cols_ = 10; + int gridSize_ = 64; + void setupGameGrid(); + QGraphicsScene *scene; + QGraphicsView *view; + bool isdrawing_ = false; + QPointF center_; + int lineWidth_; + QColor lineColor_; + void drawItems(QPainter *painter, const QPoint ¢er); + int getElement(); + QGraphicsPixmapItem* wallItem_; + QGraphicsPixmapItem* puckmanItem_; + QGraphicsPixmapItem* hostileItem_; + QGraphicsPixmapItem* coinItem_; + QGraphicsPixmapItem* dragItem_; + int dragElement_; + void dragItem(); + +private slots: + void setCursorStyle(); +}; + +#endif // REDACTOR_H diff --git a/redactor.ui b/redactor.ui new file mode 100644 index 0000000..55dbda6 --- /dev/null +++ b/redactor.ui @@ -0,0 +1,21 @@ + + + + + Redactor + + + + 0 + 0 + 400 + 300 + + + + Form + + + + + diff --git a/resource.qrc b/resource.qrc index 15ecf95..58ffa1e 100644 --- a/resource.qrc +++ b/resource.qrc @@ -2,5 +2,7 @@ puckman.png hostile.png + coin.png + wall.png diff --git a/startgame.cpp b/startgame.cpp new file mode 100644 index 0000000..27891ac --- /dev/null +++ b/startgame.cpp @@ -0,0 +1,36 @@ +#include "startgame.h" +#include "ui_startgame.h" +#include "mainwindow.h" +#include "redactor.h" + +StartGame::StartGame(QWidget *parent) : + QWidget(parent), + ui(new Ui::StartGame) +{ + ui->setupUi(this); + loadUI(); +} + +StartGame::~StartGame() +{ + delete ui; +} + +void StartGame::loadUI(){ + ui->play_button->setFont(QFont(default_font_family_, font_size_)); + ui->redactor_button->setFont(QFont(default_font_family_, font_size_)); +} + +void StartGame::on_play_button_clicked() +{ + this->close(); + MainWindow *game = new MainWindow(); + game->show(); +} + +void StartGame::on_redactor_button_clicked() +{ + this->close(); + Redactor *game = new Redactor(); + game->show(); +} diff --git a/startgame.h b/startgame.h new file mode 100644 index 0000000..5bae53a --- /dev/null +++ b/startgame.h @@ -0,0 +1,29 @@ +#ifndef STARTGAME_H +#define STARTGAME_H + +#include + +namespace Ui { +class StartGame; +} + +class StartGame : public QWidget +{ + Q_OBJECT + +public: + explicit StartGame(QWidget *parent = nullptr); + ~StartGame(); + +private slots: + void on_play_button_clicked(); + void on_redactor_button_clicked(); + +private: + Ui::StartGame *ui; + static const int font_size_ = 15; + const QString default_font_family_ = "Default"; + void loadUI(); +}; + +#endif // STARTGAME_H diff --git a/startgame.ui b/startgame.ui new file mode 100644 index 0000000..591bdaa --- /dev/null +++ b/startgame.ui @@ -0,0 +1,56 @@ + + + + + StartGame + + + + 0 + 0 + 500 + 550 + + + + Pacman + + + + + + + + + 190 + 170 + 90 + 30 + + + + PLAY + + + + + + + + 190 + 210 + 120 + 30 + + + + REDACTOR + + + + + + + + + diff --git a/wall.png b/wall.png new file mode 100644 index 0000000000000000000000000000000000000000..b7e086d8e61d535a30ae8641168fe4b537d16b9f GIT binary patch literal 157 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz#^NA%Cx&(BWL^R}Ea{HEjtmSN z`?>!lvI6;>1s;*b3=Dh+L6~vJ#O${~K_gEW$B+p3x91izGAIZf+0cA6zr^6pho&o6 m(ze=4=IrkW=|q4J)(Si26`1xo>{(_867_WTb6Mw<&;$Uz)+$>7 literal 0 HcmV?d00001 From 6f7e4bd9bde273c9420d7db117d43fc04bd1ccf1 Mon Sep 17 00:00:00 2001 From: KloopRE <100780612+KloopRE@users.noreply.github.com> Date: Tue, 12 Dec 2023 11:52:52 +0300 Subject: [PATCH 4/8] redactor add redactor --- Pacman.pro | 2 + customgraphicsview.cpp | 38 ++++++++++++ customgraphicsview.h | 27 +++++++++ mainwindow.cpp | 87 +++++++++++++++++++++++++- mainwindow.h | 1 + redactor.cpp | 135 +++++++++++++++++++++++++++-------------- redactor.h | 18 +++--- startgame.cpp | 2 +- startgame.ui | 93 ++++++++++++++++------------ 9 files changed, 308 insertions(+), 95 deletions(-) create mode 100644 customgraphicsview.cpp create mode 100644 customgraphicsview.h diff --git a/Pacman.pro b/Pacman.pro index 6302b45..49d2731 100644 --- a/Pacman.pro +++ b/Pacman.pro @@ -9,6 +9,7 @@ CONFIG += c++17 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ + customgraphicsview.cpp \ hostile.cpp \ main.cpp \ mainwindow.cpp \ @@ -17,6 +18,7 @@ SOURCES += \ startgame.cpp HEADERS += \ + customgraphicsview.h \ hostile.h \ mainwindow.h \ player.h \ diff --git a/customgraphicsview.cpp b/customgraphicsview.cpp new file mode 100644 index 0000000..e49e3c1 --- /dev/null +++ b/customgraphicsview.cpp @@ -0,0 +1,38 @@ +// customgraphicsview.cpp +#include "customgraphicsview.h" + +#include +#include + +CustomGraphicsView::CustomGraphicsView(QGraphicsScene *scene, QWidget *parent, int gridSize) + : QGraphicsView(scene, parent), gridSize(gridSize) // Добавьте инициализацию gridSize +{ + setMouseTracking(true); +} + +void CustomGraphicsView::mouseMoveEvent(QMouseEvent *event) { + if (isdrawing) { + QPoint localMousePos = event->pos(); + center = this->mapToScene(localMousePos); + center.setX(this->center.x() - gridSize / 2); + center.setY(this->center.y() - gridSize / 2); + update(); + qDebug() << "cursor Coordinates: (" << center.x() << ", " << center.y() << ")"; + } +} + +void CustomGraphicsView::mouseReleaseEvent(QMouseEvent *event) { + if (event->button() == Qt::LeftButton && isdrawing) { + isdrawing = false; + setCursorStyle(); + emit customMouseRelease(); + } +} + +void CustomGraphicsView::setCursorStyle() { + if (isdrawing) { + setCursor(Qt::CrossCursor); + } else { + setCursor(Qt::ArrowCursor); + } +} diff --git a/customgraphicsview.h b/customgraphicsview.h new file mode 100644 index 0000000..1db9e42 --- /dev/null +++ b/customgraphicsview.h @@ -0,0 +1,27 @@ +#ifndef CUSTOMGRAPHICSVIEW_H +#define CUSTOMGRAPHICSVIEW_H + +#include +#include + +class CustomGraphicsView : public QGraphicsView { + Q_OBJECT + +public: + CustomGraphicsView(QGraphicsScene *scene, QWidget *parent = nullptr, int gridSize = 64); + QPointF center; + bool isdrawing = false; + void setCursorStyle(); + +protected: + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + +private: + int gridSize; + +signals: + void customMouseRelease(); +}; + +#endif // CUSTOMGRAPHICSVIEW_H diff --git a/mainwindow.cpp b/mainwindow.cpp index 3e7151c..36928c2 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -36,12 +36,97 @@ MainWindow::MainWindow(QWidget *parent) hostileRunTimer_->start(1000); connect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); + gameGrid_ = new int*[rows_]; for (int i = 0; i < rows_; ++i) { gameGrid_[i] = new int[cols_]; } + generateRandomGameGrid(); + + setupGameGrid(); +} + +MainWindow::MainWindow(QWidget *parent, int** gameGrid) + : QMainWindow(parent), ui(new Ui::MainWindow) { + + + ui->setupUi(this); + setFocusPolicy(Qt::StrongFocus); + + hostiles_.reserve(cols_*rows_); + + scene = new QGraphicsScene(this); + view = new QGraphicsView(scene, this); + + int uiWidth = (cols_+4) * gridSize_; + int uiHeight = (rows_+1) * gridSize_; + + this->setFixedSize(uiWidth, uiHeight); + setCentralWidget(view); + + gameTimer_ = new QTimer(this); + gameTimer_->start(250); + connect(gameTimer_, SIGNAL(timeout()), this, SLOT(updateGameTime())); + + hostileRunTimer_ = new QTimer(this); + hostileRunTimer_->start(1000); + connect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); + + if (gameGrid != nullptr) { + countCoins_ = 0; + std::vector> matrix; + for (int i = 0; i < rows_; ++i) { + std::vector row; + for (int j = 0; j < cols_; ++j) { + row.push_back(gameGrid[i][j]); + } + matrix.push_back(row); + } + + // Вывод матрицы + for (const auto& row : matrix) { + for (const auto& element : row) { + std::cout << element << " "; + } + std::cout << std::endl; + } + } + Hostile newHostile; + Point p(0, 0); + if (gameGrid != nullptr) { + // Если передан, копируем его значения + gameGrid_ = new int*[rows_]; + for (int i = 0; i < rows_; ++i) { + gameGrid_[i] = new int[cols_]; + for (int j = 0; j < cols_; ++j) { + gameGrid_[i][j] = gameGrid[i][j]; + if(gameGrid_[i][j] == 3) + { + p.x = i; + p.y = j; + newHostile.setPosition(p); + qDebug() << "Hostile Coordinates: (" << p.x << ", " << p.y << ")"; + hostiles_.push_back(newHostile); + } + if(gameGrid_[i][j] == 4) + { + countCoins_++; + } + if(gameGrid_[i][j] == 2) + { + player_.setY(i); + player_.setX(j); + } + } + } + } else { + gameGrid_ = new int*[rows_]; + for (int i = 0; i < rows_; ++i) { + gameGrid_[i] = new int[cols_]; + } + generateRandomGameGrid(); + } - generateRandomGameGrid(); setupGameGrid(); } diff --git a/mainwindow.h b/mainwindow.h index 7c4e020..cafa1f5 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -19,6 +19,7 @@ Q_OBJECT public: MainWindow(QWidget *parent = nullptr); + MainWindow(QWidget *parent = nullptr, int** gameGrid = nullptr); ~MainWindow(); void generateRandomGameGrid(); diff --git a/redactor.cpp b/redactor.cpp index e5ea874..6335d06 100644 --- a/redactor.cpp +++ b/redactor.cpp @@ -1,9 +1,9 @@ #include "redactor.h" #include "ui_redactor.h" +#include "mainwindow.h" #include #include -#include #include #include #include @@ -14,14 +14,16 @@ Redactor::Redactor(QWidget *parent) : QMainWindow(parent), ui(new Ui::Redactor) { - setMouseTracking(true); ui->setupUi(this); setFocusPolicy(Qt::StrongFocus); scene = new QGraphicsScene(this); - view = new QGraphicsView(scene, this); + view = new CustomGraphicsView(scene, this, gridSize_); view->setMouseTracking(true); + view->hasMouseTracking(); + + connect(view, &CustomGraphicsView::customMouseRelease, this, &Redactor::handleCustomMouseRelease); int uiWidth = (cols_+6) * gridSize_; int uiHeight = (rows_+1) * gridSize_; @@ -39,11 +41,30 @@ Redactor::Redactor(QWidget *parent) : } } + myButton = new QPushButton("Начать игру", this); + myButton->setGeometry(10, 10, 100, 30); // Установите положение и размер кнопки + connect(myButton, &QPushButton::clicked, this, &Redactor::handleButtonClick); + setupGameGrid(); ui->setupUi(this); } +void Redactor::exitRedaction() +{ + close(); + openGame(); +} + +void Redactor::openGame() { + MainWindow *SG = new MainWindow(nullptr, gameGrid_); + SG->show(); +} + +void Redactor::handleButtonClick() { + exitRedaction(); +} + Redactor::~Redactor() { for (int i = 0; i < rows_; ++i) { @@ -54,11 +75,14 @@ Redactor::~Redactor() } void Redactor::paintEvent(QPaintEvent *event) { - QPainter painter(this); dragItem(); } void Redactor::dragItem() { + if (dragItem_ != nullptr) { + scene->removeItem(dragItem_); + delete dragItem_; + } dragItem_ = new QGraphicsPixmapItem(); if(dragElement_ == 1) { @@ -76,8 +100,8 @@ void Redactor::dragItem() { { dragItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); } - dragItem_->setX(center_.x()); - dragItem_->setY(center_.y()); + dragItem_->setX(view->center.x()); + dragItem_->setY(view->center.y()); } void Redactor::setupGameGrid() { @@ -142,38 +166,61 @@ void Redactor::setupGameGrid() { // Перерисовать сцену view->update(); - view->setMouseTracking(true); +} + +QPoint Redactor::getGridPoint() { + QPoint a(-1, -1); + for (int i = 0; i < rows_; ++i) { + for (int j = 0; j < cols_; ++j) { + if(view->center.x() > i*gridSize_-gridSize_/2 && view->center.x() < i*gridSize_+gridSize_/2) + { + if(view->center.y() > j*gridSize_-gridSize_/2 && view->center.y() < j*gridSize_+gridSize_/2) + { + a.setX(i); + a.setY(j); + qDebug() << "getGridPoint Coordinates: (" << a.x() << ", " << a.y() << ")"; + return(a); + } + } + } + } + qDebug() << "getGridPoint Coordinates: (" << a.x() << ", " << a.y() << ")"; + return a; + } int Redactor::getElement() { - QGraphicsItem* item = scene->itemAt(center_.x(), center_.y(), QTransform()); - if(center_.x() < wallItem_->x()+gridSize_ && center_.x() > wallItem_->x()-gridSize_) + QGraphicsItem* item = scene->itemAt(view->center.x(), view->center.y(), QTransform()); + if(view->center.x() < wallItem_->x()+gridSize_ && view->center.x() > wallItem_->x()-gridSize_) { - if(center_.y() < wallItem_->y()+gridSize_ && center_.y() > wallItem_->y()-gridSize_) + if(view->center.y() < wallItem_->y()+gridSize_ && view->center.y() > wallItem_->y()-gridSize_) { qDebug() << "you drag item: (" << item << ")"; return 1; } } - if(center_.x() < puckmanItem_->x()+gridSize_ && center_.x() > puckmanItem_->x()-gridSize_) + if(view->center.x() < puckmanItem_->x()+gridSize_ && view->center.x() > puckmanItem_->x()-gridSize_) { - if(center_.y() < puckmanItem_->y()+gridSize_ && center_.y() > puckmanItem_->y()-gridSize_) + if(view->center.y() < puckmanItem_->y()+gridSize_ && view->center.y() > puckmanItem_->y()-gridSize_) { - qDebug() << "you drag item: (" << item << ")"; - return 2; + if(isStatePacmanElement_ == false) + { + qDebug() << "you drag item: (" << item << ")"; + return 2; + } } } - if(center_.x() < hostileItem_->x()+gridSize_ && center_.x() > hostileItem_->x()-gridSize_) + if(view->center.x() < hostileItem_->x()+gridSize_ && view->center.x() > hostileItem_->x()-gridSize_) { - if(center_.y() < hostileItem_->y()+gridSize_ && center_.y() > hostileItem_->y()-gridSize_) + if(view->center.y() < hostileItem_->y()+gridSize_ && view->center.y() > hostileItem_->y()-gridSize_) { qDebug() << "you drag item: (" << item << ")"; return 3; } } - if(center_.x() < coinItem_->x()+gridSize_ && center_.x() > coinItem_->x()-gridSize_) + if(view->center.x() < coinItem_->x()+gridSize_ && view->center.x() > coinItem_->x()-gridSize_) { - if(center_.y() < coinItem_->y()+gridSize_ && center_.y() > coinItem_->y()-gridSize_) + if(view->center.y() < coinItem_->y()+gridSize_ && view->center.y() > coinItem_->y()-gridSize_) { qDebug() << "you drag item: (" << item << ")"; return 4; @@ -183,43 +230,39 @@ int Redactor::getElement() { return 0; } -void Redactor::setCursorStyle() { - if (isdrawing_) { - setCursor(Qt::CrossCursor); - } else { - setCursor(Qt::ArrowCursor); - } -} - void Redactor::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { - isdrawing_ = true; + dragItem_ = new QGraphicsPixmapItem(); + view->isdrawing = true; QPoint localMousePos = event->pos(); // Получаем локальные координаты мыши - center_ = view->mapToScene(localMousePos); - center_.setX(center_.x() - gridSize_ / 2); - center_.setY(center_.y() - gridSize_ / 2); - setCursorStyle(); - qDebug() << "cursor Coordinates: (" << center_.x() << ", " << center_.y() << ")"; + view->center = view->mapToScene(localMousePos); + view->center.setX(view->center.x()); + view->center.setY(view->center.y()); + view->setCursorStyle(); + qDebug() << "cursor Coordinates: (" << view->center.x() << ", " << view->center.y() << ")"; dragElement_ = getElement(); qDebug() << "you drag item: (" << getElement() << ")"; - update(); - } -} -void Redactor::mouseMoveEvent(QMouseEvent *event) { - if (isdrawing_) { - center_ = event->pos(); update(); - qDebug() << "cursor Coordinates: (" << center_.x() << ", " << center_.y() << ")"; } + } -void Redactor::mouseReleaseEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton && isdrawing_) { - isdrawing_ = false; - setCursorStyle(); - scene->removeItem(dragItem_); - delete dragItem_; - setupGameGrid(); +void Redactor::handleCustomMouseRelease() { + dragItem_ = new QGraphicsPixmapItem(); + QPoint a = getGridPoint(); + if(a.x() > 0 || a.y() > 0) + { + if (gameGrid_[a.y()][a.x()] == 2) + { + isStatePacmanElement_ = false; + } + gameGrid_[a.y()][a.x()] = dragElement_; + if(dragElement_ == 2) + { + isStatePacmanElement_ = true; + } } + update(); + setupGameGrid(); } diff --git a/redactor.h b/redactor.h index dcbc5c8..c2d8117 100644 --- a/redactor.h +++ b/redactor.h @@ -3,9 +3,10 @@ #include #include -#include +#include #include "mainwindow.h" +#include "customgraphicsview.h" namespace Ui { class Redactor; @@ -21,8 +22,6 @@ class Redactor : public QMainWindow { protected: void paintEvent(QPaintEvent *event) override; void mousePressEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; private: Ui::Redactor *ui; @@ -33,7 +32,7 @@ class Redactor : public QMainWindow { int gridSize_ = 64; void setupGameGrid(); QGraphicsScene *scene; - QGraphicsView *view; + CustomGraphicsView *view; bool isdrawing_ = false; QPointF center_; int lineWidth_; @@ -44,12 +43,17 @@ class Redactor : public QMainWindow { QGraphicsPixmapItem* puckmanItem_; QGraphicsPixmapItem* hostileItem_; QGraphicsPixmapItem* coinItem_; - QGraphicsPixmapItem* dragItem_; + QGraphicsPixmapItem* dragItem_ = nullptr; + QPoint getGridPoint(); int dragElement_; void dragItem(); + void handleCustomMouseRelease(); + bool isStatePacmanElement_ = false; + QPushButton *myButton; + void handleButtonClick(); + void openGame(); + void exitRedaction(); -private slots: - void setCursorStyle(); }; #endif // REDACTOR_H diff --git a/startgame.cpp b/startgame.cpp index 27891ac..9d4ae97 100644 --- a/startgame.cpp +++ b/startgame.cpp @@ -24,7 +24,7 @@ void StartGame::loadUI(){ void StartGame::on_play_button_clicked() { this->close(); - MainWindow *game = new MainWindow(); + MainWindow *game = new MainWindow(nullptr, nullptr); game->show(); } diff --git a/startgame.ui b/startgame.ui index 591bdaa..9d8952b 100644 --- a/startgame.ui +++ b/startgame.ui @@ -1,56 +1,69 @@ + - - - StartGame - - - 0 - 0 - 500 - 550 - - - - Pacman - - - - - - + + + 0 + 0 + 500 + 550 + + + + Pacman + + + + + - 190 - 170 - 90 - 30 + 0 + 0 + 470 + 370 - - PLAY - - - - + - 190 - 210 - 120 - 30 + 0 + 0 + 500 + 450 - - REDACTOR - + + + + 190 + 190 + 75 + 23 + + + + PLAY + + + + + + 180 + 260 + 101 + 21 + + + + REDACTOR + + - - - - + + From 4747e86c3d58f614f0933d495b95a40d3e8bceca Mon Sep 17 00:00:00 2001 From: KloopRE <100780612+KloopRE@users.noreply.github.com> Date: Tue, 12 Dec 2023 18:35:48 +0300 Subject: [PATCH 5/8] pacman edir comments --- customgraphicsview.cpp | 2 +- hostile.cpp | 7 ++----- mainwindow.cpp | 41 +++++++++++++++++++++++------------------ player.cpp | 4 +--- player.h | 2 +- redactor.cpp | 4 ---- 6 files changed, 28 insertions(+), 32 deletions(-) diff --git a/customgraphicsview.cpp b/customgraphicsview.cpp index e49e3c1..df89206 100644 --- a/customgraphicsview.cpp +++ b/customgraphicsview.cpp @@ -1,4 +1,4 @@ -// customgraphicsview.cpp + #include "customgraphicsview.h" #include diff --git a/hostile.cpp b/hostile.cpp index 83032a1..0cbc7fd 100644 --- a/hostile.cpp +++ b/hostile.cpp @@ -18,7 +18,6 @@ struct Node { Node(Point _point, int _distance) : point(_point), distance(_distance) {} - // Перегрузка оператора "больше" для приоритетной очереди bool operator>(const Node& other) const { return distance > other.distance; } @@ -64,7 +63,6 @@ vector Hostile::getPath(const Point& end) { pq.push(Node(position_, 0)); distance[position_.y][position_.x] = 0; - // Возможные смещения влево, вправо, вверх и вниз int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; @@ -73,7 +71,7 @@ vector Hostile::getPath(const Point& end) { pq.pop(); if (current.point.x == end.x && current.point.y == end.y) { - // Мы достигли конечной точки + vector pathPoints; Point currentPoint = end; @@ -121,7 +119,6 @@ vector Hostile::getPath(const Point& end) { } } - // Если конечная точка недостижима, возвращаем пустой путь return vector(); } @@ -141,7 +138,7 @@ Point Hostile::getPosition() } int Primer() { - // Пример использования + vector> inputMatrix = { {0, 0, 0, 0, 0}, {0, 1, 0, 1, 0}, diff --git a/mainwindow.cpp b/mainwindow.cpp index 36928c2..8c2e817 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -82,8 +82,6 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) } matrix.push_back(row); } - - // Вывод матрицы for (const auto& row : matrix) { for (const auto& element : row) { std::cout << element << " "; @@ -94,7 +92,6 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) Hostile newHostile; Point p(0, 0); if (gameGrid != nullptr) { - // Если передан, копируем его значения gameGrid_ = new int*[rows_]; for (int i = 0; i < rows_; ++i) { gameGrid_[i] = new int[cols_]; @@ -102,8 +99,8 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) gameGrid_[i][j] = gameGrid[i][j]; if(gameGrid_[i][j] == 3) { - p.x = i; - p.y = j; + p.x = j; + p.y = i; newHostile.setPosition(p); qDebug() << "Hostile Coordinates: (" << p.x << ", " << p.y << ")"; hostiles_.push_back(newHostile); @@ -185,19 +182,15 @@ void MainWindow::handleGameOver() { } void MainWindow::generateRandomGameGrid() { - // Сбросим генератор случайных чисел - std::srand(std::time(0)); - + std::srand(std::time(0)); - // Создадим пустую gameGrid for (int i = 0; i < rows_; ++i) { for (int j = 0; j < cols_; ++j) { gameGrid_[i][j] = 0; } } - // Расставим одну двойку int randomRow = std::rand() % rows_; int randomCol = std::rand() % cols_; @@ -232,7 +225,6 @@ void MainWindow::generateRandomElements(int element, int count) { matrix.push_back(row); } - // Вывод матрицы for (const auto& row : matrix) { for (const auto& element : row) { std::cout << element << " "; @@ -244,7 +236,7 @@ void MainWindow::generateRandomElements(int element, int count) { for (int k = 0; k < count; ++k) { int randomRow = std::rand() % rows_; int randomCol = std::rand() % cols_; - // Проверим, что выбранная ячейка еще не содержит 1 + while (gameGrid_[randomRow][randomCol] != 0) { randomRow = std::rand() % rows_; randomCol = std::rand() % cols_; @@ -261,7 +253,6 @@ void MainWindow::generateRandomElements(int element, int count) { } void MainWindow::setupGameGrid() { - // Очистите сцену перед обновлением scene->clear(); QGraphicsPixmapItem* puckmanItem; QGraphicsPixmapItem* hostileItem; @@ -269,10 +260,9 @@ void MainWindow::setupGameGrid() { QGraphicsTextItem* coinsLabel = scene->addText("Coins: "+ QString::number(countCoins_)); coinsLabel->setDefaultTextColor(Qt::black); QFont font = coinsLabel->font(); - font.setPointSize(14); // Настройте размер шрифта по вашему желанию + font.setPointSize(14); coinsLabel->setFont(font); coinsLabel->setPos(cols_ * gridSize_ + 10, 10); - // Заполните сцену значениями из игровой сетки for (int i = 0; i < rows_; ++i) { for (int j = 0; j < cols_; ++j) { switch (gameGrid_[i][j]) { @@ -292,7 +282,7 @@ void MainWindow::setupGameGrid() { hostileItem->setX(j * gridSize_); hostileItem->setY(i * gridSize_); break; - case 4: // hostile + case 4: // coin coinItem = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); coinItem->setX(j * gridSize_); coinItem->setY(i * gridSize_); @@ -301,10 +291,8 @@ void MainWindow::setupGameGrid() { } } - // Установите размер сцены view->setSceneRect(0, 0, cols_ * gridSize_, rows_ * gridSize_); - // Перерисовать сцену view->update(); } @@ -314,11 +302,28 @@ void MainWindow::moveHostile() qDebug() << "No hostiles found."; return; } + std::vector> matrix; + for (int i = 0; i < rows_; ++i) { + std::vector row; + for (int j = 0; j < cols_; ++j) { + row.push_back(gameGrid_[i][j]); + } + matrix.push_back(row); + } + + for (const auto& row : matrix) { + for (const auto& element : row) { + std::cout << element << " "; + } + std::cout << std::endl; + } + std::vector direction; Point playerPoint(player_.getX(), player_.getY()); Point hostilePosition(0,0); for (Hostile& currentHostile : hostiles_) { + currentHostile.setMatrix(matrix); direction = currentHostile.getPath(playerPoint); if(direction.empty()) { diff --git a/player.cpp b/player.cpp index 1e1762b..695e0e6 100644 --- a/player.cpp +++ b/player.cpp @@ -1,10 +1,8 @@ -// player.cpp + #include "player.h" -// Реализация конструктора по умолчанию Player::Player() : x_(0), y_(0) {} -// Геттеры и сеттеры int Player::getX() const { return x_; } diff --git a/player.h b/player.h index 0586fc5..354c428 100644 --- a/player.h +++ b/player.h @@ -8,7 +8,7 @@ class Player { int y_; // Координата y public: - // Конструктор по умолчанию + Player(); int getX() const; diff --git a/redactor.cpp b/redactor.cpp index 6335d06..f84056d 100644 --- a/redactor.cpp +++ b/redactor.cpp @@ -105,13 +105,11 @@ void Redactor::dragItem() { } void Redactor::setupGameGrid() { - // Очистите сцену перед обновлением scene->clear(); QGraphicsPixmapItem* puckmanItem; QGraphicsPixmapItem* hostileItem; QGraphicsPixmapItem* coinItem; - // Заполните сцену значениями из игровой сетки for (int i = 0; i < rows_; ++i) { for (int j = 0; j < cols_; ++j) { switch (gameGrid_[i][j]) { @@ -161,10 +159,8 @@ void Redactor::setupGameGrid() { coinItem_->setY(8 * gridSize_); qDebug() << "coinItem Coordinates: (" << coinItem_->x() << ", " << coinItem_->y() << ")"; - // Установите размер сцены view->setSceneRect(0, 0, cols_ * gridSize_, rows_ * gridSize_); - // Перерисовать сцену view->update(); } From c858500c9523bad7a55f8cdf1b33e3f0a26d5184 Mon Sep 17 00:00:00 2001 From: KloopRE <100780612+KloopRE@users.noreply.github.com> Date: Sun, 17 Dec 2023 00:19:52 +0300 Subject: [PATCH 6/8] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Простите, можно мне пожалуйста не делать collidingItems, просто у меня уже прописана вся логика и мне придется её переписывать, я невнимательно читал задание : ( . Извините! --- Pacman.pro | 2 + customgraphicsview.cpp | 62 ++++++-- customgraphicsview.h | 16 ++- gameelement.cpp | 8 ++ gameelement.h | 22 +++ hostile.cpp | 144 +++++++++++-------- hostile.h | 33 ++++- mainwindow.cpp | 317 +++++++++++++++++++++++------------------ mainwindow.h | 24 ++-- player.cpp | 13 +- player.h | 10 +- redactor.cpp | 240 ++++++++++++++++++------------- redactor.h | 31 ++-- startgame.cpp | 4 +- startgame.h | 10 +- 15 files changed, 572 insertions(+), 364 deletions(-) create mode 100644 gameelement.cpp create mode 100644 gameelement.h diff --git a/Pacman.pro b/Pacman.pro index 49d2731..6802136 100644 --- a/Pacman.pro +++ b/Pacman.pro @@ -10,6 +10,7 @@ CONFIG += c++17 SOURCES += \ customgraphicsview.cpp \ + gameelement.cpp \ hostile.cpp \ main.cpp \ mainwindow.cpp \ @@ -19,6 +20,7 @@ SOURCES += \ HEADERS += \ customgraphicsview.h \ + gameelement.h \ hostile.h \ mainwindow.h \ player.h \ diff --git a/customgraphicsview.cpp b/customgraphicsview.cpp index df89206..1ac95e7 100644 --- a/customgraphicsview.cpp +++ b/customgraphicsview.cpp @@ -1,38 +1,74 @@ - #include "customgraphicsview.h" #include #include CustomGraphicsView::CustomGraphicsView(QGraphicsScene *scene, QWidget *parent, int gridSize) - : QGraphicsView(scene, parent), gridSize(gridSize) // Добавьте инициализацию gridSize + : QGraphicsView(scene, parent), cellSize_(gridSize) { setMouseTracking(true); } -void CustomGraphicsView::mouseMoveEvent(QMouseEvent *event) { - if (isdrawing) { +void CustomGraphicsView::mouseMoveEvent(QMouseEvent *event) +{ + if (isDrawing_) + { + int halfGridSize = cellSize_ / 2; QPoint localMousePos = event->pos(); - center = this->mapToScene(localMousePos); - center.setX(this->center.x() - gridSize / 2); - center.setY(this->center.y() - gridSize / 2); + center_ = this->mapToScene(localMousePos); + center_.setX(this->center_.x() - halfGridSize); + center_.setY(this->center_.y() - halfGridSize); update(); - qDebug() << "cursor Coordinates: (" << center.x() << ", " << center.y() << ")"; + qDebug() << "cursor Coordinates: (" << center_.x() << ", " << center_.y() << ")"; } } -void CustomGraphicsView::mouseReleaseEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton && isdrawing) { - isdrawing = false; +void CustomGraphicsView::mouseReleaseEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton && isDrawing_) + { + isDrawing_ = false; setCursorStyle(); emit customMouseRelease(); } } -void CustomGraphicsView::setCursorStyle() { - if (isdrawing) { +void CustomGraphicsView::setCursorStyle() +{ + if (isDrawing_) + { setCursor(Qt::CrossCursor); } else { setCursor(Qt::ArrowCursor); } } + +int CustomGraphicsView::getCenterX() const +{ + return center_.x(); +} + +int CustomGraphicsView::getCenterY() const +{ + return center_.y(); +} + +void CustomGraphicsView::setCenterX(int newX) +{ + center_.setX(newX); +} + +void CustomGraphicsView::setCenterY(int newY) +{ + center_.setY(newY); +} + +void CustomGraphicsView::setCenter(QPointF newCenter) +{ + center_ = newCenter; +} + +void CustomGraphicsView::setDrawing(bool newDrawing) +{ + isDrawing_ = newDrawing; +} diff --git a/customgraphicsview.h b/customgraphicsview.h index 1db9e42..e052dc6 100644 --- a/customgraphicsview.h +++ b/customgraphicsview.h @@ -4,21 +4,29 @@ #include #include -class CustomGraphicsView : public QGraphicsView { +class CustomGraphicsView : public QGraphicsView +{ Q_OBJECT public: CustomGraphicsView(QGraphicsScene *scene, QWidget *parent = nullptr, int gridSize = 64); - QPointF center; - bool isdrawing = false; + void setCursorStyle(); + int getCenterX() const; + int getCenterY() const; + void setCenterX(int newX); + void setCenterY(int newY); + void setCenter(QPointF newCenter); + void setDrawing(bool newDrawing); protected: void mouseMoveEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; private: - int gridSize; + int cellSize_; + QPointF center_; + bool isDrawing_ = false; signals: void customMouseRelease(); diff --git a/gameelement.cpp b/gameelement.cpp new file mode 100644 index 0000000..1168235 --- /dev/null +++ b/gameelement.cpp @@ -0,0 +1,8 @@ +#include "gameelement.h" + +GameElement::GameElement(ElementType type) : elementType_(type) {} + +GameElement::ElementType GameElement::getType() const +{ + return elementType_; +} diff --git a/gameelement.h b/gameelement.h new file mode 100644 index 0000000..a3c5f6c --- /dev/null +++ b/gameelement.h @@ -0,0 +1,22 @@ +#ifndef GAMEELEMENT_H +#define GAMEELEMENT_H + +class GameElement { +public: + enum ElementType { + Empty = 0, + Wall = 1, + Puckman = 2, + Hostile = 3, + Coin = 4 + }; + + GameElement(ElementType type); + + ElementType getType() const; + +private: + ElementType elementType_; +}; + +#endif // GAMEELEMENT_H diff --git a/hostile.cpp b/hostile.cpp index 0cbc7fd..425f5c4 100644 --- a/hostile.cpp +++ b/hostile.cpp @@ -4,60 +4,54 @@ using namespace std; -Hostile::Hostile(std::vector>& inputMatrix) : position_(0, 0) { +Hostile::Hostile(std::vector>& inputMatrix) : position_(0, 0) +{} -} - -Hostile::Hostile() : position_(0, 0) { - -} - -struct Node { - Point point; - int distance; +Hostile::Hostile() : position_(0, 0) +{} - Node(Point _point, int _distance) : point(_point), distance(_distance) {} - - bool operator>(const Node& other) const { - return distance > other.distance; - } -}; - -bool Hostile::isValid(int x, int y) { +bool Hostile::isCellValidForMovement(int x, int y) +{ int rows = matrix_.size(); - int cols = matrix_[0].size(); - return x >= 0 && x < cols && y >= 0 && y < rows && matrix_[y][x] != 1 && matrix_[y][x] != 3; + int columns = matrix_[0].size(); + return x >= GameElement::Empty && x < columns && y >= GameElement::Empty && y < rows && matrix_[y][x] != GameElement::Wall && matrix_[y][x] != GameElement::Hostile; } -vector getMoveDirections(const Point& start, const Point& end) { +std::vector getMoveDirections(const Point& start, const Point& end) +{ int dx = end.x - start.x; int dy = end.y - start.y; - vector directions; + std::vector directions; - if (dx > 0) { - directions.push_back('R'); // Вправо - } else if (dx < 0) { - directions.push_back('L'); // Влево + if (dx > 0) + { + directions.push_back("Right"); + } else if (dx < 0) + { + directions.push_back("Left"); } - if (dy > 0) { - directions.push_back('D'); // Вниз - } else if (dy < 0) { - directions.push_back('U'); // Вверх + if (dy > 0) + { + directions.push_back("Down"); + } else if (dy < 0) + { + directions.push_back("Up"); } return directions; } -vector Hostile::getPath(const Point& end) { +std::vector Hostile::getPath(const Point& end) +{ int rows = matrix_.size(); - int cols = matrix_[0].size(); + int columns = matrix_[0].size(); - vector directions; + std::vector directions; - vector> distance(rows, vector(cols, INT_MAX)); - vector> path(rows, vector(cols, Point(-1, -1))); + vector> distance(rows, vector(columns, INT_MAX)); + vector> path(rows, vector(columns, Point(-1, -1))); priority_queue, greater> pq; pq.push(Node(position_, 0)); @@ -66,34 +60,42 @@ vector Hostile::getPath(const Point& end) { int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; - while (!pq.empty()) { + while (!pq.empty()) + { Node current = pq.top(); pq.pop(); - if (current.point.x == end.x && current.point.y == end.y) { + if (current.point.x == end.x && current.point.y == end.y) + { vector pathPoints; Point currentPoint = end; - while (!(currentPoint.x == position_.x && currentPoint.y == position_.y)) { + while (!(currentPoint.x == position_.x && currentPoint.y == position_.y)) + { pathPoints.push_back(currentPoint); currentPoint = path[currentPoint.y][currentPoint.x]; } reverse(pathPoints.begin(), pathPoints.end()); - for (const Point& point : pathPoints) { + for (const Point& point : pathPoints) + { int dx = point.x - currentPoint.x; int dy = point.y - currentPoint.y; - if (dx == -1) { - directions.push_back('L'); - } else if (dx == 1) { - directions.push_back('R'); - } else if (dy == -1) { - directions.push_back('U'); - } else if (dy == 1) { - directions.push_back('D'); + if (dx == -1) + { + directions.push_back("Left"); + } else if (dx == 1) + { + directions.push_back("Right"); + } else if (dy == -1) + { + directions.push_back("Up"); + } else if (dy == 1) + { + directions.push_back("Down"); } currentPoint = point; @@ -103,14 +105,20 @@ vector Hostile::getPath(const Point& end) { return directions; } - for (int i = 0; i < 4; ++i) { + int step_weight = 1; + static const int numDirections = 4; + + for (int i = 0; i < numDirections; ++i) + { int nextX = current.point.x + dx[i]; int nextY = current.point.y + dy[i]; - if (isValid(nextX, nextY)) { - int newDistance = current.distance + 1; // Вес каждого шага равен 1 + if (isCellValidForMovement(nextX, nextY)) + { + int newDistance = current.distance + step_weight; - if (newDistance < distance[nextY][nextX]) { + if (newDistance < distance[nextY][nextX]) + { distance[nextY][nextX] = newDistance; path[nextY][nextX] = current.point; pq.push(Node(Point(nextX, nextY), newDistance)); @@ -119,7 +127,7 @@ vector Hostile::getPath(const Point& end) { } } - return vector(); + return vector(); } void Hostile::setPosition(Point& pos) @@ -127,9 +135,9 @@ void Hostile::setPosition(Point& pos) position_ = pos; } -void Hostile::setMatrix(std::vector > &inputMatrix) +void Hostile::setMatrix(std::vector > &matrix) { - matrix_ = inputMatrix; + matrix_ = matrix; } Point Hostile::getPosition() @@ -137,9 +145,11 @@ Point Hostile::getPosition() return position_; } -int Primer() { +int Hostile::Primer() +{ - vector> inputMatrix = { + vector> inputMatrix = + { {0, 0, 0, 0, 0}, {0, 1, 0, 1, 0}, {0, 1, 0, 0, 1}, @@ -147,19 +157,21 @@ int Primer() { {1, 0, 0, 0, 0} }; - Hostile hostileObject(inputMatrix); + Hostile hostile(inputMatrix); Point start(4, 0); Point end(0, 3); - hostileObject.setPosition(start); - vector pathDirections = hostileObject.getPath(end); + hostile.setPosition(start); + vector pathDirections = hostile.getPath(end); - if (pathDirections.empty()) { + if (pathDirections.empty()) + { cout << "No path found." << endl; } else { cout << "Shortest Path Directions: "; - for (char direction : pathDirections) { + for (string direction : pathDirections) + { cout << direction << " "; } cout << endl; @@ -167,3 +179,13 @@ int Primer() { return 0; } + +void Hostile::setPreviousElement(int element) +{ + previousElement_ = element; +} + +int Hostile::getPreviousElement() +{ + return previousElement_; +} diff --git a/hostile.h b/hostile.h index cd49911..22f066b 100644 --- a/hostile.h +++ b/hostile.h @@ -1,4 +1,3 @@ -// hostile.h #ifndef HOSTILE_H #define HOSTILE_H @@ -7,30 +6,50 @@ #include #include #include +#include -struct Point { +#include "gameelement.h" + +struct Point +{ int x, y; Point(int _x, int _y) : x(_x), y(_y) {} }; -class Hostile { - +class Hostile +{ private: + struct Node + { + Point point; + int distance; + + Node(Point _point, int _distance) : point(_point), distance(_distance) {} + + bool operator>(const Node& other) const { + return distance > other.distance; + } + }; + std::vector> matrix_; - bool isValid(int x, int y); + bool isCellValidForMovement(int x, int y); + Point position_; + int previousElement_ = 0; public: Hostile(); Hostile(std::vector>& inputMatrix); - std::vector getPath(const Point& end); + std::vector getPath(const Point& end); + int getPreviousElement(); + int Primer(); + void setPreviousElement(int element); void setPosition(Point& pos); void setMatrix(std::vector>& inputMatrix); Point getPosition(); - int temp = 0; }; #endif // HOSTILE_H diff --git a/mainwindow.cpp b/mainwindow.cpp index 8c2e817..9514a57 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -1,6 +1,5 @@ #include "mainwindow.h" #include "ui_mainwindow.h" - #include "hostile.h" #include "startgame.h" @@ -13,20 +12,22 @@ #include MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), ui(new Ui::MainWindow) { + : QMainWindow(parent), ui(new Ui::MainWindow) +{ ui->setupUi(this); setFocusPolicy(Qt::StrongFocus); + setFocus(); - scene = new QGraphicsScene(this); - view = new QGraphicsView(scene, this); + scene_ = new QGraphicsScene(this); + view_ = new QGraphicsView(scene_, this); - int uiWidth = (cols_+4) * gridSize_; - int uiHeight = (rows_+1) * gridSize_; + int uiWidth = (kColumns_+4) * cellSize_; + int uiHeight = (kRows_+1) * cellSize_; this->setFixedSize(uiWidth, uiHeight); - setCentralWidget(view); + setCentralWidget(view_); gameTimer_ = new QTimer(this); gameTimer_->start(250); @@ -36,10 +37,10 @@ MainWindow::MainWindow(QWidget *parent) hostileRunTimer_->start(1000); connect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); - - gameGrid_ = new int*[rows_]; - for (int i = 0; i < rows_; ++i) { - gameGrid_[i] = new int[cols_]; + gameGrid_ = new int*[kRows_]; + for (int i = 0; i < kRows_; ++i) + { + gameGrid_[i] = new int[kColumns_]; } generateRandomGameGrid(); @@ -47,22 +48,21 @@ MainWindow::MainWindow(QWidget *parent) } MainWindow::MainWindow(QWidget *parent, int** gameGrid) - : QMainWindow(parent), ui(new Ui::MainWindow) { - - + : QMainWindow(parent), ui(new Ui::MainWindow) +{ ui->setupUi(this); setFocusPolicy(Qt::StrongFocus); - hostiles_.reserve(cols_*rows_); + hostiles_.reserve(kColumns_*kRows_); - scene = new QGraphicsScene(this); - view = new QGraphicsView(scene, this); + scene_ = new QGraphicsScene(this); + view_ = new QGraphicsView(scene_, this); - int uiWidth = (cols_+4) * gridSize_; - int uiHeight = (rows_+1) * gridSize_; + int uiWidth = (kColumns_+4) * cellSize_; + int uiHeight = (kRows_+1) * cellSize_; this->setFixedSize(uiWidth, uiHeight); - setCentralWidget(view); + setCentralWidget(view_); gameTimer_ = new QTimer(this); gameTimer_->start(250); @@ -72,12 +72,15 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) hostileRunTimer_->start(1000); connect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); - if (gameGrid != nullptr) { - countCoins_ = 0; + if (gameGrid != nullptr) + { + counsCount_ = 0; std::vector> matrix; - for (int i = 0; i < rows_; ++i) { + for (int i = 0; i < kRows_; ++i) + { std::vector row; - for (int j = 0; j < cols_; ++j) { + for (int j = 0; j < kColumns_; ++j) + { row.push_back(gameGrid[i][j]); } matrix.push_back(row); @@ -91,11 +94,14 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) } Hostile newHostile; Point p(0, 0); - if (gameGrid != nullptr) { - gameGrid_ = new int*[rows_]; - for (int i = 0; i < rows_; ++i) { - gameGrid_[i] = new int[cols_]; - for (int j = 0; j < cols_; ++j) { + if (gameGrid != nullptr) + { + gameGrid_ = new int*[kRows_]; + for (int i = 0; i < kRows_; ++i) + { + gameGrid_[i] = new int[kColumns_]; + for (int j = 0; j < kColumns_; ++j) + { gameGrid_[i][j] = gameGrid[i][j]; if(gameGrid_[i][j] == 3) { @@ -107,7 +113,7 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) } if(gameGrid_[i][j] == 4) { - countCoins_++; + counsCount_++; } if(gameGrid_[i][j] == 2) { @@ -116,10 +122,13 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) } } } - } else { - gameGrid_ = new int*[rows_]; - for (int i = 0; i < rows_; ++i) { - gameGrid_[i] = new int[cols_]; + } + else + { + gameGrid_ = new int*[kRows_]; + for (int i = 0; i < kRows_; ++i) + { + gameGrid_[i] = new int[kColumns_]; } generateRandomGameGrid(); } @@ -127,7 +136,8 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) setupGameGrid(); } -void MainWindow::updateGameTime() { +void MainWindow::updateGameTime() +{ gameTime_ += 0.5; isKeyTime_ = true; setupGameGrid(); @@ -135,18 +145,21 @@ void MainWindow::updateGameTime() { { gameOver(false); } - if(countCoins_ == 0) + if(counsCount_ == 0) { gameOver(true); } } -void MainWindow::updateHostileRunTime() { +void MainWindow::updateHostileRunTime() +{ moveHostile(); } -MainWindow::~MainWindow(){ - for (int i = 0; i < rows_; ++i) { +MainWindow::~MainWindow() +{ + for (int i = 0; i < kRows_; ++i) + { delete[] gameGrid_[i]; } delete[] gameGrid_; @@ -167,7 +180,7 @@ void MainWindow::gameOver(bool isWin) else { std::string str1 = "Game Over, coins left: "; - std::string str2 = std::to_string(countCoins_); + std::string str2 = std::to_string(counsCount_); str1.append(str2); const char* charArray = str1.c_str(); QMessageBox::information(this, "False", charArray); @@ -176,26 +189,30 @@ void MainWindow::gameOver(bool isWin) handleGameOver(); } -void MainWindow::handleGameOver() { +void MainWindow::handleGameOver() +{ StartGame *SG = new StartGame(); SG->show(); } -void MainWindow::generateRandomGameGrid() { +void MainWindow::generateRandomGameGrid() +{ std::srand(std::time(0)); - for (int i = 0; i < rows_; ++i) { - for (int j = 0; j < cols_; ++j) { + for (int i = 0; i < kRows_; ++i) + { + for (int j = 0; j < kColumns_; ++j) + { gameGrid_[i][j] = 0; } } - int randomRow = std::rand() % rows_; - int randomCol = std::rand() % cols_; + int randomRow = std::rand() % kRows_; + int randomColumn = std::rand() % kColumns_; - gameGrid_[randomRow][randomCol] = 2; - player_.setX(randomCol); + gameGrid_[randomRow][randomColumn] = 2; + player_.setX(randomColumn); player_.setY(randomRow); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; @@ -208,162 +225,181 @@ void MainWindow::generateRandomGameGrid() { generateRandomElements(element,count); element = 4; - generateRandomElements(element,countCoins_); + generateRandomElements(element,counsCount_); } -void MainWindow::generateRandomElements(int element, int count) { +void MainWindow::generateRandomElements(int element, int count) +{ Hostile newHostile; Point p(0,0); - if(element == 3){ + if(element == 3) + { std::vector> matrix; - for (int i = 0; i < rows_; ++i) { + for (int i = 0; i < kRows_; ++i) + { std::vector row; - for (int j = 0; j < cols_; ++j) { + for (int j = 0; j < kColumns_; ++j) + { row.push_back(gameGrid_[i][j]); } matrix.push_back(row); } - for (const auto& row : matrix) { - for (const auto& element : row) { + for (const auto& row : matrix) + { + for (const auto& element : row) + { std::cout << element << " "; } std::cout << std::endl; } newHostile.setMatrix(matrix); } - for (int k = 0; k < count; ++k) { - int randomRow = std::rand() % rows_; - int randomCol = std::rand() % cols_; + for (int k = 0; k < count; ++k) + { + int randomRow = std::rand() % kRows_; + int randomColumn = std::rand() % kColumns_; - while (gameGrid_[randomRow][randomCol] != 0) { - randomRow = std::rand() % rows_; - randomCol = std::rand() % cols_; + while (gameGrid_[randomRow][randomColumn] != 0) + { + randomRow = std::rand() % kRows_; + randomColumn = std::rand() % kColumns_; } if(element == 3) { - p.x = randomCol; + p.x = randomColumn; p.y = randomRow; newHostile.setPosition(p); hostiles_.push_back(newHostile); } - gameGrid_[randomRow][randomCol] = element; + gameGrid_[randomRow][randomColumn] = element; } } -void MainWindow::setupGameGrid() { - scene->clear(); +void MainWindow::setupGameGrid() +{ + scene_->clear(); QGraphicsPixmapItem* puckmanItem; QGraphicsPixmapItem* hostileItem; QGraphicsPixmapItem* coinItem; - QGraphicsTextItem* coinsLabel = scene->addText("Coins: "+ QString::number(countCoins_)); + QGraphicsTextItem* coinsLabel = scene_->addText("Coins: "+ QString::number(counsCount_)); coinsLabel->setDefaultTextColor(Qt::black); QFont font = coinsLabel->font(); font.setPointSize(14); coinsLabel->setFont(font); - coinsLabel->setPos(cols_ * gridSize_ + 10, 10); - for (int i = 0; i < rows_; ++i) { - for (int j = 0; j < cols_; ++j) { - switch (gameGrid_[i][j]) { - case 0: // Empty space - scene->addRect(j * gridSize_, i * gridSize_, gridSize_, gridSize_, QPen(Qt::black), QBrush(Qt::white)); + coinsLabel->setPos(kColumns_ * cellSize_ + 10, 10); + for (int i = 0; i < kRows_; ++i) + { + for (int j = 0; j < kColumns_; ++j) + { + + switch (gameGrid_[i][j]) + { + case GameElement::Empty: + scene_->addRect(j * cellSize_, i * cellSize_, cellSize_, cellSize_, QPen(Qt::black), QBrush(Qt::white)); break; - case 1: // Wall - scene->addRect(j * gridSize_, i * gridSize_, gridSize_, gridSize_, QPen(Qt::black), QBrush(Qt::darkGray)); + case GameElement::Wall: + scene_->addRect(j * cellSize_, i * cellSize_, cellSize_, cellSize_, QPen(Qt::black), QBrush(Qt::darkGray)); break; - case 2: // player - puckmanItem = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(gridSize_, gridSize_)); - puckmanItem->setX(j * gridSize_); - puckmanItem->setY(i * gridSize_); + case GameElement::Puckman: + puckmanItem = scene_->addPixmap(QPixmap(":resource/puckman.png").scaled(cellSize_, cellSize_)); + puckmanItem->setX(j * cellSize_); + puckmanItem->setY(i * cellSize_); break; - case 3: // hostile - hostileItem = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(gridSize_, gridSize_)); - hostileItem->setX(j * gridSize_); - hostileItem->setY(i * gridSize_); + case GameElement::Hostile: + hostileItem = scene_->addPixmap(QPixmap(":resource/hostile.png").scaled(cellSize_, cellSize_)); + hostileItem->setX(j * cellSize_); + hostileItem->setY(i * cellSize_); break; - case 4: // coin - coinItem = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); - coinItem->setX(j * gridSize_); - coinItem->setY(i * gridSize_); + case GameElement::Coin: + coinItem = scene_->addPixmap(QPixmap(":resource/coin.png").scaled(cellSize_, cellSize_)); + coinItem->setX(j * cellSize_); + coinItem->setY(i * cellSize_); break; } } } - view->setSceneRect(0, 0, cols_ * gridSize_, rows_ * gridSize_); + view_->setSceneRect(0, 0, kColumns_ * cellSize_, kRows_ * cellSize_); - view->update(); + view_->update(); } void MainWindow::moveHostile() { - if (hostiles_.empty()) { + if (hostiles_.empty()) + { qDebug() << "No hostiles found."; return; } std::vector> matrix; - for (int i = 0; i < rows_; ++i) { + for (int i = 0; i < kRows_; ++i) + { std::vector row; - for (int j = 0; j < cols_; ++j) { + for (int j = 0; j < kColumns_; ++j) + { row.push_back(gameGrid_[i][j]); } matrix.push_back(row); } - for (const auto& row : matrix) { - for (const auto& element : row) { + for (const auto& row : matrix) + { + for (const auto& element : row) + { std::cout << element << " "; } std::cout << std::endl; } - std::vector direction; + std::vector direction; Point playerPoint(player_.getX(), player_.getY()); Point hostilePosition(0,0); - for (Hostile& currentHostile : hostiles_) { + for (Hostile& currentHostile : hostiles_) + { currentHostile.setMatrix(matrix); direction = currentHostile.getPath(playerPoint); if(direction.empty()) { return; } - if(direction[0] == 'L') + if(direction[0] == "Left") { hostilePosition = currentHostile.getPosition(); - gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; - currentHostile.temp = gameGrid_[hostilePosition.y][hostilePosition.x-1]; + gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); + currentHostile.setPreviousElement(gameGrid_[hostilePosition.y][hostilePosition.x-1]); hostilePosition.x = hostilePosition.x - 1; gameGrid_[hostilePosition.y][hostilePosition.x] = 3; currentHostile.setPosition(hostilePosition); } - if(direction[0] == 'R') + if(direction[0] == "Right") { hostilePosition = currentHostile.getPosition(); - gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; - currentHostile.temp = gameGrid_[hostilePosition.y][hostilePosition.x+1]; + gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); + currentHostile.setPreviousElement(gameGrid_[hostilePosition.y][hostilePosition.x+1]); hostilePosition.x = hostilePosition.x + 1; gameGrid_[hostilePosition.y][hostilePosition.x] = 3; currentHostile.setPosition(hostilePosition); } - if(direction[0] == 'U') + if(direction[0] == "Up") { hostilePosition = currentHostile.getPosition(); - gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; - currentHostile.temp = gameGrid_[hostilePosition.y-1][hostilePosition.x]; + gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); + currentHostile.setPreviousElement(gameGrid_[hostilePosition.y-1][hostilePosition.x]); hostilePosition.y = hostilePosition.y - 1; gameGrid_[hostilePosition.y][hostilePosition.x] = 3; qDebug() << "gameGrid_ Coordinates: (" << hostilePosition.x << ", " << hostilePosition.y << ")"; currentHostile.setPosition(hostilePosition); } - if(direction[0] == 'D') + if(direction[0] == "Down") { hostilePosition = currentHostile.getPosition(); - gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.temp; - currentHostile.temp = gameGrid_[hostilePosition.y+1][hostilePosition.x]; + gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); + currentHostile.setPreviousElement(gameGrid_[hostilePosition.y+1][hostilePosition.x]); hostilePosition.y = hostilePosition.y + 1; gameGrid_[hostilePosition.y][hostilePosition.x] = 3; qDebug() << "gameGrid_ Coordinates: (" << hostilePosition.x << ", " << hostilePosition.y << ")"; @@ -375,7 +411,8 @@ void MainWindow::moveHostile() void MainWindow::keyPressEvent(QKeyEvent *event) { if(isKeyTime_) { - switch (event->key()) { + switch (event->key()) + { case Qt::Key_W: movePlayerUp(); isKeyTime_ = false; @@ -399,64 +436,72 @@ void MainWindow::keyPressEvent(QKeyEvent *event) { } } -void MainWindow::movePlayerUp() { - if (player_.getY() > 0) { - if(gameGrid_[player_.getY()-1][player_.getX()] != 1) +void MainWindow::movePlayerUp() +{ + if (player_.getY() > 0) + { + if(gameGrid_[player_.getY()-1][player_.getX()] != GameElement::Wall) { - gameGrid_[player_.getY()][player_.getX()] = 0; - if(gameGrid_[player_.getY()-1][player_.getX()] == 4) + gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; + if(gameGrid_[player_.getY()-1][player_.getX()] == GameElement::Coin) { - countCoins_--; + counsCount_--; } - gameGrid_[player_.getY()-1][player_.getX()] = 2; + gameGrid_[player_.getY()-1][player_.getX()] = GameElement::Puckman; player_.setY(player_.getY() - 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } } } -void MainWindow::movePlayerDown() { - if (player_.getY()+1 < rows_) { - if(gameGrid_[player_.getY()+1][player_.getX()] != 1) +void MainWindow::movePlayerDown() +{ + if (player_.getY()+1 < kRows_) + { + if(gameGrid_[player_.getY()+1][player_.getX()] != GameElement::Wall) { - gameGrid_[player_.getY()][player_.getX()] = 0; - if(gameGrid_[player_.getY()+1][player_.getX()] == 4) + gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; + if(gameGrid_[player_.getY()+1][player_.getX()] == GameElement::Coin) { - countCoins_--; + counsCount_--; } - gameGrid_[player_.getY()+1][player_.getX()] = 2; + gameGrid_[player_.getY()+1][player_.getX()] = GameElement::Puckman; player_.setY(player_.getY() + 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } } } -void MainWindow::movePlayerLeft() { - if(gameGrid_[player_.getY()][player_.getX()-1] != 1) +void MainWindow::movePlayerLeft() +{ + if(gameGrid_[player_.getY()][player_.getX()-1] != GameElement::Wall) { - if (player_.getX() > 0) { - gameGrid_[player_.getY()][player_.getX()] = 0; - if(gameGrid_[player_.getY()][player_.getX()-1] == 4) + if (player_.getX() > 0) + { + gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; + if(gameGrid_[player_.getY()][player_.getX()-1] == GameElement::Coin) { - countCoins_--; + counsCount_--; } - gameGrid_[player_.getY()][player_.getX()-1] = 2; + gameGrid_[player_.getY()][player_.getX()-1] = GameElement::Puckman; player_.setX(player_.getX() - 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } } } -void MainWindow::movePlayerRight() { - if (player_.getX()+1 < cols_) { - if(gameGrid_[player_.getY()][player_.getX()+1] != 1) +void MainWindow::movePlayerRight() +{ + if (player_.getX()+1 < kColumns_) + { + if(gameGrid_[player_.getY()][player_.getX()+1] != GameElement::Wall) { - gameGrid_[player_.getY()][player_.getX()] = 0; - if(gameGrid_[player_.getY()][player_.getX()+1] == 4) + gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; + if(gameGrid_[player_.getY()][player_.getX()+1] == GameElement::Coin) { - countCoins_--; + counsCount_--; } - gameGrid_[player_.getY()][player_.getX()+1] = 2; + gameGrid_[player_.getY()][player_.getX()+1] = GameElement::Puckman; player_.setX(player_.getX() + 1); qDebug() << "Player Coordinates: (" << player_.getY() << ", " << player_.getX() << ")"; } diff --git a/mainwindow.h b/mainwindow.h index cafa1f5..6013ab7 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -3,6 +3,7 @@ #include "player.h" #include "hostile.h" +#include "gameelement.h" #include #include @@ -14,8 +15,9 @@ QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE -class MainWindow : public QMainWindow { -Q_OBJECT +class MainWindow : public QMainWindow +{ + Q_OBJECT public: MainWindow(QWidget *parent = nullptr); @@ -23,7 +25,7 @@ Q_OBJECT ~MainWindow(); void generateRandomGameGrid(); - void setupGameGrid(); // Объявление функции setupGameGrid + void setupGameGrid(); protected: void keyPressEvent(QKeyEvent *event) override; @@ -31,23 +33,24 @@ Q_OBJECT private: Ui::MainWindow *ui; QTimer* gameTimer_; - float gameTime_; QTimer* hostileRunTimer_; - const int rows_ = 10; - const int cols_ = 10; + float gameTime_; + const int kRows_ = 10; + const int kColumns_ = 10; int **gameGrid_; - int gridSize_ = 64; - int countCoins_ = 5; + int cellSize_ = 64; + int counsCount_ = 5; bool isKeyTime_ = true; Player player_; + QGraphicsScene *scene_; + QGraphicsView *view_; std::vector hostiles_; + void movePlayerUp(); void movePlayerDown(); void movePlayerLeft(); void movePlayerRight(); void moveHostile(); - QGraphicsScene *scene; - QGraphicsView *view; void generateRandomElements(int element, int count); void updateCoinsCount(); void gameOver(bool isWin); @@ -56,7 +59,6 @@ Q_OBJECT private slots: void updateGameTime(); void updateHostileRunTime(); - void handleKeyRepeat(); }; diff --git a/player.cpp b/player.cpp index 695e0e6..ac2be04 100644 --- a/player.cpp +++ b/player.cpp @@ -1,20 +1,23 @@ - #include "player.h" Player::Player() : x_(0), y_(0) {} -int Player::getX() const { +int Player::getX() const +{ return x_; } -int Player::getY() const { +int Player::getY() const +{ return y_; } -void Player::setX(int newX) { +void Player::setX(int newX) +{ x_ = newX; } -void Player::setY(int newY) { +void Player::setY(int newY) +{ y_ = newY; } diff --git a/player.h b/player.h index 354c428..274a9b2 100644 --- a/player.h +++ b/player.h @@ -1,20 +1,18 @@ -// player.h #ifndef PLAYER_H #define PLAYER_H class Player { -private: - int x_; // Координата x - int y_; // Координата y - public: - Player(); int getX() const; int getY() const; void setX(int newX); void setY(int newY); + +private: + int x_; + int y_; }; #endif // PLAYER_H diff --git a/redactor.cpp b/redactor.cpp index f84056d..336e116 100644 --- a/redactor.cpp +++ b/redactor.cpp @@ -1,6 +1,7 @@ #include "redactor.h" #include "ui_redactor.h" #include "mainwindow.h" +#include "startgame.h" #include #include @@ -18,31 +19,34 @@ Redactor::Redactor(QWidget *parent) : setFocusPolicy(Qt::StrongFocus); scene = new QGraphicsScene(this); - view = new CustomGraphicsView(scene, this, gridSize_); + view = new CustomGraphicsView(scene, this, cellSize_); view->setMouseTracking(true); view->hasMouseTracking(); connect(view, &CustomGraphicsView::customMouseRelease, this, &Redactor::handleCustomMouseRelease); - int uiWidth = (cols_+6) * gridSize_; - int uiHeight = (rows_+1) * gridSize_; + int uiWidth = (kColumns_+6) * cellSize_; + int uiHeight = (kRows_+1) * cellSize_; this->setFixedSize(uiWidth, uiHeight); setCentralWidget(view); - gameGrid_ = new int*[rows_]; - for (int i = 0; i < rows_; ++i) { - gameGrid_[i] = new int[cols_]; + gameGrid_ = new int*[kRows_]; + for (int i = 0; i < kRows_; ++i) + { + gameGrid_[i] = new int[kColumns_]; } - for (int i = 0; i < rows_; ++i) { - for (int j = 0; j < cols_; ++j) { + for (int i = 0; i < kRows_; ++i) + { + for (int j = 0; j < kColumns_; ++j) + { gameGrid_[i][j] = 0; } } myButton = new QPushButton("Начать игру", this); - myButton->setGeometry(10, 10, 100, 30); // Установите положение и размер кнопки + myButton->setGeometry(10, 10, 100, 30); connect(myButton, &QPushButton::clicked, this, &Redactor::handleButtonClick); setupGameGrid(); @@ -56,186 +60,210 @@ void Redactor::exitRedaction() openGame(); } -void Redactor::openGame() { - MainWindow *SG = new MainWindow(nullptr, gameGrid_); - SG->show(); +void Redactor::openGame() +{ + MainWindow *startGame = new MainWindow(nullptr, gameGrid_); + startGame->show(); } -void Redactor::handleButtonClick() { +void Redactor::handleButtonClick() +{ + if(counsCount_ <= 0) + { + std::string str1 = "couns count < 0"; + const char* charArray = str1.c_str(); + QMessageBox::information(this, "False", charArray); + return; + } exitRedaction(); } Redactor::~Redactor() { - for (int i = 0; i < rows_; ++i) { + for (int i = 0; i < kRows_; ++i) + { delete[] gameGrid_[i]; } delete[] gameGrid_; delete ui; } -void Redactor::paintEvent(QPaintEvent *event) { +void Redactor::paintEvent(QPaintEvent *event) +{ dragItem(); } -void Redactor::dragItem() { - if (dragItem_ != nullptr) { +void Redactor::dragItem() +{ + if (dragItem_ != nullptr) + { scene->removeItem(dragItem_); delete dragItem_; } dragItem_ = new QGraphicsPixmapItem(); - if(dragElement_ == 1) + if(dragElement_ == GameElement::Wall) { - dragItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(gridSize_, gridSize_)); + dragItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(cellSize_, cellSize_)); } - if(dragElement_ == 2) + if(dragElement_ == GameElement::Puckman) { - dragItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(gridSize_, gridSize_)); + dragItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(cellSize_, cellSize_)); } - if(dragElement_ == 3) + if(dragElement_ == GameElement::Hostile) { - dragItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(gridSize_, gridSize_)); + dragItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(cellSize_, cellSize_)); } - if(dragElement_ == 4) + if(dragElement_ == GameElement::Coin) { - dragItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); + dragItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(cellSize_, cellSize_)); } - dragItem_->setX(view->center.x()); - dragItem_->setY(view->center.y()); + dragItem_->setX(view->getCenterX()); + dragItem_->setY(view->getCenterY()); } -void Redactor::setupGameGrid() { +void Redactor::setupGameGrid() +{ scene->clear(); QGraphicsPixmapItem* puckmanItem; QGraphicsPixmapItem* hostileItem; QGraphicsPixmapItem* coinItem; - for (int i = 0; i < rows_; ++i) { - for (int j = 0; j < cols_; ++j) { - switch (gameGrid_[i][j]) { - case 0: // Empty space - scene->addRect(j * gridSize_, i * gridSize_, gridSize_, gridSize_, QPen(Qt::black), QBrush(Qt::white)); + for (int i = 0; i < kRows_; ++i) + { + for (int j = 0; j < kColumns_; ++j) + { + + switch (gameGrid_[i][j]) + { + case GameElement::Empty: + scene->addRect(j * cellSize_, i * cellSize_, cellSize_, cellSize_, QPen(Qt::black), QBrush(Qt::white)); break; - case 1: // Wall - scene->addRect(j * gridSize_, i * gridSize_, gridSize_, gridSize_, QPen(Qt::black), QBrush(Qt::darkGray)); + case GameElement::Wall: + scene->addRect(j * cellSize_, i * cellSize_, cellSize_, cellSize_, QPen(Qt::black), QBrush(Qt::darkGray)); break; - case 2: // player - puckmanItem = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(gridSize_, gridSize_)); - puckmanItem->setX(j * gridSize_); - puckmanItem->setY(i * gridSize_); + case GameElement::Puckman: + puckmanItem = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(cellSize_, cellSize_)); + puckmanItem->setX(j * cellSize_); + puckmanItem->setY(i * cellSize_); break; - case 3: // hostile - hostileItem = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(gridSize_, gridSize_)); - hostileItem->setX(j * gridSize_); - hostileItem->setY(i * gridSize_); + case GameElement::Hostile: + hostileItem = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(cellSize_, cellSize_)); + hostileItem->setX(j * cellSize_); + hostileItem->setY(i * cellSize_); break; - case 4: // hostile - coinItem = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); - coinItem->setX(j * gridSize_); - coinItem->setY(i * gridSize_); + case GameElement::Coin: + coinItem = scene->addPixmap(QPixmap(":resource/coin.png").scaled(cellSize_, cellSize_)); + coinItem->setX(j * cellSize_); + coinItem->setY(i * cellSize_); break; } } } int RETURN = 2; - wallItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(gridSize_, gridSize_)); - wallItem_->setX((cols_+RETURN) * gridSize_); - wallItem_->setY(1 * gridSize_); + wallItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(cellSize_, cellSize_)); + wallItem_->setX((kColumns_+RETURN) * cellSize_); + wallItem_->setY(1 * cellSize_); qDebug() << "wallItem Coordinates: (" << wallItem_->x() << ", " << wallItem_->y() << ")"; - puckmanItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(gridSize_, gridSize_)); - puckmanItem_->setX((cols_+RETURN) * gridSize_); - puckmanItem_->setY(4 * gridSize_); + puckmanItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(cellSize_, cellSize_)); + puckmanItem_->setX((kColumns_+RETURN) * cellSize_); + puckmanItem_->setY(4 * cellSize_); qDebug() << "puckmanItem Coordinates: (" << puckmanItem_->x() << ", " << puckmanItem_->y() << ")"; - hostileItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(gridSize_, gridSize_)); - hostileItem_->setX((cols_+RETURN) * gridSize_); - hostileItem_->setY(6 * gridSize_); + hostileItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(cellSize_, cellSize_)); + hostileItem_->setX((kColumns_+RETURN) * cellSize_); + hostileItem_->setY(6 * cellSize_); qDebug() << "hostileItem Coordinates: (" << hostileItem_->x() << ", " << hostileItem_->y() << ")"; - coinItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(gridSize_, gridSize_)); - coinItem_->setX((cols_+RETURN) * gridSize_); - coinItem_->setY(8 * gridSize_); + coinItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(cellSize_, cellSize_)); + coinItem_->setX((kColumns_+RETURN) * cellSize_); + coinItem_->setY(8 * cellSize_); qDebug() << "coinItem Coordinates: (" << coinItem_->x() << ", " << coinItem_->y() << ")"; - view->setSceneRect(0, 0, cols_ * gridSize_, rows_ * gridSize_); + view->setSceneRect(0, 0, kColumns_ * cellSize_, kRows_ * cellSize_); view->update(); } -QPoint Redactor::getGridPoint() { - QPoint a(-1, -1); - for (int i = 0; i < rows_; ++i) { - for (int j = 0; j < cols_; ++j) { - if(view->center.x() > i*gridSize_-gridSize_/2 && view->center.x() < i*gridSize_+gridSize_/2) +QPoint Redactor::getGridPoint() +{ + QPoint coordinateElementGrid(-1, -1); + int halfGridSize = cellSize_ / 2; + for (int i = 0; i < kRows_; ++i) + { + for (int j = 0; j < kColumns_; ++j) + { + if(view->getCenterX()> i*cellSize_-halfGridSize && view->getCenterX()< i*cellSize_+halfGridSize) { - if(view->center.y() > j*gridSize_-gridSize_/2 && view->center.y() < j*gridSize_+gridSize_/2) + if(view->getCenterY() > j*cellSize_-halfGridSize && view->getCenterY() < j*cellSize_+halfGridSize) { - a.setX(i); - a.setY(j); - qDebug() << "getGridPoint Coordinates: (" << a.x() << ", " << a.y() << ")"; - return(a); + coordinateElementGrid.setX(i); + coordinateElementGrid.setY(j); + qDebug() << "getGridPoint Coordinates: (" << coordinateElementGrid.x() << ", " << coordinateElementGrid.y() << ")"; + return(coordinateElementGrid); } } } } - qDebug() << "getGridPoint Coordinates: (" << a.x() << ", " << a.y() << ")"; - return a; - + qDebug() << "getGridPoint Coordinates: (" << coordinateElementGrid.x() << ", " << coordinateElementGrid.y() << ")"; + return coordinateElementGrid; } -int Redactor::getElement() { - QGraphicsItem* item = scene->itemAt(view->center.x(), view->center.y(), QTransform()); - if(view->center.x() < wallItem_->x()+gridSize_ && view->center.x() > wallItem_->x()-gridSize_) +int Redactor::getElement() +{ + QGraphicsItem* item = scene->itemAt(view->getCenterX(), view->getCenterY(), QTransform()); + if(view->getCenterX()< wallItem_->x()+cellSize_ && view->getCenterX()> wallItem_->x()-cellSize_) { - if(view->center.y() < wallItem_->y()+gridSize_ && view->center.y() > wallItem_->y()-gridSize_) + if(view->getCenterY() < wallItem_->y()+cellSize_ && view->getCenterY() > wallItem_->y()-cellSize_) { qDebug() << "you drag item: (" << item << ")"; - return 1; + return GameElement::Wall; } } - if(view->center.x() < puckmanItem_->x()+gridSize_ && view->center.x() > puckmanItem_->x()-gridSize_) + if(view->getCenterX()< puckmanItem_->x()+cellSize_ && view->getCenterX()> puckmanItem_->x()-cellSize_) { - if(view->center.y() < puckmanItem_->y()+gridSize_ && view->center.y() > puckmanItem_->y()-gridSize_) + if(view->getCenterY() < puckmanItem_->y()+cellSize_ && view->getCenterY() > puckmanItem_->y()-cellSize_) { if(isStatePacmanElement_ == false) { qDebug() << "you drag item: (" << item << ")"; - return 2; + return GameElement::Puckman; } } } - if(view->center.x() < hostileItem_->x()+gridSize_ && view->center.x() > hostileItem_->x()-gridSize_) + if(view->getCenterX()< hostileItem_->x()+cellSize_ && view->getCenterX()> hostileItem_->x()-cellSize_) { - if(view->center.y() < hostileItem_->y()+gridSize_ && view->center.y() > hostileItem_->y()-gridSize_) + if(view->getCenterY() < hostileItem_->y()+cellSize_ && view->getCenterY() > hostileItem_->y()-cellSize_) { qDebug() << "you drag item: (" << item << ")"; - return 3; + return GameElement::Hostile; } } - if(view->center.x() < coinItem_->x()+gridSize_ && view->center.x() > coinItem_->x()-gridSize_) + if(view->getCenterX()< coinItem_->x()+cellSize_ && view->getCenterX()> coinItem_->x()-cellSize_) { - if(view->center.y() < coinItem_->y()+gridSize_ && view->center.y() > coinItem_->y()-gridSize_) + if(view->getCenterY() < coinItem_->y()+cellSize_ && view->getCenterY() > coinItem_->y()-cellSize_) { qDebug() << "you drag item: (" << item << ")"; - return 4; + return GameElement::Coin; } } qDebug() << "you drag item: (" << item << ")"; return 0; } -void Redactor::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) { +void Redactor::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) + { dragItem_ = new QGraphicsPixmapItem(); - view->isdrawing = true; - QPoint localMousePos = event->pos(); // Получаем локальные координаты мыши - view->center = view->mapToScene(localMousePos); - view->center.setX(view->center.x()); - view->center.setY(view->center.y()); + view->setDrawing(true); + QPoint localMousePos = event->pos(); + view->setCenter(view->mapToScene(localMousePos)); + view->setCenterX(view->getCenterX()); + view->setCenterY(view->getCenterY()); view->setCursorStyle(); - qDebug() << "cursor Coordinates: (" << view->center.x() << ", " << view->center.y() << ")"; + qDebug() << "cursor Coordinates: (" << view->getCenterX()<< ", " << view->getCenterY() << ")"; dragElement_ = getElement(); qDebug() << "you drag item: (" << getElement() << ")"; @@ -244,20 +272,30 @@ void Redactor::mousePressEvent(QMouseEvent *event) { } -void Redactor::handleCustomMouseRelease() { +void Redactor::handleCustomMouseRelease() +{ dragItem_ = new QGraphicsPixmapItem(); - QPoint a = getGridPoint(); - if(a.x() > 0 || a.y() > 0) + QPoint cell = getGridPoint(); + if(cell.x() > 0 || cell.y() > 0) { - if (gameGrid_[a.y()][a.x()] == 2) + if (gameGrid_[cell.y()][cell.x()] == GameElement::Puckman) { isStatePacmanElement_ = false; } - gameGrid_[a.y()][a.x()] = dragElement_; - if(dragElement_ == 2) + if (gameGrid_[cell.y()][cell.x()] == GameElement::Coin) + { + counsCount_--; + } + gameGrid_[cell.y()][cell.x()] = dragElement_; + if(dragElement_ == GameElement::Puckman) { isStatePacmanElement_ = true; } + if(dragElement_ == GameElement::Coin) + { + counsCount_++; + qDebug() << "counsCount = (" << counsCount_ << ")"; + } } update(); setupGameGrid(); diff --git a/redactor.h b/redactor.h index c2d8117..6f5ffa8 100644 --- a/redactor.h +++ b/redactor.h @@ -8,11 +8,13 @@ #include "mainwindow.h" #include "customgraphicsview.h" -namespace Ui { -class Redactor; +namespace Ui +{ + class Redactor; } -class Redactor : public QMainWindow { +class Redactor : public QMainWindow +{ Q_OBJECT public: @@ -27,33 +29,34 @@ class Redactor : public QMainWindow { Ui::Redactor *ui; MainWindow *MW; int **gameGrid_; - const int rows_ = 10; - const int cols_ = 10; - int gridSize_ = 64; - void setupGameGrid(); + const int kRows_ = 10; + const int kColumns_ = 10; + int cellSize_ = 64; + int counsCount_ = 0; QGraphicsScene *scene; CustomGraphicsView *view; - bool isdrawing_ = false; + bool isDrawing_ = false; QPointF center_; int lineWidth_; QColor lineColor_; - void drawItems(QPainter *painter, const QPoint ¢er); - int getElement(); + int dragElement_; QGraphicsPixmapItem* wallItem_; QGraphicsPixmapItem* puckmanItem_; QGraphicsPixmapItem* hostileItem_; QGraphicsPixmapItem* coinItem_; QGraphicsPixmapItem* dragItem_ = nullptr; + bool isStatePacmanElement_ = false; + QPushButton *myButton; + + void setupGameGrid(); + void drawItems(QPainter *painter, const QPoint ¢er); QPoint getGridPoint(); - int dragElement_; void dragItem(); void handleCustomMouseRelease(); - bool isStatePacmanElement_ = false; - QPushButton *myButton; void handleButtonClick(); void openGame(); void exitRedaction(); - + int getElement(); }; #endif // REDACTOR_H diff --git a/startgame.cpp b/startgame.cpp index 9d4ae97..65cca1a 100644 --- a/startgame.cpp +++ b/startgame.cpp @@ -17,8 +17,8 @@ StartGame::~StartGame() } void StartGame::loadUI(){ - ui->play_button->setFont(QFont(default_font_family_, font_size_)); - ui->redactor_button->setFont(QFont(default_font_family_, font_size_)); + ui->play_button->setFont(QFont(kdefaultFontFamily_, kFontSize_)); + ui->redactor_button->setFont(QFont(kdefaultFontFamily_, kFontSize_)); } void StartGame::on_play_button_clicked() diff --git a/startgame.h b/startgame.h index 5bae53a..9973c2e 100644 --- a/startgame.h +++ b/startgame.h @@ -3,8 +3,9 @@ #include -namespace Ui { -class StartGame; +namespace Ui +{ + class StartGame; } class StartGame : public QWidget @@ -21,8 +22,9 @@ private slots: private: Ui::StartGame *ui; - static const int font_size_ = 15; - const QString default_font_family_ = "Default"; + static const int kFontSize_ = 15; + const QString kdefaultFontFamily_ = "Default"; + void loadUI(); }; From bdb0d053b41746cd5bf9946a59117df94ed613d8 Mon Sep 17 00:00:00 2001 From: KloopRE <100780612+KloopRE@users.noreply.github.com> Date: Sun, 17 Dec 2023 16:50:22 +0300 Subject: [PATCH 7/8] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Pacman.pro | 2 ++ customgraphicsview.cpp | 8 +++-- customgraphicsview.h | 2 +- directions.cpp | 24 +++++++++++++++ directions.h | 24 +++++++++++++++ hostile.cpp | 68 ++++++++++++++++++++++-------------------- hostile.h | 24 ++++++++------- mainwindow.cpp | 54 ++++++++++++++++----------------- redactor.cpp | 67 ++++++++++++++++++++++------------------- 9 files changed, 168 insertions(+), 105 deletions(-) create mode 100644 directions.cpp create mode 100644 directions.h diff --git a/Pacman.pro b/Pacman.pro index 6802136..be9dd46 100644 --- a/Pacman.pro +++ b/Pacman.pro @@ -10,6 +10,7 @@ CONFIG += c++17 SOURCES += \ customgraphicsview.cpp \ + directions.cpp \ gameelement.cpp \ hostile.cpp \ main.cpp \ @@ -20,6 +21,7 @@ SOURCES += \ HEADERS += \ customgraphicsview.h \ + directions.h \ gameelement.h \ hostile.h \ mainwindow.h \ diff --git a/customgraphicsview.cpp b/customgraphicsview.cpp index 1ac95e7..b245c5c 100644 --- a/customgraphicsview.cpp +++ b/customgraphicsview.cpp @@ -38,7 +38,9 @@ void CustomGraphicsView::setCursorStyle() if (isDrawing_) { setCursor(Qt::CrossCursor); - } else { + } + else + { setCursor(Qt::ArrowCursor); } } @@ -68,7 +70,7 @@ void CustomGraphicsView::setCenter(QPointF newCenter) center_ = newCenter; } -void CustomGraphicsView::setDrawing(bool newDrawing) +void CustomGraphicsView::setDrawing(bool isDrawing) { - isDrawing_ = newDrawing; + isDrawing_ = isDrawing; } diff --git a/customgraphicsview.h b/customgraphicsview.h index e052dc6..f10b512 100644 --- a/customgraphicsview.h +++ b/customgraphicsview.h @@ -16,7 +16,7 @@ class CustomGraphicsView : public QGraphicsView int getCenterY() const; void setCenterX(int newX); void setCenterY(int newY); - void setCenter(QPointF newCenter); + void setCenter(QPointF isDrawing); void setDrawing(bool newDrawing); protected: diff --git a/directions.cpp b/directions.cpp new file mode 100644 index 0000000..b703ecf --- /dev/null +++ b/directions.cpp @@ -0,0 +1,24 @@ +#include "directions.h" + +const std::string Directions::Left = "Left"; +const std::string Directions::Right = "Right"; +const std::string Directions::Up = "Up"; +const std::string Directions::Down = "Down"; + +Directions::Directions(const std::string& type) : directionsType_(type) {} + +std::string Directions::getType() const +{ + return directionsType_; +} + +std::ostream& operator<<(std::ostream& os, const Directions& direction) +{ + os << direction.getType(); + return os; +} + +bool operator==(const Directions& left, const Directions& right) +{ + return left.getType() == right.getType(); +} diff --git a/directions.h b/directions.h new file mode 100644 index 0000000..132bd15 --- /dev/null +++ b/directions.h @@ -0,0 +1,24 @@ +#ifndef DIRECTIONS_H +#define DIRECTIONS_H + +#include + +class Directions { +public: + static const std::string Left; + static const std::string Right; + static const std::string Up; + static const std::string Down; + + Directions(const std::string& type); + + std::string getType() const; + + friend std::ostream& operator<<(std::ostream& os, const Directions& direction); + friend bool operator==(const Directions& left, const Directions& right); + +private: + std::string directionsType_; +}; + +#endif // DIRECTIONS_H diff --git a/hostile.cpp b/hostile.cpp index 425f5c4..6247d4f 100644 --- a/hostile.cpp +++ b/hostile.cpp @@ -2,8 +2,6 @@ using namespace std; - - Hostile::Hostile(std::vector>& inputMatrix) : position_(0, 0) {} @@ -17,53 +15,54 @@ bool Hostile::isCellValidForMovement(int x, int y) return x >= GameElement::Empty && x < columns && y >= GameElement::Empty && y < rows && matrix_[y][x] != GameElement::Wall && matrix_[y][x] != GameElement::Hostile; } -std::vector getMoveDirections(const Point& start, const Point& end) +std::vector getMoveDirections(const Point& start, const Point& end) { int dx = end.x - start.x; int dy = end.y - start.y; - std::vector directions; + std::vector directions; if (dx > 0) { - directions.push_back("Right"); + directions.push_back(Directions(Directions::Right)); } else if (dx < 0) { - directions.push_back("Left"); + directions.push_back(Directions(Directions::Left)); } if (dy > 0) { - directions.push_back("Down"); - } else if (dy < 0) + directions.push_back(Directions(Directions::Down)); + } + else if (dy < 0) { - directions.push_back("Up"); + directions.push_back(Directions(Directions::Up)); } return directions; } -std::vector Hostile::getPath(const Point& end) +std::vector Hostile::getPath(const Point& end) { int rows = matrix_.size(); int columns = matrix_[0].size(); - std::vector directions; + std::vector directions; vector> distance(rows, vector(columns, INT_MAX)); vector> path(rows, vector(columns, Point(-1, -1))); - priority_queue, greater> pq; + priority_queue, greater> priorityQueue; - pq.push(Node(position_, 0)); + priorityQueue.push(Node(position_, 0)); distance[position_.y][position_.x] = 0; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; - while (!pq.empty()) + while (!priorityQueue.empty()) { - Node current = pq.top(); - pq.pop(); + Node current = priorityQueue.top(); + priorityQueue.pop(); if (current.point.x == end.x && current.point.y == end.y) { @@ -86,16 +85,19 @@ std::vector Hostile::getPath(const Point& end) if (dx == -1) { - directions.push_back("Left"); - } else if (dx == 1) + directions.push_back(Directions(Directions::Left)); + } + else if (dx == 1) { - directions.push_back("Right"); - } else if (dy == -1) + directions.push_back(Directions(Directions::Right)); + } + else if (dy == -1) { - directions.push_back("Up"); - } else if (dy == 1) + directions.push_back(Directions(Directions::Up)); + } + else if (dy == 1) { - directions.push_back("Down"); + directions.push_back(Directions(Directions::Down)); } currentPoint = point; @@ -105,29 +107,29 @@ std::vector Hostile::getPath(const Point& end) return directions; } - int step_weight = 1; - static const int numDirections = 4; + int stepWeight = 1; + const int kDirections = 4; - for (int i = 0; i < numDirections; ++i) + for (int i = 0; i < kDirections; ++i) { int nextX = current.point.x + dx[i]; int nextY = current.point.y + dy[i]; if (isCellValidForMovement(nextX, nextY)) { - int newDistance = current.distance + step_weight; + int newDistance = current.distance + stepWeight; if (newDistance < distance[nextY][nextX]) { distance[nextY][nextX] = newDistance; path[nextY][nextX] = current.point; - pq.push(Node(Point(nextX, nextY), newDistance)); + priorityQueue.push(Node(Point(nextX, nextY), newDistance)); } } } } - return vector(); + return std::vector(); } void Hostile::setPosition(Point& pos) @@ -163,14 +165,16 @@ int Hostile::Primer() Point end(0, 3); hostile.setPosition(start); - vector pathDirections = hostile.getPath(end); + std::vector pathDirections = hostile.getPath(end); if (pathDirections.empty()) { cout << "No path found." << endl; - } else { + } + else + { cout << "Shortest Path Directions: "; - for (string direction : pathDirections) + for (Directions direction : pathDirections) { cout << direction << " "; } diff --git a/hostile.h b/hostile.h index 22f066b..b7c92cb 100644 --- a/hostile.h +++ b/hostile.h @@ -8,6 +8,7 @@ #include #include +#include "directions.h" #include "gameelement.h" struct Point @@ -19,6 +20,18 @@ struct Point class Hostile { +public: + Hostile(); + Hostile(std::vector>& inputMatrix); + + std::vector getPath(const Point& end); + int getPreviousElement(); + int Primer(); + void setPreviousElement(int element); + void setPosition(Point& pos); + void setMatrix(std::vector>& inputMatrix); + Point getPosition(); + private: struct Node { @@ -39,17 +52,6 @@ class Hostile Point position_; int previousElement_ = 0; -public: - Hostile(); - Hostile(std::vector>& inputMatrix); - - std::vector getPath(const Point& end); - int getPreviousElement(); - int Primer(); - void setPreviousElement(int element); - void setPosition(Point& pos); - void setMatrix(std::vector>& inputMatrix); - Point getPosition(); }; #endif // HOSTILE_H diff --git a/mainwindow.cpp b/mainwindow.cpp index 9514a57..b43eb02 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -23,8 +23,8 @@ MainWindow::MainWindow(QWidget *parent) scene_ = new QGraphicsScene(this); view_ = new QGraphicsView(scene_, this); - int uiWidth = (kColumns_+4) * cellSize_; - int uiHeight = (kRows_+1) * cellSize_; + int uiWidth = (kColumns_ + 4) * cellSize_; + int uiHeight = (kRows_ + 1) * cellSize_; this->setFixedSize(uiWidth, uiHeight); setCentralWidget(view_); @@ -58,8 +58,8 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) scene_ = new QGraphicsScene(this); view_ = new QGraphicsView(scene_, this); - int uiWidth = (kColumns_+4) * cellSize_; - int uiHeight = (kRows_+1) * cellSize_; + int uiWidth = (kColumns_ + 4) * cellSize_; + int uiHeight = (kRows_ + 1) * cellSize_; this->setFixedSize(uiWidth, uiHeight); setCentralWidget(view_); @@ -171,7 +171,7 @@ void MainWindow::gameOver(bool isWin) { disconnect(gameTimer_, SIGNAL(timeout()), this, SLOT(updateGameTime())); disconnect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); - if(isWin) + if (isWin) { std::string str1 = "You WIN!"; const char* charArray = str1.c_str(); @@ -233,7 +233,7 @@ void MainWindow::generateRandomElements(int element, int count) { Hostile newHostile; Point p(0,0); - if(element == 3) + if (element == 3) { std::vector> matrix; for (int i = 0; i < kRows_; ++i) @@ -353,7 +353,7 @@ void MainWindow::moveHostile() std::cout << std::endl; } - std::vector direction; + std::vector direction; Point playerPoint(player_.getX(), player_.getY()); Point hostilePosition(0,0); @@ -361,29 +361,29 @@ void MainWindow::moveHostile() { currentHostile.setMatrix(matrix); direction = currentHostile.getPath(playerPoint); - if(direction.empty()) + if (direction.empty()) { return; } - if(direction[0] == "Left") + if (direction[0] == Directions::Left) { hostilePosition = currentHostile.getPosition(); gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); - currentHostile.setPreviousElement(gameGrid_[hostilePosition.y][hostilePosition.x-1]); + currentHostile.setPreviousElement(gameGrid_[hostilePosition.y][hostilePosition.x - 1]); hostilePosition.x = hostilePosition.x - 1; gameGrid_[hostilePosition.y][hostilePosition.x] = 3; currentHostile.setPosition(hostilePosition); } - if(direction[0] == "Right") + if (direction[0] == Directions::Right) { hostilePosition = currentHostile.getPosition(); gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); - currentHostile.setPreviousElement(gameGrid_[hostilePosition.y][hostilePosition.x+1]); + currentHostile.setPreviousElement(gameGrid_[hostilePosition.y][hostilePosition.x + 1]); hostilePosition.x = hostilePosition.x + 1; gameGrid_[hostilePosition.y][hostilePosition.x] = 3; currentHostile.setPosition(hostilePosition); } - if(direction[0] == "Up") + if (direction[0] == Directions::Up) { hostilePosition = currentHostile.getPosition(); @@ -394,7 +394,7 @@ void MainWindow::moveHostile() qDebug() << "gameGrid_ Coordinates: (" << hostilePosition.x << ", " << hostilePosition.y << ")"; currentHostile.setPosition(hostilePosition); } - if(direction[0] == "Down") + if (direction[0] == Directions::Down) { hostilePosition = currentHostile.getPosition(); @@ -409,7 +409,7 @@ void MainWindow::moveHostile() } void MainWindow::keyPressEvent(QKeyEvent *event) { - if(isKeyTime_) + if (isKeyTime_) { switch (event->key()) { @@ -440,14 +440,14 @@ void MainWindow::movePlayerUp() { if (player_.getY() > 0) { - if(gameGrid_[player_.getY()-1][player_.getX()] != GameElement::Wall) + if (gameGrid_[player_.getY() - 1][player_.getX()] != GameElement::Wall) { gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; - if(gameGrid_[player_.getY()-1][player_.getX()] == GameElement::Coin) + if (gameGrid_[player_.getY() - 1][player_.getX()] == GameElement::Coin) { counsCount_--; } - gameGrid_[player_.getY()-1][player_.getX()] = GameElement::Puckman; + gameGrid_[player_.getY() - 1][player_.getX()] = GameElement::Puckman; player_.setY(player_.getY() - 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } @@ -458,10 +458,10 @@ void MainWindow::movePlayerDown() { if (player_.getY()+1 < kRows_) { - if(gameGrid_[player_.getY()+1][player_.getX()] != GameElement::Wall) + if (gameGrid_[player_.getY()+1][player_.getX()] != GameElement::Wall) { gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; - if(gameGrid_[player_.getY()+1][player_.getX()] == GameElement::Coin) + if (gameGrid_[player_.getY()+1][player_.getX()] == GameElement::Coin) { counsCount_--; } @@ -474,16 +474,16 @@ void MainWindow::movePlayerDown() void MainWindow::movePlayerLeft() { - if(gameGrid_[player_.getY()][player_.getX()-1] != GameElement::Wall) + if (gameGrid_[player_.getY()][player_.getX() - 1] != GameElement::Wall) { if (player_.getX() > 0) { gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; - if(gameGrid_[player_.getY()][player_.getX()-1] == GameElement::Coin) + if (gameGrid_[player_.getY()][player_.getX() - 1] == GameElement::Coin) { counsCount_--; } - gameGrid_[player_.getY()][player_.getX()-1] = GameElement::Puckman; + gameGrid_[player_.getY()][player_.getX() - 1] = GameElement::Puckman; player_.setX(player_.getX() - 1); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } @@ -492,16 +492,16 @@ void MainWindow::movePlayerLeft() void MainWindow::movePlayerRight() { - if (player_.getX()+1 < kColumns_) + if (player_.getX() + 1 < kColumns_) { - if(gameGrid_[player_.getY()][player_.getX()+1] != GameElement::Wall) + if (gameGrid_[player_.getY()][player_.getX() + 1] != GameElement::Wall) { gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; - if(gameGrid_[player_.getY()][player_.getX()+1] == GameElement::Coin) + if (gameGrid_[player_.getY()][player_.getX() + 1] == GameElement::Coin) { counsCount_--; } - gameGrid_[player_.getY()][player_.getX()+1] = GameElement::Puckman; + gameGrid_[player_.getY()][player_.getX() + 1] = GameElement::Puckman; player_.setX(player_.getX() + 1); qDebug() << "Player Coordinates: (" << player_.getY() << ", " << player_.getX() << ")"; } diff --git a/redactor.cpp b/redactor.cpp index 336e116..40504ce 100644 --- a/redactor.cpp +++ b/redactor.cpp @@ -26,8 +26,8 @@ Redactor::Redactor(QWidget *parent) : connect(view, &CustomGraphicsView::customMouseRelease, this, &Redactor::handleCustomMouseRelease); - int uiWidth = (kColumns_+6) * cellSize_; - int uiHeight = (kRows_+1) * cellSize_; + int uiWidth = (kColumns_ + 6) * cellSize_; + int uiHeight = (kRows_ + 1) * cellSize_; this->setFixedSize(uiWidth, uiHeight); setCentralWidget(view); @@ -68,7 +68,7 @@ void Redactor::openGame() void Redactor::handleButtonClick() { - if(counsCount_ <= 0) + if (counsCount_ <= 0) { std::string str1 = "couns count < 0"; const char* charArray = str1.c_str(); @@ -101,19 +101,19 @@ void Redactor::dragItem() delete dragItem_; } dragItem_ = new QGraphicsPixmapItem(); - if(dragElement_ == GameElement::Wall) + if (dragElement_ == GameElement::Wall) { dragItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(cellSize_, cellSize_)); } - if(dragElement_ == GameElement::Puckman) + if (dragElement_ == GameElement::Puckman) { dragItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(cellSize_, cellSize_)); } - if(dragElement_ == GameElement::Hostile) + if (dragElement_ == GameElement::Hostile) { dragItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(cellSize_, cellSize_)); } - if(dragElement_ == GameElement::Coin) + if (dragElement_ == GameElement::Coin) { dragItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(cellSize_, cellSize_)); } @@ -159,26 +159,31 @@ void Redactor::setupGameGrid() } } } - int RETURN = 2; - + int extraColumns = kColumns_+2; + int nextRow = 1 * cellSize_; wallItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(cellSize_, cellSize_)); - wallItem_->setX((kColumns_+RETURN) * cellSize_); - wallItem_->setY(1 * cellSize_); + wallItem_->setX((extraColumns) * cellSize_); + wallItem_->setY(nextRow); qDebug() << "wallItem Coordinates: (" << wallItem_->x() << ", " << wallItem_->y() << ")"; + nextRow = 4 * cellSize_; puckmanItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(cellSize_, cellSize_)); - puckmanItem_->setX((kColumns_+RETURN) * cellSize_); - puckmanItem_->setY(4 * cellSize_); + puckmanItem_->setX((extraColumns) * cellSize_); + puckmanItem_->setY(nextRow); qDebug() << "puckmanItem Coordinates: (" << puckmanItem_->x() << ", " << puckmanItem_->y() << ")"; + extraColumns = 2; + nextRow = 6 * cellSize_; hostileItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(cellSize_, cellSize_)); - hostileItem_->setX((kColumns_+RETURN) * cellSize_); - hostileItem_->setY(6 * cellSize_); + hostileItem_->setX((extraColumns) * cellSize_); + hostileItem_->setY(nextRow); qDebug() << "hostileItem Coordinates: (" << hostileItem_->x() << ", " << hostileItem_->y() << ")"; + extraColumns = 2; + nextRow = 8 * cellSize_; coinItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(cellSize_, cellSize_)); - coinItem_->setX((kColumns_+RETURN) * cellSize_); - coinItem_->setY(8 * cellSize_); + coinItem_->setX((extraColumns) * cellSize_); + coinItem_->setY(nextRow); qDebug() << "coinItem Coordinates: (" << coinItem_->x() << ", " << coinItem_->y() << ")"; view->setSceneRect(0, 0, kColumns_ * cellSize_, kRows_ * cellSize_); @@ -194,9 +199,9 @@ QPoint Redactor::getGridPoint() { for (int j = 0; j < kColumns_; ++j) { - if(view->getCenterX()> i*cellSize_-halfGridSize && view->getCenterX()< i*cellSize_+halfGridSize) + if (view->getCenterX()> i * cellSize_-halfGridSize && view->getCenterX()< i * cellSize_+halfGridSize) { - if(view->getCenterY() > j*cellSize_-halfGridSize && view->getCenterY() < j*cellSize_+halfGridSize) + if (view->getCenterY() > j * cellSize_-halfGridSize && view->getCenterY() < j * cellSize_+halfGridSize) { coordinateElementGrid.setX(i); coordinateElementGrid.setY(j); @@ -213,36 +218,36 @@ QPoint Redactor::getGridPoint() int Redactor::getElement() { QGraphicsItem* item = scene->itemAt(view->getCenterX(), view->getCenterY(), QTransform()); - if(view->getCenterX()< wallItem_->x()+cellSize_ && view->getCenterX()> wallItem_->x()-cellSize_) + if (view->getCenterX() < wallItem_->x() + cellSize_ && view->getCenterX() > wallItem_->x() - cellSize_) { - if(view->getCenterY() < wallItem_->y()+cellSize_ && view->getCenterY() > wallItem_->y()-cellSize_) + if (view->getCenterY() < wallItem_->y() + cellSize_ && view->getCenterY() > wallItem_->y() - cellSize_) { qDebug() << "you drag item: (" << item << ")"; return GameElement::Wall; } } - if(view->getCenterX()< puckmanItem_->x()+cellSize_ && view->getCenterX()> puckmanItem_->x()-cellSize_) + if (view->getCenterX() < puckmanItem_->x() + cellSize_ && view->getCenterX() > puckmanItem_->x() - cellSize_) { - if(view->getCenterY() < puckmanItem_->y()+cellSize_ && view->getCenterY() > puckmanItem_->y()-cellSize_) + if (view->getCenterY() < puckmanItem_->y() + cellSize_ && view->getCenterY() > puckmanItem_->y() - cellSize_) { - if(isStatePacmanElement_ == false) + if (isStatePacmanElement_ == false) { qDebug() << "you drag item: (" << item << ")"; return GameElement::Puckman; } } } - if(view->getCenterX()< hostileItem_->x()+cellSize_ && view->getCenterX()> hostileItem_->x()-cellSize_) + if (view->getCenterX() < hostileItem_->x() + cellSize_ && view->getCenterX() > hostileItem_->x() - cellSize_) { - if(view->getCenterY() < hostileItem_->y()+cellSize_ && view->getCenterY() > hostileItem_->y()-cellSize_) + if (view->getCenterY() < hostileItem_->y() + cellSize_ && view->getCenterY() > hostileItem_->y() - cellSize_) { qDebug() << "you drag item: (" << item << ")"; return GameElement::Hostile; } } - if(view->getCenterX()< coinItem_->x()+cellSize_ && view->getCenterX()> coinItem_->x()-cellSize_) + if (view->getCenterX() < coinItem_->x() + cellSize_ && view->getCenterX() > coinItem_->x() - cellSize_) { - if(view->getCenterY() < coinItem_->y()+cellSize_ && view->getCenterY() > coinItem_->y()-cellSize_) + if (view->getCenterY() < coinItem_->y() + cellSize_ && view->getCenterY() > coinItem_->y() - cellSize_) { qDebug() << "you drag item: (" << item << ")"; return GameElement::Coin; @@ -276,7 +281,7 @@ void Redactor::handleCustomMouseRelease() { dragItem_ = new QGraphicsPixmapItem(); QPoint cell = getGridPoint(); - if(cell.x() > 0 || cell.y() > 0) + if (cell.x() > 0 || cell.y() > 0) { if (gameGrid_[cell.y()][cell.x()] == GameElement::Puckman) { @@ -287,11 +292,11 @@ void Redactor::handleCustomMouseRelease() counsCount_--; } gameGrid_[cell.y()][cell.x()] = dragElement_; - if(dragElement_ == GameElement::Puckman) + if (dragElement_ == GameElement::Puckman) { isStatePacmanElement_ = true; } - if(dragElement_ == GameElement::Coin) + if (dragElement_ == GameElement::Coin) { counsCount_++; qDebug() << "counsCount = (" << counsCount_ << ")"; From 1a8bf8c9d0547ae5cc35fddec2fb073d94088aa2 Mon Sep 17 00:00:00 2001 From: KloopRE <100780612+KloopRE@users.noreply.github.com> Date: Tue, 19 Dec 2023 13:30:44 +0300 Subject: [PATCH 8/8] =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit else if нужно перенести Опять 1 и 4 - числа, уже 3е исправление. Все это - магические числа. Как я уже писал, у вас 1, 4, 6, 8 встречаются числами во всем коде - все это магические числа. Исправьте во ВСЕМ проекте. 1 - не во вех местах маг. число, но там, где оно идет по логике с 4, 6, 8 - магическое точно. str1 ? Почему она тут 1? Дайте нормальное название. Не исправлено сокращение Название с сокращением не исправляется уже 3ий раз! Пробел после if, скобку не переносим player_.getY()+1 Пробелы. 6 и 1 все еще дубляж кода. Вообще у вас уже есть схожий конструктор в классе mainwinow.... прямо напрашивается создать базовый класс и вынести эту функциональность в нее. str1 - бесполезное название, дайте осмысленное название. --- hostile.cpp | 3 +- mainwindow.cpp | 210 ++++++++++++++++++------------------------------- mainwindow.h | 6 +- redactor.cpp | 30 ++++--- 4 files changed, 98 insertions(+), 151 deletions(-) diff --git a/hostile.cpp b/hostile.cpp index 6247d4f..e958975 100644 --- a/hostile.cpp +++ b/hostile.cpp @@ -25,7 +25,8 @@ std::vector getMoveDirections(const Point& start, const Point& end) if (dx > 0) { directions.push_back(Directions(Directions::Right)); - } else if (dx < 0) + } + else if (dx < 0) { directions.push_back(Directions(Directions::Left)); } diff --git a/mainwindow.cpp b/mainwindow.cpp index b43eb02..98fab81 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -11,55 +11,22 @@ #include #include -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), ui(new Ui::MainWindow) -{ - - - ui->setupUi(this); - setFocusPolicy(Qt::StrongFocus); - setFocus(); - - scene_ = new QGraphicsScene(this); - view_ = new QGraphicsView(scene_, this); - - int uiWidth = (kColumns_ + 4) * cellSize_; - int uiHeight = (kRows_ + 1) * cellSize_; - - this->setFixedSize(uiWidth, uiHeight); - setCentralWidget(view_); - - gameTimer_ = new QTimer(this); - gameTimer_->start(250); - connect(gameTimer_, SIGNAL(timeout()), this, SLOT(updateGameTime())); - - hostileRunTimer_ = new QTimer(this); - hostileRunTimer_->start(1000); - connect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); - - gameGrid_ = new int*[kRows_]; - for (int i = 0; i < kRows_; ++i) - { - gameGrid_[i] = new int[kColumns_]; - } - generateRandomGameGrid(); - - setupGameGrid(); -} - MainWindow::MainWindow(QWidget *parent, int** gameGrid) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setFocusPolicy(Qt::StrongFocus); + setFocus(); hostiles_.reserve(kColumns_*kRows_); scene_ = new QGraphicsScene(this); view_ = new QGraphicsView(scene_, this); - int uiWidth = (kColumns_ + 4) * cellSize_; - int uiHeight = (kRows_ + 1) * cellSize_; + int indentationColumns = 4; + int indentationRows = 4; + int uiWidth = (kColumns_ + indentationColumns) * cellSize_; + int uiHeight = (kRows_ + indentationRows) * cellSize_; this->setFixedSize(uiWidth, uiHeight); setCentralWidget(view_); @@ -93,7 +60,7 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) } } Hostile newHostile; - Point p(0, 0); + Point hostilePosition(0, 0); if (gameGrid != nullptr) { gameGrid_ = new int*[kRows_]; @@ -103,19 +70,19 @@ MainWindow::MainWindow(QWidget *parent, int** gameGrid) for (int j = 0; j < kColumns_; ++j) { gameGrid_[i][j] = gameGrid[i][j]; - if(gameGrid_[i][j] == 3) + if(gameGrid_[i][j] == GameElement::Hostile) { - p.x = j; - p.y = i; - newHostile.setPosition(p); - qDebug() << "Hostile Coordinates: (" << p.x << ", " << p.y << ")"; + hostilePosition.x = j; + hostilePosition.y = i; + newHostile.setPosition(hostilePosition); + qDebug() << "Hostile Coordinates: (" << hostilePosition.x << ", " << hostilePosition.y << ")"; hostiles_.push_back(newHostile); } - if(gameGrid_[i][j] == 4) + if(gameGrid_[i][j] == GameElement::Coin) { counsCount_++; } - if(gameGrid_[i][j] == 2) + if(gameGrid_[i][j] == GameElement::Puckman) { player_.setY(i); player_.setX(j); @@ -141,7 +108,7 @@ void MainWindow::updateGameTime() gameTime_ += 0.5; isKeyTime_ = true; setupGameGrid(); - if(gameGrid_[player_.getY()][player_.getX()] == 3) + if(gameGrid_[player_.getY()][player_.getX()] == GameElement::Hostile) { gameOver(false); } @@ -173,16 +140,16 @@ void MainWindow::gameOver(bool isWin) disconnect(hostileRunTimer_, SIGNAL(timeout()), this, SLOT(updateHostileRunTime())); if (isWin) { - std::string str1 = "You WIN!"; - const char* charArray = str1.c_str(); + std::string stringGameOver = "You WIN!"; + const char* charArray = stringGameOver.c_str(); QMessageBox::information(this, "WIN", charArray); } else { - std::string str1 = "Game Over, coins left: "; - std::string str2 = std::to_string(counsCount_); - str1.append(str2); - const char* charArray = str1.c_str(); + std::string stringGameOver = "Game Over, coins left: "; + std::string stringGameOver2 = std::to_string(counsCount_); + stringGameOver.append(stringGameOver2); + const char* charArray = stringGameOver.c_str(); QMessageBox::information(this, "False", charArray); } close(); @@ -211,20 +178,20 @@ void MainWindow::generateRandomGameGrid() int randomRow = std::rand() % kRows_; int randomColumn = std::rand() % kColumns_; - gameGrid_[randomRow][randomColumn] = 2; + gameGrid_[randomRow][randomColumn] = GameElement::Puckman; player_.setX(randomColumn); player_.setY(randomRow); qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; - int element = 1; + int element = GameElement::Wall; int count = 5; generateRandomElements(element,count); - element = 3; + element = GameElement::Hostile; count = 2; generateRandomElements(element,count); - element = 4; + element = GameElement::Coin; generateRandomElements(element,counsCount_); } @@ -232,8 +199,8 @@ void MainWindow::generateRandomGameGrid() void MainWindow::generateRandomElements(int element, int count) { Hostile newHostile; - Point p(0,0); - if (element == 3) + Point hostilePosition(0,0); + if (element == GameElement::Hostile) { std::vector> matrix; for (int i = 0; i < kRows_; ++i) @@ -261,16 +228,16 @@ void MainWindow::generateRandomElements(int element, int count) int randomRow = std::rand() % kRows_; int randomColumn = std::rand() % kColumns_; - while (gameGrid_[randomRow][randomColumn] != 0) + while (gameGrid_[randomRow][randomColumn] != GameElement::Empty) { randomRow = std::rand() % kRows_; randomColumn = std::rand() % kColumns_; } - if(element == 3) + if(element == GameElement::Hostile) { - p.x = randomColumn; - p.y = randomRow; - newHostile.setPosition(p); + hostilePosition.x = randomColumn; + hostilePosition.y = randomRow; + newHostile.setPosition(hostilePosition); hostiles_.push_back(newHostile); } gameGrid_[randomRow][randomColumn] = element; @@ -371,7 +338,7 @@ void MainWindow::moveHostile() gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); currentHostile.setPreviousElement(gameGrid_[hostilePosition.y][hostilePosition.x - 1]); hostilePosition.x = hostilePosition.x - 1; - gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + gameGrid_[hostilePosition.y][hostilePosition.x] = GameElement::Hostile; currentHostile.setPosition(hostilePosition); } if (direction[0] == Directions::Right) @@ -380,7 +347,7 @@ void MainWindow::moveHostile() gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); currentHostile.setPreviousElement(gameGrid_[hostilePosition.y][hostilePosition.x + 1]); hostilePosition.x = hostilePosition.x + 1; - gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + gameGrid_[hostilePosition.y][hostilePosition.x] = GameElement::Hostile; currentHostile.setPosition(hostilePosition); } if (direction[0] == Directions::Up) @@ -388,9 +355,9 @@ void MainWindow::moveHostile() hostilePosition = currentHostile.getPosition(); gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); - currentHostile.setPreviousElement(gameGrid_[hostilePosition.y-1][hostilePosition.x]); + currentHostile.setPreviousElement(gameGrid_[hostilePosition.y - 1][hostilePosition.x]); hostilePosition.y = hostilePosition.y - 1; - gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + gameGrid_[hostilePosition.y][hostilePosition.x] = GameElement::Hostile; qDebug() << "gameGrid_ Coordinates: (" << hostilePosition.x << ", " << hostilePosition.y << ")"; currentHostile.setPosition(hostilePosition); } @@ -399,34 +366,35 @@ void MainWindow::moveHostile() hostilePosition = currentHostile.getPosition(); gameGrid_[hostilePosition.y][hostilePosition.x] = currentHostile.getPreviousElement(); - currentHostile.setPreviousElement(gameGrid_[hostilePosition.y+1][hostilePosition.x]); + currentHostile.setPreviousElement(gameGrid_[hostilePosition.y + 1][hostilePosition.x]); hostilePosition.y = hostilePosition.y + 1; - gameGrid_[hostilePosition.y][hostilePosition.x] = 3; + gameGrid_[hostilePosition.y][hostilePosition.x] = GameElement::Hostile; qDebug() << "gameGrid_ Coordinates: (" << hostilePosition.x << ", " << hostilePosition.y << ")"; currentHostile.setPosition(hostilePosition); } } } -void MainWindow::keyPressEvent(QKeyEvent *event) { +void MainWindow::keyPressEvent(QKeyEvent *event) +{ if (isKeyTime_) { switch (event->key()) { case Qt::Key_W: - movePlayerUp(); + movePlayer(Directions::Up); isKeyTime_ = false; break; case Qt::Key_S: - movePlayerDown(); + movePlayer(Directions::Down); isKeyTime_ = false; break; case Qt::Key_A: - movePlayerLeft(); + movePlayer(Directions::Left); isKeyTime_ = false; break; case Qt::Key_D: - movePlayerRight(); + movePlayer(Directions::Right); isKeyTime_ = false; break; default: @@ -436,74 +404,50 @@ void MainWindow::keyPressEvent(QKeyEvent *event) { } } -void MainWindow::movePlayerUp() +void MainWindow::movePlayer(Directions direction) { - if (player_.getY() > 0) + int newX = player_.getX(); + int newY = player_.getY(); + + int direc = 4; + if (direction == Directions::Up) { - if (gameGrid_[player_.getY() - 1][player_.getX()] != GameElement::Wall) - { - gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; - if (gameGrid_[player_.getY() - 1][player_.getX()] == GameElement::Coin) - { - counsCount_--; - } - gameGrid_[player_.getY() - 1][player_.getX()] = GameElement::Puckman; - player_.setY(player_.getY() - 1); - qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; - } + direc = 1; } -} - -void MainWindow::movePlayerDown() -{ - if (player_.getY()+1 < kRows_) + if (direction == Directions::Down) { - if (gameGrid_[player_.getY()+1][player_.getX()] != GameElement::Wall) - { - gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; - if (gameGrid_[player_.getY()+1][player_.getX()] == GameElement::Coin) - { - counsCount_--; - } - gameGrid_[player_.getY()+1][player_.getX()] = GameElement::Puckman; - player_.setY(player_.getY() + 1); - qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; - } + direc = 2; } -} - -void MainWindow::movePlayerLeft() -{ - if (gameGrid_[player_.getY()][player_.getX() - 1] != GameElement::Wall) + if (direction == Directions::Left) { - if (player_.getX() > 0) - { - gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; - if (gameGrid_[player_.getY()][player_.getX() - 1] == GameElement::Coin) - { - counsCount_--; - } - gameGrid_[player_.getY()][player_.getX() - 1] = GameElement::Puckman; - player_.setX(player_.getX() - 1); - qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; - } + direc = 3; + } + switch (direc) + { + case 1: + newY = std::max(0, newY - 1); + break; + case 2: + newY = std::min(kRows_ - 1, newY + 1); + break; + case 3: + newX = std::max(0, newX - 1); + break; + case 4: + newX = std::min(kColumns_ - 1, newX + 1); + break; } -} -void MainWindow::movePlayerRight() -{ - if (player_.getX() + 1 < kColumns_) + if (gameGrid_[newY][newX] != GameElement::Wall) { - if (gameGrid_[player_.getY()][player_.getX() + 1] != GameElement::Wall) + gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; + if (gameGrid_[newY][newX] == GameElement::Coin) { - gameGrid_[player_.getY()][player_.getX()] = GameElement::Empty; - if (gameGrid_[player_.getY()][player_.getX() + 1] == GameElement::Coin) - { - counsCount_--; - } - gameGrid_[player_.getY()][player_.getX() + 1] = GameElement::Puckman; - player_.setX(player_.getX() + 1); - qDebug() << "Player Coordinates: (" << player_.getY() << ", " << player_.getX() << ")"; + counsCount_--; } + gameGrid_[newY][newX] = GameElement::Puckman; + player_.setX(newX); + player_.setY(newY); + qDebug() << "Player Coordinates: (" << player_.getX() << ", " << player_.getY() << ")"; } } diff --git a/mainwindow.h b/mainwindow.h index 6013ab7..9369cdc 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -20,7 +20,6 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); MainWindow(QWidget *parent = nullptr, int** gameGrid = nullptr); ~MainWindow(); @@ -46,10 +45,7 @@ class MainWindow : public QMainWindow QGraphicsView *view_; std::vector hostiles_; - void movePlayerUp(); - void movePlayerDown(); - void movePlayerLeft(); - void movePlayerRight(); + void movePlayer(Directions direction); void moveHostile(); void generateRandomElements(int element, int count); void updateCoinsCount(); diff --git a/redactor.cpp b/redactor.cpp index 40504ce..e2573ad 100644 --- a/redactor.cpp +++ b/redactor.cpp @@ -26,8 +26,10 @@ Redactor::Redactor(QWidget *parent) : connect(view, &CustomGraphicsView::customMouseRelease, this, &Redactor::handleCustomMouseRelease); - int uiWidth = (kColumns_ + 6) * cellSize_; - int uiHeight = (kRows_ + 1) * cellSize_; + int indentationColumns = 6; + int indentationRows = 1; + int uiWidth = (kColumns_ + indentationColumns) * cellSize_; + int uiHeight = (kRows_ + indentationRows) * cellSize_; this->setFixedSize(uiWidth, uiHeight); setCentralWidget(view); @@ -70,8 +72,8 @@ void Redactor::handleButtonClick() { if (counsCount_ <= 0) { - std::string str1 = "couns count < 0"; - const char* charArray = str1.c_str(); + std::string stringWarn = "couns count < 0"; + const char* charArray = stringWarn.c_str(); QMessageBox::information(this, "False", charArray); return; } @@ -160,26 +162,30 @@ void Redactor::setupGameGrid() } } int extraColumns = kColumns_+2; - int nextRow = 1 * cellSize_; + int Row = 2; + int nextRow = Row * cellSize_; wallItem_ = scene->addPixmap(QPixmap(":resource/wall.png").scaled(cellSize_, cellSize_)); wallItem_->setX((extraColumns) * cellSize_); wallItem_->setY(nextRow); qDebug() << "wallItem Coordinates: (" << wallItem_->x() << ", " << wallItem_->y() << ")"; - nextRow = 4 * cellSize_; + Row = 4; + nextRow = Row * cellSize_; puckmanItem_ = scene->addPixmap(QPixmap(":resource/puckman.png").scaled(cellSize_, cellSize_)); puckmanItem_->setX((extraColumns) * cellSize_); puckmanItem_->setY(nextRow); qDebug() << "puckmanItem Coordinates: (" << puckmanItem_->x() << ", " << puckmanItem_->y() << ")"; - extraColumns = 2; - nextRow = 6 * cellSize_; + + Row = 6; + nextRow = Row * cellSize_; hostileItem_ = scene->addPixmap(QPixmap(":resource/hostile.png").scaled(cellSize_, cellSize_)); hostileItem_->setX((extraColumns) * cellSize_); hostileItem_->setY(nextRow); qDebug() << "hostileItem Coordinates: (" << hostileItem_->x() << ", " << hostileItem_->y() << ")"; - extraColumns = 2; - nextRow = 8 * cellSize_; + + Row = 8; + nextRow = Row * cellSize_; coinItem_ = scene->addPixmap(QPixmap(":resource/coin.png").scaled(cellSize_, cellSize_)); coinItem_->setX((extraColumns) * cellSize_); @@ -199,9 +205,9 @@ QPoint Redactor::getGridPoint() { for (int j = 0; j < kColumns_; ++j) { - if (view->getCenterX()> i * cellSize_-halfGridSize && view->getCenterX()< i * cellSize_+halfGridSize) + if (view->getCenterX() > i * cellSize_ - halfGridSize && view->getCenterX()< i * cellSize_ + halfGridSize) { - if (view->getCenterY() > j * cellSize_-halfGridSize && view->getCenterY() < j * cellSize_+halfGridSize) + if (view->getCenterY() > j * cellSize_ - halfGridSize && view->getCenterY() < j * cellSize_ + halfGridSize) { coordinateElementGrid.setX(i); coordinateElementGrid.setY(j);