From 98c3ff5dfbc13a14e3b92ee21e676c5f1dbf51db Mon Sep 17 00:00:00 2001 From: Adelina Vakilova Date: Tue, 28 Nov 2023 22:09:54 +0300 Subject: [PATCH 1/4] tetris_Adelina --- TetrisTask.pro | 11 +- gamefield.cpp | 32 ------ gamefield.h | 36 ------- main.cpp | 13 +-- mainwindow.cpp | 117 ++++++++++++++++++++ mainwindow.h | 40 +++++++ tetris.ui | 46 -------- tetrisgrid.cpp | 288 +++++++++++++++++++++++++++++++++++++++++++++++++ tetrisgrid.h | 65 +++++++++++ 9 files changed, 522 insertions(+), 126 deletions(-) delete mode 100644 gamefield.cpp delete mode 100644 gamefield.h create mode 100644 mainwindow.cpp create mode 100644 mainwindow.h delete mode 100644 tetris.ui create mode 100644 tetrisgrid.cpp create mode 100644 tetrisgrid.h diff --git a/TetrisTask.pro b/TetrisTask.pro index f4de819..041fcb4 100644 --- a/TetrisTask.pro +++ b/TetrisTask.pro @@ -9,16 +9,15 @@ CONFIG += c++17 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ - gamefield.cpp \ main.cpp \ - tetris.cpp + mainwindow.cpp \ + tetrisgrid.cpp HEADERS += \ - gamefield.h \ - tetris.h + mainwindow.h \ + tetrisgrid.h -FORMS += \ - tetris.ui +FORMS += # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin diff --git a/gamefield.cpp b/gamefield.cpp deleted file mode 100644 index 6a5ce13..0000000 --- a/gamefield.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "gamefield.h" - -#include - -GameField::GameField(QWidget *parent) : QWidget{parent} { - connect(this, &GameField::InitialisationStarted, this, &GameField::SetCells, - Qt::QueuedConnection); - - emit InitialisationStarted(); -} - -uint GameField::GetRowsNumber() const { return rowsNumber_; } - -void GameField::SetRowsNumber(uint rowsNumber) { - if (rowsNumber_ == rowsNumber) return; - - rowsNumber_ = rowsNumber; - emit RowsNumberChanged(); -} - -uint GameField::GetColumnsNumber() const { return columnsNumber_; } - -void GameField::SetColumnNumber(uint columnsCount) { - if (columnsNumber_ == columnsCount) return; - - columnsNumber_ = columnsCount; - emit ColumnsNumberChanged(); -} - -void GameField::SetCells() { - qDebug() << rowsNumber_ << " " << columnsNumber_ << "|"; -} diff --git a/gamefield.h b/gamefield.h deleted file mode 100644 index e36baa8..0000000 --- a/gamefield.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef GAMEFIELD_H -#define GAMEFIELD_H - -#include - -class GameField : public QWidget { - Q_OBJECT - public: - explicit GameField(QWidget *parent = nullptr); - - Q_PROPERTY(uint rowsNumber READ GetRowsNumber WRITE SetRowsNumber NOTIFY - RowsNumberChanged FINAL) - Q_PROPERTY(uint columnsNumber READ GetColumnsNumber WRITE SetColumnNumber - NOTIFY ColumnsNumberChanged FINAL) - - signals: - void RowsNumberChanged(); - void ColumnsNumberChanged(); - void InitialisationStarted(); - - private slots: - void SetCells(); - - public: - uint GetRowsNumber() const; - void SetRowsNumber(uint newRowsNumber); - - uint GetColumnsNumber() const; - void SetColumnNumber(uint newColumnsCount); - - private: - uint rowsNumber_ = 0; - uint columnsNumber_ = 0; -}; - -#endif // GAMEFIELD_H diff --git a/main.cpp b/main.cpp index f1c8bd9..2e33976 100644 --- a/main.cpp +++ b/main.cpp @@ -1,10 +1,11 @@ #include - -#include "tetris.h" +#include +#include "mainwindow.h" int main(int argc, char *argv[]) { - QApplication a(argc, argv); - Tetris w; - w.show(); - return a.exec(); + QApplication a(argc, argv); + MainWindow w; + w.resize(400, 500); + w.show(); + return a.exec(); } diff --git a/mainwindow.cpp b/mainwindow.cpp new file mode 100644 index 0000000..65c9ed1 --- /dev/null +++ b/mainwindow.cpp @@ -0,0 +1,117 @@ +#include "mainwindow.h" +#include +#include +#include +#include +#include + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), score_(0) { + gameOverHandled_ = false; + tetrisGrid = new TetrisGrid(this); + startButton =new QPushButton("Начать новую игру", this); + exitButton = new QPushButton("Выход", this); + scoreLabel = new QLabel("Счетчик очков: 0", this); + helpButton = new QPushButton("Справка", this); + + qApp->setStyle(QStyleFactory::create("Fusion")); + QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this); + shadowEffect->setBlurRadius(15); + shadowEffect->setColor(QColor(0, 0, 0, 150)); + shadowEffect->setOffset(0, 5); + + QString buttonStyle = "QPushButton {" + " background-color: #3498db;" + " border-style: outset;" + " border-width: 2px;" + " border-radius: 10px;" + " border-color: #2980b9;" + " color: #ecf0f1;" + " padding: 5px;" + "}" + "QPushButton:hover {" + " background-color: #2980b9;" + " color: #bdc3c7;" + "}"; + + startButton->setStyleSheet(buttonStyle); + startButton->setGraphicsEffect(shadowEffect); + + helpButton->setStyleSheet(buttonStyle); + helpButton->setGraphicsEffect(shadowEffect); + + exitButton->setStyleSheet(buttonStyle); + exitButton->setGraphicsEffect(shadowEffect); + + connect(helpButton, &QPushButton::clicked, this, &MainWindow::showHelp); + connect(startButton, &QPushButton::clicked, this, &MainWindow::restartGame); + connect(exitButton, &QPushButton::clicked, this, &MainWindow::exitGame); + connect(tetrisGrid, SIGNAL(scoreChanged(int)), this, SLOT(updateScore(int))); + connect(tetrisGrid, SIGNAL(gameOver()), this, SLOT(exitGame())); + connect(tetrisGrid, &TetrisGrid::gameOver, [=]() { + if (!gameOverHandled_) { + gameOverHandled_ = true; + exitGame(); + } + }); + + + QVBoxLayout *layout = new QVBoxLayout; + layout->addWidget(tetrisGrid, Qt::AlignHCenter); + layout->addWidget(scoreLabel); + layout->addWidget(startButton); + layout->addWidget(helpButton); + layout->addWidget(exitButton); + + QWidget *centralWidget = new QWidget(this); + centralWidget->setLayout(layout); + setCentralWidget(centralWidget); +} + +MainWindow::~MainWindow() {} + +void MainWindow::showHelp() { + QString helpText = "Правила игры:\n\n" + "1. Сдвигайте фигуры влево/вправо, используя стрелки клавиатуры.\n" + "2. Поворачивайте фигуры при помощи клавиши 'Вверх'.\n" + "3. Ускоряйте падение фигур с помощью кнопки 'Вниз'.\n" + "4. Заполняйте горизонтальные линии, чтобы они исчезали и приносили очки.\n" + "\nУправление:\n" + "- Сдвиг влево: Стрелка влево\n" + "- Сдвиг вправо: Стрелка вправо\n" + "- Поворот: Стрелка вверх\n" + "- Ускорение падения: Стрелка вниз'\n"; + QMessageBox::information(this, "Справка", helpText); +} + +void MainWindow::restartGame() { + tetrisGrid->startGame(); + setupGame(); +} + +void MainWindow::startGame() { + setFocus(); + score_ = 0; + updateScore(score_); +} + +void MainWindow::exitGame() { + gameOverHandled_ = true; + QMessageBox messageBox; + messageBox.setWindowTitle("Игра окончена"); + messageBox.setText("Игра завершена. Набрано очков: " + QString::number(score_)); + messageBox.setStandardButtons(QMessageBox::Ok); + messageBox.exec(); + close(); +} + +void MainWindow::updateScore(int newScore) { + score_ = newScore; + scoreLabel->setText("Счетчик очков: " + QString::number(score_)); +} + +void MainWindow::keyPressEvent(QKeyEvent *event) { + tetrisGrid->handleKeyPressEvent(event); +} + +void MainWindow::setupGame() {} diff --git a/mainwindow.h b/mainwindow.h new file mode 100644 index 0000000..275270c --- /dev/null +++ b/mainwindow.h @@ -0,0 +1,40 @@ +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include +#include +#include "tetrisgrid.h" + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = nullptr); + ~MainWindow(); + +private: + TetrisGrid *tetrisGrid; + QPushButton *startButton; + QPushButton *exitButton; + QPushButton *helpButton; + QLabel *scoreLabel; + void setupGame(); + int score_; + bool gameOverHandled_ = false; + +private slots: + void startGame(); + void exitGame(); + void updateScore(int newScore); + void restartGame(); + void showHelp(); + +public slots: + void keyPressEvent(QKeyEvent *event); + + +}; + +#endif // MAINWINDOW_H diff --git a/tetris.ui b/tetris.ui deleted file mode 100644 index ae63379..0000000 --- a/tetris.ui +++ /dev/null @@ -1,46 +0,0 @@ - - - Tetris - - - - 0 - 0 - 800 - 600 - - - - Tetris - - - - 20 - - - 10 - - - - - - 0 - 0 - 800 - 21 - - - - - - - - GameField - QWidget -
gamefield.h
- 1 -
-
- - -
diff --git a/tetrisgrid.cpp b/tetrisgrid.cpp new file mode 100644 index 0000000..13f60d9 --- /dev/null +++ b/tetrisgrid.cpp @@ -0,0 +1,288 @@ +#include "tetrisgrid.h" +#include +#include +#include +#include + +TetrisGrid::TetrisGrid(QWidget *parent) + : QWidget(parent), m_rows_(20), m_cols_(10), m_gridNew_(m_rows_, QVector(m_cols_, 0)), timer_(new QTimer(this)), score_(0) { + m_grid_.resize(m_rows_, QVector(m_cols_, 0)); + setFocusPolicy(Qt::StrongFocus); + connect(timer_, &QTimer::timeout, this, &TetrisGrid::dropShape); + timer_->setInterval(speed_); + startGame(); +} + +void TetrisGrid::addCurrentShapeToGridNew() { + for (int i = 0; i < currentShape_.size(); ++i) { + for (int j = 0; j < currentShape_[i].size(); ++j) { + if (currentShape_[i][j] == 1) { + int gridRow = shapeRow_ + i; + int gridCol = shapeCol_ + j; + if (gridRow >= 0 && gridRow < m_rows_ && gridCol >= 0 && gridCol < m_cols_) { + if (gridRow <= 0) { + emit gameOver(); + } + else + m_grid_[gridRow][gridCol] = 1; + } + } + } + } +} + +void TetrisGrid::setupGame() { + m_grid_.clear(); + m_grid_.resize(m_rows_, QVector(m_cols_, 0)); + score_ = 0; + updateScore(score_); + generateNewShape(); +} + +void TetrisGrid::speedFigure(){ + timer_->setInterval(100); + timer_->start(); +} + +int TetrisGrid::rows() const { + return m_rows_; +} + +int TetrisGrid::cols() const { + return m_cols_; +} + +void TetrisGrid::setRows(int rows) { + if (m_rows_ != rows) { + m_rows_ = rows; + m_grid_.resize(m_rows_); + for (auto &row : m_grid_) { + row.resize(m_cols_); + } + emit rowsChanged(m_rows_); + update(); + } +} + +void TetrisGrid::setCols(int cols) { + if (m_cols_ != cols) { + m_cols_ = cols; + for (auto &row_ : m_grid_) { + row_.resize(m_cols_); + } + emit colsChanged(m_cols_); + update(); + } +} + +void TetrisGrid::startGame() { + setupGame(); + timer_->start(); +} + + +void TetrisGrid::moveShapeLeft() { + if (shapeCol_ > 0) { + --shapeCol_; + if (!isValidMove(currentShape_, shapeRow_, shapeCol_)) { + ++shapeCol_; + } + update(); + } +} + +void TetrisGrid::moveShapeRight() { + if (shapeCol_ + currentShape_[0].size() < m_cols_) { + ++shapeCol_; + if (!isValidMove(currentShape_, shapeRow_, shapeCol_)) { + --shapeCol_; + } + update(); + } +} + +bool TetrisGrid::isValidMove(const QVector> &shape, int rows, int cols) { + for (int i = 0; i < shape.size(); ++i) { + for (int j = 0; j < shape[i].size(); ++j) { + if (shape[i][j] == 1) { + int gridRow = rows + i; + int gridCol = cols + j; + if (gridRow < 0 || gridRow >= m_rows_ || gridCol < 0 || gridCol >= m_cols_) { + return false; + } + if (m_grid_[gridRow][gridCol] == 1) { + return false; + } + } + } + } + return true; +} + +void TetrisGrid::rotateShape() +{ + QVector> rotatedShape; + QVector temp; + for (int j = currentShape_[0].size()-1; j >= 0; --j) { + temp.clear(); + for (int i = 0; i < currentShape_.size(); ++i) { + temp.append(currentShape_[i][j]); + } + rotatedShape.append(temp); + } + if (isValidMove(rotatedShape, shapeRow_, shapeCol_)) { + currentShape_ = rotatedShape; + update(); + } +} + +void TetrisGrid::dropShape() { + + if (shapeRow_ + currentShape_.size() <= m_rows_) { + ++shapeRow_; + if (isCollision()) { + --shapeRow_; + addCurrentShapeToGridNew(); + generateNewShape(); + checkLines(); + } + update(); + } +} + +void TetrisGrid::updateScore(int newScore) { + score_ = newScore; + emit scoreChanged(score_); +} + +void TetrisGrid::paintEvent(QPaintEvent *event) { + Q_UNUSED(event); + QPainter painter(this); + int cellSize = qMin(width() / m_cols_, height() / m_rows_); + drawGrid(painter, cellSize); + drawShape(painter, cellSize); +} + +void TetrisGrid::drawGrid(QPainter &painter, int cellSize) { + for (int row = 0; row < m_rows_; ++row) { + for (int col = 0; col < m_cols_; ++col) { + if (m_grid_[row][col] == 1) { + QColor color = generateRandomColor(); + painter.fillRect(col * cellSize, row * cellSize, cellSize, cellSize, color); + } else { + painter.fillRect(col * cellSize, row * cellSize, cellSize, cellSize, Qt::white); + painter.drawRect(col * cellSize, row * cellSize, cellSize, cellSize); + } + } + } +} + +void TetrisGrid::drawShape(QPainter &painter, int cellSize) { + for (int i = 0; i < currentShape_.size(); ++i) { + for (int j = 0; j < currentShape_[i].size(); ++j) { + if (currentShape_[i][j] == 1) { + QColor color = generateRandomColor(); + QBrush brush(color); + painter.setBrush(brush); + painter.fillRect((shapeCol_ + j) * cellSize, (shapeRow_ + i) * cellSize, cellSize, cellSize, color); + painter.drawRect((shapeCol_ + j) * cellSize, (shapeRow_ + i) * cellSize, cellSize, cellSize); + } + } + } +} + +QColor TetrisGrid::generateRandomColor() { + return QColor(rand() % 256, rand() % 256, rand() % 256); +} + +void TetrisGrid::generateNewShape() { + shapeRow_ = 0; + shapeCol_ = m_cols_ / 2 - 1; + int type = rand() % 6; + currentShape_.clear(); + currentShape_ = nextShape_; + nextShape_.clear(); + if (type == 0) { + nextShape_.append({1, 1}); + nextShape_.append({1, 1}); + } else if (type == 1) { + nextShape_.append({1, 1, 1, 1}); + } else if (type == 2){ + nextShape_.append({1, 1}); + nextShape_.append({1, 0}); + nextShape_.append({1, 0}); + } else if (type == 3){ + nextShape_.append({1, 1}); + } else if (type == 4){ + nextShape_.append({1, 1}); + nextShape_.append({0, 1}); + nextShape_.append({0, 1}); + } else { + nextShape_.append({0, 1, 0}); + nextShape_.append({1, 1, 1}); + } + if (currentShape_.size() == 0) { + generateNewShape(); + } + timer_->setInterval(speed_); +} + +void TetrisGrid::handleKeyPressEvent(QKeyEvent *event) { + keyPressEvent(event); +} + +void TetrisGrid::keyPressEvent(QKeyEvent *event) +{ + switch (event->key()) { + case Qt::Key_Left: + emit moveShapeLeft(); + break; + case Qt::Key_Right: + emit moveShapeRight(); + break; + case Qt::Key_Up: + emit rotateShape(); + break; + case Qt::Key_Down: + emit speedFigure(); + break; + default: + QWidget::keyPressEvent(event); + } +} + +bool TetrisGrid::isCollision() { + for (int i = 0; i < currentShape_.size(); ++i) { + for (int j = 0; j < currentShape_[i].size(); ++j) { + if (currentShape_[i][j] == 1) { + int gridRow = shapeRow_ + i; + int gridCol = shapeCol_ + j; + if (gridRow < 0 || gridRow >= m_rows_ || gridCol < 0 || gridCol >= m_cols_ || m_grid_[gridRow][gridCol] == 1) { + return true; + } + } + } + } + return false; +} + +void TetrisGrid::checkLines() { + + for (int row = m_rows_ - 1; row >= 0; --row) { + bool lineFilled = true; + for (int col = 0; col < m_cols_; ++col) { + if (m_grid_[row][col] == 0) { + lineFilled = false; + break; + } + } + if (lineFilled) { + for (int r = row; r > 0; --r) { + m_grid_[r] = m_grid_[r - 1]; + } + m_grid_[0].fill(0); + ++score_; + updateScore(score_); + } + } +} diff --git a/tetrisgrid.h b/tetrisgrid.h new file mode 100644 index 0000000..69b85f4 --- /dev/null +++ b/tetrisgrid.h @@ -0,0 +1,65 @@ +#ifndef TETRISGRID_H +#define TETRISGRID_H + +#include +#include +#include + +class TetrisGrid : public QWidget { + Q_OBJECT + Q_PROPERTY(int rows READ rows WRITE setRows NOTIFY rowsChanged) + Q_PROPERTY(int cols READ cols WRITE setCols NOTIFY colsChanged) +public: + TetrisGrid(QWidget *parent = nullptr); + int rows() const; + int cols() const; + bool isValidMove(const QVector> &shape, int rows, int cols); + void lockShape(); + void handleKeyPressEvent(QKeyEvent *event); + void setupGame(); + QColor generateRandomColor(); + +public slots: + void setRows(int rows); + void setCols(int cols); + void startGame(); + void dropShape(); + void updateScore(int newScore); + void moveShapeLeft(); + void moveShapeRight(); + void rotateShape(); + void speedFigure(); + +signals: + void rowsChanged(int rows); + void colsChanged(int cols); + void scoreChanged(int newScore); + void gameOver(); + +protected: + void paintEvent(QPaintEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; + +private: + int m_rows_; + int m_cols_; + QVector> m_grid_; + QTimer *timer_; + QVector> currentShape_; + QVector> nextShape_; + QVector> m_gridNew_; + int shapeRow_; + int shapeCol_; + int score_; + int speed_ = 500; + void drawGrid(QPainter &painter, int cellSize); + void drawShape(QPainter &painter, int cellSize); + void generateNewShape(); + void checkLines(); + void addCurrentShapeToGridNew(); + bool isCollision(); + bool locking_; + bool shapeLocked_; +}; + +#endif // TETRISGRID_H From d3c2a94f135e3aa55d7e5efda69e1526181060de Mon Sep 17 00:00:00 2001 From: Adelina Vakilova Date: Tue, 28 Nov 2023 22:17:13 +0300 Subject: [PATCH 2/4] tetrisNewAdelina --- mainwindow.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/mainwindow.cpp b/mainwindow.cpp index 65c9ed1..9b10849 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -33,13 +33,10 @@ MainWindow::MainWindow(QWidget *parent) " background-color: #2980b9;" " color: #bdc3c7;" "}"; - startButton->setStyleSheet(buttonStyle); startButton->setGraphicsEffect(shadowEffect); - helpButton->setStyleSheet(buttonStyle); helpButton->setGraphicsEffect(shadowEffect); - exitButton->setStyleSheet(buttonStyle); exitButton->setGraphicsEffect(shadowEffect); @@ -55,7 +52,6 @@ MainWindow::MainWindow(QWidget *parent) } }); - QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(tetrisGrid, Qt::AlignHCenter); layout->addWidget(scoreLabel); From 5dfab8bfe2014e556dc1cd2bd1bad747fc9e6d13 Mon Sep 17 00:00:00 2001 From: Adelina Vakilova Date: Wed, 29 Nov 2023 03:16:49 +0300 Subject: [PATCH 3/4] tetrisNEW --- mainwindow.cpp | 1 - tetrisgrid.cpp | 20 +++++++++++++++++--- tetrisgrid.h | 2 +- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/mainwindow.cpp b/mainwindow.cpp index 9b10849..6772f4f 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -44,7 +44,6 @@ MainWindow::MainWindow(QWidget *parent) connect(startButton, &QPushButton::clicked, this, &MainWindow::restartGame); connect(exitButton, &QPushButton::clicked, this, &MainWindow::exitGame); connect(tetrisGrid, SIGNAL(scoreChanged(int)), this, SLOT(updateScore(int))); - connect(tetrisGrid, SIGNAL(gameOver()), this, SLOT(exitGame())); connect(tetrisGrid, &TetrisGrid::gameOver, [=]() { if (!gameOverHandled_) { gameOverHandled_ = true; diff --git a/tetrisgrid.cpp b/tetrisgrid.cpp index 13f60d9..08b3659 100644 --- a/tetrisgrid.cpp +++ b/tetrisgrid.cpp @@ -5,7 +5,7 @@ #include TetrisGrid::TetrisGrid(QWidget *parent) - : QWidget(parent), m_rows_(20), m_cols_(10), m_gridNew_(m_rows_, QVector(m_cols_, 0)), timer_(new QTimer(this)), score_(0) { + : QWidget(parent), m_rows_(24), m_cols_(10), timer_(new QTimer(this)), score_(0) { m_grid_.resize(m_rows_, QVector(m_cols_, 0)); setFocusPolicy(Qt::StrongFocus); connect(timer_, &QTimer::timeout, this, &TetrisGrid::dropShape); @@ -137,7 +137,6 @@ void TetrisGrid::rotateShape() } void TetrisGrid::dropShape() { - if (shapeRow_ + currentShape_.size() <= m_rows_) { ++shapeRow_; if (isCollision()) { @@ -161,6 +160,7 @@ void TetrisGrid::paintEvent(QPaintEvent *event) { int cellSize = qMin(width() / m_cols_, height() / m_rows_); drawGrid(painter, cellSize); drawShape(painter, cellSize); + drawNextShape(painter, cellSize); } void TetrisGrid::drawGrid(QPainter &painter, int cellSize) { @@ -191,12 +191,26 @@ void TetrisGrid::drawShape(QPainter &painter, int cellSize) { } } +void TetrisGrid::drawNextShape(QPainter &painter, int cellSize) { + for (int i = 0; i < nextShape_.size(); ++i) { + for (int j = 0; j < nextShape_[i].size(); ++j) { + if (nextShape_[i][j] == 1) { + QColor color = Qt::red; + QBrush brush(color); + painter.setBrush(brush); + painter.fillRect((4 + j) * cellSize, (i) * cellSize, cellSize, cellSize, color); + painter.drawRect((4 + j) * cellSize, (i) * cellSize, cellSize, cellSize); + } + } + } +} + QColor TetrisGrid::generateRandomColor() { return QColor(rand() % 256, rand() % 256, rand() % 256); } void TetrisGrid::generateNewShape() { - shapeRow_ = 0; + shapeRow_ = 4; shapeCol_ = m_cols_ / 2 - 1; int type = rand() % 6; currentShape_.clear(); diff --git a/tetrisgrid.h b/tetrisgrid.h index 69b85f4..4dd911d 100644 --- a/tetrisgrid.h +++ b/tetrisgrid.h @@ -47,13 +47,13 @@ public slots: QTimer *timer_; QVector> currentShape_; QVector> nextShape_; - QVector> m_gridNew_; int shapeRow_; int shapeCol_; int score_; int speed_ = 500; void drawGrid(QPainter &painter, int cellSize); void drawShape(QPainter &painter, int cellSize); + void drawNextShape(QPainter &painter, int cellSize); void generateNewShape(); void checkLines(); void addCurrentShapeToGridNew(); From ab34839b9691101914873236f28640abe5ef9fcc Mon Sep 17 00:00:00 2001 From: Adelina Vakilova Date: Tue, 5 Dec 2023 11:12:30 +0300 Subject: [PATCH 4/4] tetris2new --- mainwindow.cpp | 56 ++++++++++----------- mainwindow.h | 19 +++---- tetrisgrid.cpp | 133 ++++++++++++++++++++++++------------------------- tetrisgrid.h | 34 ++++++------- 4 files changed, 118 insertions(+), 124 deletions(-) diff --git a/mainwindow.cpp b/mainwindow.cpp index 6772f4f..2208300 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -7,12 +7,12 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), score_(0) { - gameOverHandled_ = false; - tetrisGrid = new TetrisGrid(this); - startButton =new QPushButton("Начать новую игру", this); - exitButton = new QPushButton("Выход", this); - scoreLabel = new QLabel("Счетчик очков: 0", this); - helpButton = new QPushButton("Справка", this); + isGameOverHandled_ = false; + tetrisGrid_ = new TetrisGrid(this); + startButton_ =new QPushButton("Начать новую игру", this); + exitButton_ = new QPushButton("Выход", this); + scoreLabel_ = new QLabel("Счетчик очков: 0", this); + helpButton_ = new QPushButton("Справка", this); qApp->setStyle(QStyleFactory::create("Fusion")); QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this); @@ -33,30 +33,30 @@ MainWindow::MainWindow(QWidget *parent) " background-color: #2980b9;" " color: #bdc3c7;" "}"; - startButton->setStyleSheet(buttonStyle); - startButton->setGraphicsEffect(shadowEffect); - helpButton->setStyleSheet(buttonStyle); - helpButton->setGraphicsEffect(shadowEffect); - exitButton->setStyleSheet(buttonStyle); - exitButton->setGraphicsEffect(shadowEffect); + startButton_->setStyleSheet(buttonStyle); + startButton_->setGraphicsEffect(shadowEffect); + helpButton_->setStyleSheet(buttonStyle); + helpButton_->setGraphicsEffect(shadowEffect); + exitButton_->setStyleSheet(buttonStyle); + exitButton_->setGraphicsEffect(shadowEffect); - connect(helpButton, &QPushButton::clicked, this, &MainWindow::showHelp); - connect(startButton, &QPushButton::clicked, this, &MainWindow::restartGame); - connect(exitButton, &QPushButton::clicked, this, &MainWindow::exitGame); - connect(tetrisGrid, SIGNAL(scoreChanged(int)), this, SLOT(updateScore(int))); - connect(tetrisGrid, &TetrisGrid::gameOver, [=]() { - if (!gameOverHandled_) { - gameOverHandled_ = true; + connect(helpButton_, &QPushButton::clicked, this, &MainWindow::showHelp); + connect(startButton_, &QPushButton::clicked, this, &MainWindow::restartGame); + connect(exitButton_, &QPushButton::clicked, this, &MainWindow::exitGame); + connect(tetrisGrid_, SIGNAL(scoreChanged(int)), this, SLOT(updateScore(int))); + connect(tetrisGrid_, &TetrisGrid::gameOver, [=]() { + if (!isGameOverHandled_) { + isGameOverHandled_ = true; exitGame(); } }); QVBoxLayout *layout = new QVBoxLayout; - layout->addWidget(tetrisGrid, Qt::AlignHCenter); - layout->addWidget(scoreLabel); - layout->addWidget(startButton); - layout->addWidget(helpButton); - layout->addWidget(exitButton); + layout->addWidget(tetrisGrid_, Qt::AlignHCenter); + layout->addWidget(scoreLabel_); + layout->addWidget(startButton_); + layout->addWidget(helpButton_); + layout->addWidget(exitButton_); QWidget *centralWidget = new QWidget(this); centralWidget->setLayout(layout); @@ -80,7 +80,7 @@ void MainWindow::showHelp() { } void MainWindow::restartGame() { - tetrisGrid->startGame(); + tetrisGrid_->startGame(); setupGame(); } @@ -91,7 +91,7 @@ void MainWindow::startGame() { } void MainWindow::exitGame() { - gameOverHandled_ = true; + isGameOverHandled_ = true; QMessageBox messageBox; messageBox.setWindowTitle("Игра окончена"); messageBox.setText("Игра завершена. Набрано очков: " + QString::number(score_)); @@ -102,11 +102,11 @@ void MainWindow::exitGame() { void MainWindow::updateScore(int newScore) { score_ = newScore; - scoreLabel->setText("Счетчик очков: " + QString::number(score_)); + scoreLabel_->setText("Счетчик очков: " + QString::number(score_)); } void MainWindow::keyPressEvent(QKeyEvent *event) { - tetrisGrid->handleKeyPressEvent(event); + tetrisGrid_->handleKeyPressEvent(event); } void MainWindow::setupGame() {} diff --git a/mainwindow.h b/mainwindow.h index 275270c..d600a8b 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -6,8 +6,7 @@ #include #include "tetrisgrid.h" -class MainWindow : public QMainWindow -{ +class MainWindow : public QMainWindow { Q_OBJECT public: @@ -15,14 +14,14 @@ class MainWindow : public QMainWindow ~MainWindow(); private: - TetrisGrid *tetrisGrid; - QPushButton *startButton; - QPushButton *exitButton; - QPushButton *helpButton; - QLabel *scoreLabel; void setupGame(); int score_; - bool gameOverHandled_ = false; + bool isGameOverHandled_ = false; + TetrisGrid *tetrisGrid_; + QPushButton *startButton_; + QPushButton *exitButton_; + QPushButton *helpButton_; + QLabel *scoreLabel_; private slots: void startGame(); @@ -31,10 +30,8 @@ private slots: void restartGame(); void showHelp(); -public slots: +protected: void keyPressEvent(QKeyEvent *event); - - }; #endif // MAINWINDOW_H diff --git a/tetrisgrid.cpp b/tetrisgrid.cpp index 08b3659..1b22ee1 100644 --- a/tetrisgrid.cpp +++ b/tetrisgrid.cpp @@ -5,8 +5,8 @@ #include TetrisGrid::TetrisGrid(QWidget *parent) - : QWidget(parent), m_rows_(24), m_cols_(10), timer_(new QTimer(this)), score_(0) { - m_grid_.resize(m_rows_, QVector(m_cols_, 0)); + : QWidget(parent), mRows_(24), mColumns_(10), timer_(new QTimer(this)), score_(0) { + mGrid_.resize(mRows_, QVector(mColumns_, 0)); setFocusPolicy(Qt::StrongFocus); connect(timer_, &QTimer::timeout, this, &TetrisGrid::dropShape); timer_->setInterval(speed_); @@ -18,13 +18,13 @@ void TetrisGrid::addCurrentShapeToGridNew() { for (int j = 0; j < currentShape_[i].size(); ++j) { if (currentShape_[i][j] == 1) { int gridRow = shapeRow_ + i; - int gridCol = shapeCol_ + j; - if (gridRow >= 0 && gridRow < m_rows_ && gridCol >= 0 && gridCol < m_cols_) { - if (gridRow <= 0) { + int gridColumn = shapeColumn_ + j; + if (gridRow >= 0 && gridRow < mRows_ && gridColumn >= 0 && gridColumn < mColumns_) { + if (gridRow <= 4) { emit gameOver(); } else - m_grid_[gridRow][gridCol] = 1; + mGrid_[gridRow][gridColumn] = 1; } } } @@ -32,8 +32,8 @@ void TetrisGrid::addCurrentShapeToGridNew() { } void TetrisGrid::setupGame() { - m_grid_.clear(); - m_grid_.resize(m_rows_, QVector(m_cols_, 0)); + mGrid_.clear(); + mGrid_.resize(mRows_, QVector(mColumns_, 0)); score_ = 0; updateScore(score_); generateNewShape(); @@ -45,32 +45,32 @@ void TetrisGrid::speedFigure(){ } int TetrisGrid::rows() const { - return m_rows_; + return mRows_; } -int TetrisGrid::cols() const { - return m_cols_; +int TetrisGrid::columns() const { + return mColumns_; } void TetrisGrid::setRows(int rows) { - if (m_rows_ != rows) { - m_rows_ = rows; - m_grid_.resize(m_rows_); - for (auto &row : m_grid_) { - row.resize(m_cols_); + if (mRows_ != rows) { + mRows_ = rows; + mGrid_.resize(mRows_); + for (auto &row : mGrid_) { + row.resize(mColumns_); } - emit rowsChanged(m_rows_); + emit rowsChanged(mRows_); update(); } } -void TetrisGrid::setCols(int cols) { - if (m_cols_ != cols) { - m_cols_ = cols; - for (auto &row_ : m_grid_) { - row_.resize(m_cols_); +void TetrisGrid::setColumns(int columns) { + if (mColumns_ != columns) { + mColumns_ = columns; + for (auto &row_ : mGrid_) { + row_.resize(mColumns_); } - emit colsChanged(m_cols_); + emit columnsChanged(mColumns_); update(); } } @@ -80,37 +80,36 @@ void TetrisGrid::startGame() { timer_->start(); } - void TetrisGrid::moveShapeLeft() { - if (shapeCol_ > 0) { - --shapeCol_; - if (!isValidMove(currentShape_, shapeRow_, shapeCol_)) { - ++shapeCol_; + if (shapeColumn_ > 0) { + --shapeColumn_; + if (!isValidMove(currentShape_, shapeRow_, shapeColumn_)) { + ++shapeColumn_; } update(); } } void TetrisGrid::moveShapeRight() { - if (shapeCol_ + currentShape_[0].size() < m_cols_) { - ++shapeCol_; - if (!isValidMove(currentShape_, shapeRow_, shapeCol_)) { - --shapeCol_; + if (shapeColumn_ + currentShape_[0].size() < mColumns_) { + ++shapeColumn_; + if (!isValidMove(currentShape_, shapeRow_, shapeColumn_)) { + --shapeColumn_; } update(); } } -bool TetrisGrid::isValidMove(const QVector> &shape, int rows, int cols) { +bool TetrisGrid::isValidMove(const QVector> &shape, int rows, int columns) { for (int i = 0; i < shape.size(); ++i) { for (int j = 0; j < shape[i].size(); ++j) { if (shape[i][j] == 1) { int gridRow = rows + i; - int gridCol = cols + j; - if (gridRow < 0 || gridRow >= m_rows_ || gridCol < 0 || gridCol >= m_cols_) { + int gridColumn = columns + j; + if (gridRow < 0 || gridRow >= mRows_ || gridColumn < 0 || gridColumn >= mColumns_) { return false; } - if (m_grid_[gridRow][gridCol] == 1) { + if (mGrid_[gridRow][gridColumn] == 1) { return false; } } @@ -122,22 +121,22 @@ bool TetrisGrid::isValidMove(const QVector> &shape, int rows, int c void TetrisGrid::rotateShape() { QVector> rotatedShape; - QVector temp; - for (int j = currentShape_[0].size()-1; j >= 0; --j) { - temp.clear(); + QVector currentRow; + for (int j = currentShape_[0].size() - 1; j >= 0; --j) { + currentRow.clear(); for (int i = 0; i < currentShape_.size(); ++i) { - temp.append(currentShape_[i][j]); + currentRow.append(currentShape_[i][j]); } - rotatedShape.append(temp); + rotatedShape.append(currentRow); } - if (isValidMove(rotatedShape, shapeRow_, shapeCol_)) { + if (isValidMove(rotatedShape, shapeRow_, shapeColumn_)) { currentShape_ = rotatedShape; update(); } } void TetrisGrid::dropShape() { - if (shapeRow_ + currentShape_.size() <= m_rows_) { + if (shapeRow_ + currentShape_.size() <= mRows_) { ++shapeRow_; if (isCollision()) { --shapeRow_; @@ -157,21 +156,21 @@ void TetrisGrid::updateScore(int newScore) { void TetrisGrid::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); - int cellSize = qMin(width() / m_cols_, height() / m_rows_); + int cellSize = qMin(width() / mColumns_, height() / mRows_); drawGrid(painter, cellSize); drawShape(painter, cellSize); drawNextShape(painter, cellSize); } void TetrisGrid::drawGrid(QPainter &painter, int cellSize) { - for (int row = 0; row < m_rows_; ++row) { - for (int col = 0; col < m_cols_; ++col) { - if (m_grid_[row][col] == 1) { + for (int row = 0; row < mRows_; ++row) { + for (int column = 0; column < mColumns_; ++column) { + if (mGrid_[row][column] == 1) { QColor color = generateRandomColor(); - painter.fillRect(col * cellSize, row * cellSize, cellSize, cellSize, color); + painter.fillRect(column * cellSize, row * cellSize, cellSize, cellSize, color); } else { - painter.fillRect(col * cellSize, row * cellSize, cellSize, cellSize, Qt::white); - painter.drawRect(col * cellSize, row * cellSize, cellSize, cellSize); + painter.fillRect(column * cellSize, row * cellSize, cellSize, cellSize, Qt::white); + painter.drawRect(column * cellSize, row * cellSize, cellSize, cellSize); } } } @@ -184,8 +183,8 @@ void TetrisGrid::drawShape(QPainter &painter, int cellSize) { QColor color = generateRandomColor(); QBrush brush(color); painter.setBrush(brush); - painter.fillRect((shapeCol_ + j) * cellSize, (shapeRow_ + i) * cellSize, cellSize, cellSize, color); - painter.drawRect((shapeCol_ + j) * cellSize, (shapeRow_ + i) * cellSize, cellSize, cellSize); + painter.fillRect((shapeColumn_ + j) * cellSize, (shapeRow_ + i) * cellSize, cellSize, cellSize, color); + painter.drawRect((shapeColumn_ + j) * cellSize, (shapeRow_ + i) * cellSize, cellSize, cellSize); } } } @@ -211,7 +210,7 @@ QColor TetrisGrid::generateRandomColor() { void TetrisGrid::generateNewShape() { shapeRow_ = 4; - shapeCol_ = m_cols_ / 2 - 1; + shapeColumn_ = mColumns_ / 2 - 1; int type = rand() % 6; currentShape_.clear(); currentShape_ = nextShape_; @@ -249,16 +248,16 @@ void TetrisGrid::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Left: - emit moveShapeLeft(); + moveShapeLeft(); break; case Qt::Key_Right: - emit moveShapeRight(); + moveShapeRight(); break; case Qt::Key_Up: - emit rotateShape(); + rotateShape(); break; case Qt::Key_Down: - emit speedFigure(); + speedFigure(); break; default: QWidget::keyPressEvent(event); @@ -270,8 +269,8 @@ bool TetrisGrid::isCollision() { for (int j = 0; j < currentShape_[i].size(); ++j) { if (currentShape_[i][j] == 1) { int gridRow = shapeRow_ + i; - int gridCol = shapeCol_ + j; - if (gridRow < 0 || gridRow >= m_rows_ || gridCol < 0 || gridCol >= m_cols_ || m_grid_[gridRow][gridCol] == 1) { + int gridColumn = shapeColumn_ + j; + if (gridRow < 0 || gridRow >= mRows_ || gridColumn < 0 || gridColumn >= mColumns_ || mGrid_[gridRow][gridColumn] == 1) { return true; } } @@ -282,19 +281,19 @@ bool TetrisGrid::isCollision() { void TetrisGrid::checkLines() { - for (int row = m_rows_ - 1; row >= 0; --row) { - bool lineFilled = true; - for (int col = 0; col < m_cols_; ++col) { - if (m_grid_[row][col] == 0) { - lineFilled = false; + for (int row = mRows_ - 1; row >= 0; --row) { + bool isLineFilled = true; + for (int column = 0; column < mColumns_; ++column) { + if (mGrid_[row][column] == 0) { + isLineFilled = false; break; } } - if (lineFilled) { + if (isLineFilled) { for (int r = row; r > 0; --r) { - m_grid_[r] = m_grid_[r - 1]; + mGrid_[r] = mGrid_[r - 1]; } - m_grid_[0].fill(0); + mGrid_[0].fill(0); ++score_; updateScore(score_); } diff --git a/tetrisgrid.h b/tetrisgrid.h index 4dd911d..b476393 100644 --- a/tetrisgrid.h +++ b/tetrisgrid.h @@ -8,20 +8,20 @@ class TetrisGrid : public QWidget { Q_OBJECT Q_PROPERTY(int rows READ rows WRITE setRows NOTIFY rowsChanged) - Q_PROPERTY(int cols READ cols WRITE setCols NOTIFY colsChanged) + Q_PROPERTY(int columns READ columns WRITE setColumns NOTIFY columnsChanged) public: - TetrisGrid(QWidget *parent = nullptr); int rows() const; - int cols() const; - bool isValidMove(const QVector> &shape, int rows, int cols); + int columns() const; + bool isValidMove(const QVector> &shape, int rows, int columns); void lockShape(); void handleKeyPressEvent(QKeyEvent *event); void setupGame(); + TetrisGrid(QWidget *parent = nullptr); QColor generateRandomColor(); public slots: void setRows(int rows); - void setCols(int cols); + void setColumns(int columns); void startGame(); void dropShape(); void updateScore(int newScore); @@ -32,7 +32,7 @@ public slots: signals: void rowsChanged(int rows); - void colsChanged(int cols); + void columnsChanged(int columns); void scoreChanged(int newScore); void gameOver(); @@ -41,16 +41,6 @@ public slots: void keyPressEvent(QKeyEvent *event) override; private: - int m_rows_; - int m_cols_; - QVector> m_grid_; - QTimer *timer_; - QVector> currentShape_; - QVector> nextShape_; - int shapeRow_; - int shapeCol_; - int score_; - int speed_ = 500; void drawGrid(QPainter &painter, int cellSize); void drawShape(QPainter &painter, int cellSize); void drawNextShape(QPainter &painter, int cellSize); @@ -58,8 +48,16 @@ public slots: void checkLines(); void addCurrentShapeToGridNew(); bool isCollision(); - bool locking_; - bool shapeLocked_; + QVector> mGrid_; + QVector> currentShape_; + QVector> nextShape_; + QTimer *timer_; + int mRows_; + int mColumns_; + int shapeRow_; + int shapeColumn_; + int score_; + int speed_ = 500; }; #endif // TETRISGRID_H