【Qt 教程篇】从小白进阶成Qt大神_基础篇 俄罗斯方块游戏的实现

本系列是本人实践记录
有问题欢迎探讨!

使用Qt制作俄罗斯方块游戏

本文将详细介绍如何使用Qt框架创建一款简单的俄罗斯方块游戏。我们将一步步实现游戏的基本功能,包括游戏界面、方块的移动、旋转和消除行等。

环境准备

在开始之前,请确保你已经安装了Qt开发环境。如果还没有安装,可以从Qt官方下载安装。

创建项目

首先,打开Qt Creator,新建一个Qt Widgets应用程序,并命名为TetrisGame

目录结构

TetrisGame/
├── CMakeLists.txt
├── main.cpp
├── tetrisboard.cpp
├── tetrisboard.h
└── mainwindow.ui

定义游戏界面

mainwindow.ui

使用Qt Designer添加一个QWidget作为主窗口,并命名为TetrisBoard。将其放置在主窗口中,并设置好布局。

main.cpp

创建一个简单的main函数来启动应用程序。

#include <QApplication>
#include "tetrisboard.h"

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    TetrisBoard window;
    window.resize(500, 1000);  // 调整窗口大小
    window.setWindowTitle("Tetris Game");
    window.show();
    return app.exec();
}

定义TetrisBoard

tetrisboard.h

在头文件中定义TetrisBoard类。

#ifndef TETRISBOARD_H
#define TETRISBOARD_H

#include <QWidget>
#include <QKeyEvent>
#include <QBasicTimer>
#include <QVector>

class TetrisBoard : public QWidget {
    Q_OBJECT

public:
    TetrisBoard(QWidget *parent = nullptr);
    ~TetrisBoard();

protected:
    void paintEvent(QPaintEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    void timerEvent(QTimerEvent *event) override;

private:
    enum { BoardWidth = 10, BoardHeight = 22 };
    QBasicTimer timer;
    QVector<QVector<int>> board;
    int curX, curY;
    int curShape[4][4];

    void clearBoard();
    void dropDown();
    void oneLineDown();
    void pieceDropped();
    void removeFullLines();
    void newPiece();
    bool tryMove(int newX, int newY, int newRotation);
    void drawSquare(QPainter &painter, int x, int y, int shape);
};

#endif // TETRISBOARD_H

tetrisboard.cpp

在源文件中实现TetrisBoard类的功能。

#include "tetrisboard.h"
#include <QPainter>
#include <QTimerEvent>
#include <QDebug>
#include <cstring>  // for memset

TetrisBoard::TetrisBoard(QWidget *parent)
    : QWidget(parent)
{
    setStyleSheet("background-color: black;");
    setFixedSize(500, 1000);  // 调整窗口大小
    clearBoard();
    newPiece();
    timer.start(300, this);
}

TetrisBoard::~TetrisBoard()
{
}

void TetrisBoard::clearBoard() {
    board.resize(BoardHeight);
    for (int i = 0; i < BoardHeight; ++i) {
        board[i].resize(BoardWidth);
        for (int j = 0; j < BoardWidth; ++j) {
            board[i][j] = 0;
        }
    }
}

void TetrisBoard::paintEvent(QPaintEvent *event) {
    Q_UNUSED(event);

    QPainter painter(this);
    for (int i = 0; i < BoardHeight; ++i) {
        for (int j = 0; j < BoardWidth; ++j) {
            if (board[i][j] != 0) {
                drawSquare(painter, j * 50, i * 50, board[i][j]);  // 调整方块大小
            }
        }
    }

    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (curShape[i][j] != 0) {
                drawSquare(painter, (curX + j) * 50, (curY + i) * 50, curShape[i][j]);
            }
        }
    }
}

void TetrisBoard::keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
        case Qt::Key_Left:
            tryMove(curX - 1, curY, 0);
            break;
        case Qt::Key_Right:
            tryMove(curX + 1, curY, 0);
            break;
        case Qt::Key_Down:
            dropDown();
            break;
        case Qt::Key_Up:
            // Handle rotation
            break;
        default:
            QWidget::keyPressEvent(event);
    }
    update();
}

void TetrisBoard::timerEvent(QTimerEvent *event) {
    Q_UNUSED(event);
    dropDown();
}

void TetrisBoard::dropDown() {
    if (!tryMove(curX, curY + 1, 0)) {
        pieceDropped();
    }
    update();
}

bool TetrisBoard::tryMove(int newX, int newY, int newRotation) {
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (curShape[i][j] != 0) {
                int x = newX + j;
                int y = newY + i;
                if (x < 0 || x >= BoardWidth || y >= BoardHeight || board[y][x] != 0) {
                    return false;
                }
            }
        }
    }
    curX = newX;
    curY = newY;
    return true;
}

void TetrisBoard::pieceDropped() {
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (curShape[i][j] != 0) {
                board[curY + i][curX + j] = curShape[i][j];
            }
        }
    }
    removeFullLines();
    newPiece();
    if (!tryMove(curX, curY, 0)) {
        timer.stop();
        qDebug() << "Game Over";
    }
}

void TetrisBoard::removeFullLines() {
    for (int row = 0; row < BoardHeight; ++row) {
        bool fullLine = true;
        for (int col = 0; col < BoardWidth; ++col) {
            if (board[row][col] == 0) {
                fullLine = false;
                break;
            }
        }
        if (fullLine) {
            for (int r = row; r > 0; --r) {
                for (int c = 0; c < BoardWidth; ++c) {
                    board[r][c] = board[r - 1][c];
                }
            }
            for (int c = 0; c < BoardWidth; ++c) {
                board[0][c] = 0;
            }
        }
    }
}

void TetrisBoard::newPiece() {
    curX = BoardWidth / 2 - 2;
    curY = 0;
    int tShape[4][4] = {
        {0, 1, 0, 0},
        {1, 1, 1, 0},
        {0, 0, 0, 0},
        {0, 0, 0, 0}
    };
    std::memcpy(curShape, tShape, 4 * 4 * sizeof(int));
}

void TetrisBoard::drawSquare(QPainter &painter, int x, int y, int shape) {
    QColor color;
    switch(shape) {
        case 1:
            color = QColor(255, 0, 0);
            break;
        // Define colors for other shapes
        default:
            color = QColor(255, 255, 255);
    }
    painter.fillRect(x, y, 50, 50, color);  // 调整方块大小
    painter.setPen(QColor(0, 0, 0));
    painter.drawRect(x, y, 50, 50);  // 调整方块大小
}

补充对旋转、下坠键的处理

  • 添加基本的形状旋转逻辑。我们可以通过改变方块的矩阵来旋转它。
  • 支持快速下坠功能,让方块可以快速下落到最下面一行。
bool TetrisBoard::tryMove(int newX, int newY, int newRotation) {
    int rotatedShape[4][4];
    
    // Rotate the shape
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            rotatedShape[j][3 - i] = curShape[i][j];
        }
    }
    // Check if the rotated shape can be moved to the new position
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (rotatedShape[i][j] != 0) {
                int x = newX + j;
                int y = newY + i;
                if (x < 0 || x >= BoardWidth || y >= BoardHeight || board[y][x] != 0) {
                    return false;
                }
            }
        }
    }
    std::memcpy(curShape, rotatedShape, 4 * 4 * sizeof(int));
    curX = newX;
    curY = newY;
    return true;
}

void TetrisBoard::keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
        case Qt::Key_Left:
            tryMove(curX - 1, curY, 0);
            break;
        case Qt::Key_Right:
            tryMove(curX + 1, curY, 0);
            break;
        case Qt::Key_Down:
            dropDown();
            break;
        case Qt::Key_Up:
            tryMove(curX, curY, 1);
            break;
        case Qt::Key_Space:
            while (tryMove(curX, curY + 1, 0)) {
                curY++;
            }
            pieceDropped();
            break;
        default:
            QWidget::keyPressEvent(event);
    }
    update();
}

完善游戏逻辑

TetrisBoard类中,我们需要实现各种游戏逻辑,包括方块的移动、旋转、消除行等。这些逻辑可以通过定义和管理方块的形状和状态来实现。

补全形状和初始化逻辑:

// 全局变量(形状定义)
static const int Shapes[7][4][4] = {
    { {1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} },  // I
    { {1, 1, 0, 0}, {1, 1, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} },  // O
    { {1, 1, 1, 0}, {0, 1, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} },  // T
    { {1, 0, 0, 0}, {1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} },  // L
    { {0, 0, 1, 0}, {1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} },  // J
    { {1, 1, 0, 0}, {0, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} },  // S
    { {0, 1, 1, 0}, {1, 1, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} },  // Z
};

void TetrisBoard::newPiece() {
    curX = BoardWidth / 2 - 2;
    curY = 0;
    int shapeIndex = rand() % 7; // 随机选择形状
    std::memcpy(curShape, Shapes[shapeIndex], 4 * 4 * sizeof(int));
}

运行游戏

编译并运行项目,你将看到一个简单的俄罗斯方块游戏窗口。你可以使用键盘方向键来控制方块的移动和旋转。

结语

通过本教程,我们学习了如何使用Qt框架创建一个基本的俄罗斯方块游戏。你可以在此基础上进行更多扩展和优化,使游戏更加有趣和完善。

如有任何问题或建议,欢迎留言讨论。祝你编码愉快!

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zw_Loneranger

你的鼓励是将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值