Proyecto QT juego de combate real de convertir monedas de oro

Tabla de contenido

Uno, logra el efecto

En segundo lugar, el proceso de realización

1. Cree un proyecto y agregue recursos del proyecto

2. Cree la escena principal (mainscene.cpp / .h)

3. Botón de inicio personalizado (mypushbutton.cpp / .h)

4. Cree una escena de nivel de selección (chooselevelscene.cpp / .h)

5. Crea una escena de lanzamiento de moneda (playscene.cpp / .h)

6. Cree monedas de oro (mycoin.cpp / .h)

7. La visualización predeterminada de cada nivel

8. Efecto especial de lanzamiento de una moneda de oro

9. Lanza las monedas de oro circundantes

10. Juzga la victoria

11. Efectos de sonido añadidos

12. Optimización de proyectos

13. Empaquetado de proyectos y expansión de juegos

3. Código fuente del programa y ruta de recursos de imágenes


Uno, logra el efecto

En segundo lugar, el proceso de realización

1. Cree un proyecto y agregue recursos del proyecto

Los siguientes son los recursos de imágenes requeridos y el directorio del proyecto completo

2. Cree la escena principal (mainscene.cpp / .h)

Establecer tamaño fijo, título, icono, fondo, elemento de salida de la barra de menú, botón de inicio, etc. 

#include "mainscene.h"
#include "ui_mainscene.h"
#include "QPainter"
#include "QPixmap"
#include "mypushbutton.h"
#include "QDebug"
#include "chooselevelscene.h"
#include "QTimer"
#include "QSound"//多媒体模块下的音效头文件

mainscene::mainscene(QWidget *parent) : QMainWindow(parent), ui(new Ui::mainscene)
{
    ui->setupUi(this);

    //配置主场景
    setFixedSize(320,588);//设置固定大小
    setWindowIcon(QIcon(":/res/Coin0001.png"));//设置图标
    setWindowTitle("翻金币主场景");//设置标题

    //菜单栏-->退出选项 的实现
    connect(ui->actionQuit, &QAction::triggered, [=](){
        this->close();
    });

    //准备开始按钮的音效
    QSound *startsound = new QSound(":/res/TapButtonSound.wav", this);

    //实例化选择关卡场景
    chooseScene = new ChooseLevelScene;
    //监听选择关卡的返回按钮信号
    connect(chooseScene, &ChooseLevelScene::chooseSceneBack, this, [=](){
        chooseScene->hide();//隐藏选择关卡
        this->setGeometry(chooseScene->geometry());//由选择场景返回时,设置主场景的位置,不然会乱动
        this->show();//重新显示主场景
    });

    //开始按钮,使用自定义的PushButton
    MyPushbutton *startbtn = new MyPushbutton(":/res/MenuSceneStartButton.png");
    startbtn->setParent(this);
    startbtn->move(this->width()*0.5 - startbtn->width()*0.5, this->height()*0.7);
    connect(startbtn, &MyPushbutton::clicked, [=](){
        qDebug() <<"点击了开始";
        startbtn->zoom1();
        startbtn->zoom2();

        //播放音效
        startsound->play();
        //startsound->setLoops(-1);//设置循环,如果是-1表示无限循环

        //延时进入选择关卡,才能看见弹跳的效果
        QTimer::singleShot(100,this,[=](){
            this->hide();//隐藏主场景
            chooseScene->setGeometry(this->geometry());//进入选择场景时,设置选择场景的位置,不然会乱动
            chooseScene->show();//显示选择关卡的场景
        });
    });
}

mainscene::~mainscene()
{
    delete ui;
}

//重写paintEvent事件,画背景图
void mainscene::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QPixmap pix;

    pix.load(":/res/PlayLevelSceneBg.png");
    painter.drawPixmap(0,0,this->width(), this->height(), pix);

    pix.load(":/res/Title.png");
    pix = pix.scaled(pix.width()*0.5, pix.height()*0.5);//对图片进行缩放
    painter.drawPixmap(10,30,pix);
}

3. Botón de inicio personalizado (mypushbutton.cpp / .h)

1. Encapsular un botón personalizado MyPushButton

2. Constructor (imagen de visualización predeterminada, imagen que se muestra después de presionar)

3. Botón de inicio de prueba

4. Empiece a hacer efectos especiales

5. Zoom1 salta hacia abajo

6, zoom2 saltar

#include "mypushbutton.h"
#include "QDebug"
#include "QPropertyAnimation"

//构造函数,参数:正常显示的图片路径 按下后显示的图片路径
MyPushbutton::MyPushbutton(QString normalImg, QString pressImg)
{
    this->normalImgPath = normalImg;
    this->pressImgPath = pressImg;

    QPixmap pix;
    bool ret = pix.load(normalImgPath);
    if (!ret){
        qDebug() <<"图片加载失败";
        return;
    }

    //设置图片固定大小
    this->setFixedSize(pix.width(), pix.height());

    //设置不规则图片的样式
    this->setStyleSheet("QPushButton{border:0px}");

    //设置图标
    this->setIcon(pix);

    //设置图标大小
    this->setIconSize(QSize(pix.width(), pix.height()));
}

//向下跳
void MyPushbutton::zoom1()
{
    //创建动态对象
    QPropertyAnimation *animation = new QPropertyAnimation(this, "geometry");
    //设置动画时间间隔
    animation->setDuration(100);
    //起始位置
    animation->setStartValue(QRect(this->x(), this->y(), this->width(), this->height()));
    //结束位置
    animation->setEndValue(QRect(this->x(), this->y()+10, this->width(), this->height()));
    //设置弹跳曲线
    animation->setEasingCurve(QEasingCurve::OutBounce);
    //执行动画
    animation->start();
}

//向上跳
void MyPushbutton::zoom2()
{
    //创建动态对象
    QPropertyAnimation *animation = new QPropertyAnimation(this, "geometry");
    //设置动画时间间隔
    animation->setDuration(100);
    //起始位置
    animation->setStartValue(QRect(this->x(), this->y()+10, this->width(), this->height()));
    //结束位置
    animation->setEndValue(QRect(this->x(), this->y(), this->width(), this->height()));
    //设置弹跳曲线
    animation->setEasingCurve(QEasingCurve::OutBounce);
    //执行动画
    animation->start();
}


void MyPushbutton::mousePressEvent(QMouseEvent *e)
{
    if (this->pressImgPath != "")//传入的按下按钮不为空,表示需要切换图片
    {
        QPixmap pix;
        bool ret = pix.load(this->pressImgPath);
        if (!ret){
            qDebug() <<"图片加载失败";
            return;
        }
        //设置图片固定大小
        this->setFixedSize(pix.width(), pix.height());
        //设置不规则图片的样式
        this->setStyleSheet("QPushButton{border:0px}");
        //设置图标
        this->setIcon(pix);
        //设置图标大小
        this->setIconSize(QSize(pix.width(), pix.height()));
    }
    //让父类执行其他内容
    return QPushButton::mousePressEvent(e);
}

void MyPushbutton::mouseReleaseEvent(QMouseEvent *e)
{
    if (this->pressImgPath != "")//传入的按下按钮不为空,表示按下的时候切换图片了,弹起的时候需要切换回去
    {
        QPixmap pix;
        bool ret = pix.load(this->normalImgPath);
        if (!ret){
            qDebug() <<"图片加载失败";
            return;
        }
        //设置图片固定大小
        this->setFixedSize(pix.width(), pix.height());
        //设置不规则图片的样式
        this->setStyleSheet("QPushButton{border:0px}");
        //设置图标
        this->setIcon(pix);
        //设置图标大小
        this->setIconSize(QSize(pix.width(), pix.height()));
    }

    //让父类执行其他内容
    return QPushButton::mouseReleaseEvent(e);
}

4. Cree una escena de nivel de selección (chooselevelscene.cpp / .h)

1. Después de hacer clic en el botón de inicio, retrase la entrada al nivel seleccionado para ver el efecto del rebote

2. Configure la escena de nivel seleccionada (tamaño fijo, título, icono, fondo, elemento de salida de la barra de menú, botón de retorno)

3. Escriba el efecto especial del botón de retroceso: cambie el fondo después de presionar y aparecer

4. Cambiar entre la escena de inicio y la escena seleccionada: haga clic en el botón de retorno de la escena de nivel seleccionada para enviar una señal personalizada. En la escena principal, supervise la señal personalizada de la escena de nivel seleccionada, luego oculte la escena seleccionada y muestre la escena principal

5. Cree el botón de selección en el nivel de selección: use un bucle for para organizar todos los botones de la escena, establezca un QLabel en el botón para mostrar el número de niveles, QLabel establece el tamaño, la fuente, el texto de visualización, la alineación y la penetración del mouse; Evento de clic de botón

#include "chooselevelscene.h"
#include "QMenuBar"
#include "QPainter"
#include "QPixmap"
#include "QDebug"
#include "mypushbutton.h"
#include "QTimer"
#include "QLabel"
#include "QSound"

ChooseLevelScene::ChooseLevelScene(QWidget *parent) : QMainWindow(parent)
{
    //配置选择关卡场景
    this->setFixedSize(320,588);
    //设置图标
    this->setWindowIcon(QPixmap(":/res/Coin0001.png"));
    //设置标题
    this->setWindowTitle("选择关卡场景");

    //创建菜单栏
    QMenuBar *bar = menuBar();
    setMenuBar(bar);
    QMenu *startMenu = bar->addMenu("开始");//创建开始菜单项
    QAction *quitAction = startMenu->addAction("退出"); //场景退出的菜单项
    connect(quitAction, &QAction::triggered, [=](){
        this->close();
    });

    //选择关卡音效
    QSound *choosesound = new QSound(":/res/TapButtonSound.wav", this);
    //返回音效
    QSound *backsound = new QSound(":/res/BackButtonSound.wav", this);

    //创建返回按钮
    MyPushbutton *backbtn = new MyPushbutton(":/res/BackButton.png", ":/res/BackButtonSelected.png");
    backbtn->setParent(this);
    backbtn->move(this->width()-backbtn->width(), this->height()-backbtn->height());
    //点击之后返回主场景
    connect(backbtn, &MyPushbutton::clicked, [=](){
        //播放返回音效
        backsound->play();

        qDebug() <<"选择场景点击了返回按钮";
        //需要告诉主场景,选择场景返回了,主场景监听 chooseScene 的返回
        QTimer::singleShot(100, this, [=](){
            emit this->chooseSceneBack();//延时返回
        });
    });

    //场景选择按钮
    for (int i=0; i<20; i++)
    {
        //创建按钮
        MyPushbutton *menuBtn = new MyPushbutton(":/res/LevelIcon.png");
        menuBtn->setParent(this);
        menuBtn->move(25+i%4*70, 130+i/4*70);

        //创建按钮文本
        QLabel *label = new QLabel;
        label->setParent(this);
        label->setFixedSize(menuBtn->width(), menuBtn->height());
        label->setText(QString::number(i+1));
        label->move(25+i%4*70, 130+i/4*70);
        label->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); //设置文字对齐方式
        label->setAttribute(Qt::WA_TransparentForMouseEvents); //设置让鼠标进行穿透!!!!这样menuBtn才能收到点击事件

        //监听每个按钮的点击事件
        connect(menuBtn, &MyPushbutton::clicked, [=](){
            //播放音效
            choosesound->play();

            QString str = QString("选择的关卡是 %1 关").arg(i+1);
            qDebug() <<str.toUtf8().data();

            //进入到游戏场景
            this->hide();//隐藏选择场景
            this->play = new PlayScene(i+1);
            this->play->setGeometry(this->geometry());//进入翻金币场景时,设置其位置
            this->play->show();//进入游戏场景

            //监听游戏场景的返回信号
            connect(play, &PlayScene::chooseSceneBack, [=](){
                this->setGeometry(this->play->geometry());//翻金币场景返回时,设置选择场景的位置
                this->show();//展示选择场景,这里不会立马显示出来????????
                delete this->play;//删除翻金币场景
                this->play = NULL;
            });
        });
    }
}

//重写绘图事件,绘制背景
void ChooseLevelScene::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QPixmap pix;

    //加载背景
    pix.load(":/res/OtherSceneBg.png");
    painter.drawPixmap(0,0,this->width(),this->height(),pix);

    //加载标题
    pix.load(":/res/Title.png");
    //pix = pix.scaled(pix.width()*0.5, pix.height()*0.5);//对图片进行缩放
    painter.drawPixmap(10,30,pix);
}

5. Crea una escena de lanzamiento de moneda (playscene.cpp / .h)

1. Después de hacer clic en el botón de selección de nivel, ingrese a la escena del juego de lanzamiento de monedas

2. Configure la escena del juego (tamaño fijo, título, icono, fondo, elemento de salida de la barra de menú, botón de retorno, etiqueta de visualización del número de nivel)

#include "playscene.h"
#include "QMenuBar"
#include "QPainter"
#include "QPixmap"
#include "QDebug"
#include "mypushbutton.h"
#include "QTimer"
#include "QLabel"
#include "mycoin.h"
#include "dataconfig.h"
#include <QPropertyAnimation>
#include <QSound>

//PlayScene::PlayScene(QWidget *parent) : QMainWindow(parent)
//{

//}

PlayScene::PlayScene(int levelNum)
{
    QString str = QString("进入了第 %1 关").arg(levelNum);
    qDebug() <<str.toUtf8().data();
    this->levelIndex = levelNum;

    //初始化游戏场景
    this->setFixedSize(320,588);
    this->setWindowIcon(QPixmap(":/res/Coin0001.png"));
    this->setWindowTitle("翻金币场景");

    //创建菜单栏
    QMenuBar *bar = menuBar();
    setMenuBar(bar);
    QMenu *startMenu = bar->addMenu("开始");//创建开始菜单
    QAction *quitAction = startMenu->addAction("退出"); //场景退出的菜单项
    connect(quitAction, &QAction::triggered, [=](){
        this->close();
    });

    //胜利的音效
    QSound *winsound = new QSound(":/res/LevelWinSound.wav", this);
    //翻金币音效
    QSound *flipsound = new QSound(":/res/ConFlipSound.wav", this);
    //返回音效
    QSound *backsound = new QSound(":/res/BackButtonSound.wav", this);


    //创建返回按钮
    MyPushbutton *backbtn = new MyPushbutton(":/res/BackButton.png", ":/res/BackButtonSelected.png");
    backbtn->setParent(this);
    backbtn->move(this->width()-backbtn->width(), this->height()-backbtn->height());
    //点击之后返回选择场景
    connect(backbtn, &MyPushbutton::clicked, [=](){
        //播放返回音效
        backsound->play();

        qDebug() <<"翻金币场景点击了返回按钮";
        //需要告诉选择场景,翻金币场景返回了,选择d场景监听 chooseScene 的返回
        QTimer::singleShot(10, this, [=](){
            emit this->chooseSceneBack();//延时返回
        });
    });

    //创建显示关卡的文本
    QLabel *label = new QLabel;
    QFont font;
    font.setFamily("华文新魏");
    font.setPointSize(20);
    QString str1 = QString("Level: %1").arg(this->levelIndex);
    label->setParent(this);
    label->setFont(font);
    label->setText(str1);
    label->setGeometry(30, this->height()-50, 130, 50);

    //初始化每个关卡的二维数组,记录金币的正反面状态
    dataconfig config;
    for (int i=0; i<4; i++)
    {
        for (int j=0; j<4; j++)
        {
            this->gameArray[i][j] = config.mData[this->levelIndex][i][j];
        }
    }

    //胜利图片显示
    QLabel *winLabel = new QLabel;
    QPixmap tmppix;
    tmppix.load(":/res/LevelCompletedDialogBg.png");
    winLabel->setGeometry(0,0,tmppix.width(),tmppix.height());
    winLabel->setPixmap(tmppix);
    winLabel->setParent(this);
    winLabel->move((this->width()-tmppix.width())*0.5, -tmppix.height());

    //显示金币
    for (int i=0; i<4; i++)
    {
        for (int j=0; j<4; j++)
        {
            //显示金币的背景图片
            QPixmap pix = QPixmap(":/res/BoardNode.png");
            QLabel *label = new QLabel;
            label->setGeometry(0,0,pix.width(),pix.height());
            label->setPixmap(pix);
            label->setParent(this);
            label->move(40+i*60, 200+j*60);

            //创建金币
            QString str;
            if (this->gameArray[i][j] == 1){
                str = ":/res/Coin0001.png";
            } else {
                str = ":/res/Coin0008.png";
            }
            MyCoin *coin = new MyCoin(str);
            coin->setParent(this);
            coin->move(44+i*60, 205+j*60);

            //给金币的属性赋值
            coin->posX = i;//记录X坐标
            coin->posY = j;//记录y坐标
            coin->flag = gameArray[i][j];//记录正反标志 1正面 0反面

            //记录金币的句柄,以便后期的维护
            this->coinbtns[i][j] = coin;

            //监听金币按钮的点击事件,进行翻转
            connect(coin, &MyCoin::clicked, [=](){
                //播放翻金币音效
                flipsound->play();

                //点击金币后,在翻金币前,先禁用其他金币的点击响应,否则手速快会出现bug
                for (int i=0; i<4; i++)
                {
                    for (int j=0; j<4; j++)
                    {
                        this->coinbtns[i][j]->isWin = true;
                    }
                }

                //翻转点击的金币
                coin->changeFlag();
                this->gameArray[coin->posX][coin->posY] = (this->gameArray[coin->posX][coin->posY] == 0)?1:0;

                //延时 翻转周围金币
                QTimer::singleShot(300, this, [=](){
                    if (coin->posX+1 <= 3)//翻转右侧金币
                    {
                        this->coinbtns[coin->posX+1][coin->posY]->changeFlag();
                        this->gameArray[coin->posX+1][coin->posY] = (this->gameArray[coin->posX+1][coin->posY] == 0)?1:0;
                    }
                    if (coin->posX-1 >= 0)//翻转左侧金币
                    {
                        this->coinbtns[coin->posX-1][coin->posY]->changeFlag();
                        this->gameArray[coin->posX-1][coin->posY] = (this->gameArray[coin->posX-1][coin->posY] == 0)?1:0;
                    }
                    if (coin->posY-1 >= 0)//翻转上侧金币
                    {
                        this->coinbtns[coin->posX][coin->posY-1]->changeFlag();
                        this->gameArray[coin->posX][coin->posY-1] = (this->gameArray[coin->posX][coin->posY-1] == 0)?1:0;
                    }
                    if (coin->posY+1 <= 3)//翻转下侧金币
                    {
                        this->coinbtns[coin->posX][coin->posY+1]->changeFlag();
                        this->gameArray[coin->posX][coin->posY+1] = (this->gameArray[coin->posX][coin->posY+1] == 0)?1:0;
                    }

                    //翻转完所有金币后,才启用其他金币的点击响应,否则手速快会出现bug
                    for (int i=0; i<4; i++)
                    {
                        for (int j=0; j<4; j++)
                        {
                            this->coinbtns[i][j]->isWin = false;
                        }
                    }

                    //判断是否胜利
                    this->isWin = true;
                    for (int i=0; i<4; i++)
                    {
                        for (int j=0; j<4; j++)
                        {
                            if (this->gameArray[i][j] == false)
                            {
                                this->isWin = false;
                                break;
                            }
                        }
                    }
                    if (this->isWin == true)
                    {
                        //播放胜利音效
                        winsound->play();

                        qDebug() <<"游戏胜利";

                        //将胜利的图片降下来
                        QPropertyAnimation *animation = new QPropertyAnimation(winLabel, "geometry");
                        //设置动画时间间隔
                        animation->setDuration(1000);
                        //起始位置
                        animation->setStartValue(QRect(winLabel->x(), winLabel->y(), winLabel->width(), winLabel->height()));
                        //结束位置
                        animation->setEndValue(QRect(winLabel->x(), winLabel->y()+110, winLabel->width(), winLabel->height()));
                        //设置缓和曲线
                        animation->setEasingCurve(QEasingCurve::OutBounce);
                        //执行动画
                        animation->start();

                        //胜利后 将每个btn的标志都改为true,再点击按钮,不做响应
                        for (int i=0; i<4; i++)
                        {
                            for (int j=0; j<4; j++)
                            {
                                this->coinbtns[i][j]->isWin = true;
                            }
                        }
                    }

                });
            });
        }
    }
}
void PlayScene::paintEvent(QPaintEvent *)
{
    QPixmap pix;
    QPainter painter(this);

    //加载背景
    pix.load(":/res/PlayLevelSceneBg.png");
    painter.drawPixmap(0,0,this->width(),this->height(),pix);

    //加载标题
    pix.load(":/res/Title.png");
    pix = pix.scaled(pix.width()*0.5, pix.height()*0.5);//对图片进行缩放
    painter.drawPixmap(10,30,pix);
}

6. Cree monedas de oro (mycoin.cpp / .h)

1. Pon en juego la imagen de fondo de la moneda de oro.

2. Cree la clase de botón de moneda personalizada MyCoin

3. En el constructor MyCoin :: MyCoin (QString btnImg), pase las monedas de oro que se muestran por defecto

4. Crea todos los botones de monedas de oro en playScene

#include "mycoin.h"
#include "QString"
#include "QDebug"
#include "QPixmap"
#include "QPushButton"

//MyCoin::MyCoin(QWidget *parent) : QWidget(parent)
//{

//}


MyCoin::MyCoin(QString btnImg)
{
    QPixmap pix;
    bool ret = pix.load(btnImg);
    if (!ret)
    {
        QString str = QString("图片 %1 加载失败").arg(btnImg);
        qDebug() <<str;
        return;
    }

    this->setFixedSize(pix.width(), pix.height());
    this->setStyleSheet("QPushButton{border:0px}");
    this->setIcon(pix);
    this->setIconSize(QSize(pix.width(), pix.height()));

    //初始化定时器对象
    timer1 = new QTimer(this);
    timer2 = new QTimer(this);

    //监听正面翻反面(金币翻成银币)的信号,并且翻转金币
    connect(timer1, &QTimer::timeout, [=](){
        QPixmap pix;
        QString str = QString(":/res/Coin000%1.png").arg(this->min++);
        bool ret = pix.load(str);
        if (!ret){
            QString str = QString("图片 %1 加载失败").arg(str);
            qDebug() <<str;
            return;
        }
        this->setFixedSize(pix.width(), pix.height());
        this->setStyleSheet("QPushButton{border:0px}");
        this->setIcon(pix);
        this->setIconSize(QSize(pix.width(), pix.height()));
        if (this->min > this->max)
        {
            this->min = 1;
            timer1->stop();
            this->isAnimation = false;
        }
    });

    //监听反面翻正面(银币翻成金币)的信号,并且翻转金币
    connect(timer2, &QTimer::timeout, [=](){
        QPixmap pix;
        QString str = QString(":/res/Coin000%1.png").arg(this->max--);
        bool ret = pix.load(str);
        if (!ret){
            QString str = QString("图片 %1 加载失败").arg(str);
            qDebug() <<str;
            return;
        }
        this->setFixedSize(pix.width(), pix.height());
        this->setStyleSheet("QPushButton{border:0px}");
        this->setIcon(pix);
        this->setIconSize(QSize(pix.width(), pix.height()));
        if (this->max < this->min)
        {
            this->max = 8;
            timer2->stop();//翻转8次后才停止,显示整个翻转的过程
            this->isAnimation = false;
        }
    });
}

//改变正反面的标志的方法
void MyCoin::changeFlag()
{
    if (this->flag)
    {
        timer1->start(30);
        this->flag = false;
        this->isAnimation = true;//翻转开始,定时器停止翻转结束
    }
    else
    {
        timer2->start(30);
        this->flag = true;
        this->isAnimation = true;
    }
}

//重写按下事件,只有在isAnimation为false时执行,避免翻转过程中连续点击按钮
//在执行中或胜利后不再执行点击事件
void MyCoin::mousePressEvent(QMouseEvent *e)
{
    if (this->isAnimation || this->isWin)
    {
        return;
    }
    else
    {
        QPushButton::mousePressEvent(e);//交给父类处理
    }
}

7. La visualización predeterminada de cada nivel

1. Primero importe los archivos dataconfig.hy dataconfig.cpp al proyecto

2. Agregue una matriz de int gameArray [4] [4] en PlayScene para mantener el estado de las monedas de oro en cada nivel

3. Inicialice la visualización de cada nivel

8. Efecto especial de lanzamiento de una moneda de oro

1. Agregue atributos a cada moneda de oro: posX, posY, señalización de signos positivos y negativos

2. Agregue la función changeFlag () a MyCoin para modificar las banderas frontal y posterior de la bandera

3. Agregue el temporizador de giro hacia adelante1 y el temporizador de giro hacia atrás2. Después de hacer clic en la moneda de oro, si la bandera es verdadera, cambie a falso y el temporizador1 está encendido, el anverso y el reverso comenzarán a voltearse. Cada tarjeta se mostrará con un retraso de 30 ms. Se mostrará un total de 8 tarjetas. El efecto de la visualización de la animación; si la bandera se cambia de falso a verdadero y el temporizador2 está encendido, la marcha atrás comenzará a girar hacia el frente, y cada cuadro se mostrará con un retraso de 30 ms, y se mostrará un total de 8 cuadros para lograr el efecto de la visualización de la animación;

4. Para resolver el problema de que el efecto del clic rápido no es bueno, agregue isAnimation para determinar si se está realizando una animación y, al mismo tiempo, vuelva a escribir el evento mousePressEvent para responder cuando isAnimation = false para garantizar el efecto completo del giro.

9. Lanza las monedas de oro circundantes

Haga clic en la moneda de oro, después de lanzar la moneda de oro golpeada, retrase el lanzamiento de las monedas de oro circundantes

10. Juzga la victoria

1. Agregue el logotipo de isWin en PlayScene para juzgar si gana; si gana, bloquee todos los clics de las monedas de oro

2. Visualización de efectos especiales de la imagen de la victoria, cree una etiqueta de victoria para mostrar una imagen de la victoria, cuando se gane el juego, mueva la imagen al centro de la pantalla

11. Efectos de sonido añadidos

1. QSound pertenece al módulo multimedia, que debe agregarse al archivo .pro

QT + = núcleo de interfaz gráfica de usuario multimedia

2. Comience a agregar efectos de sonido (escena de inicio ---> seleccione escena, seleccione escena ---> escena de moneda de oro)

3. Agregue el efecto de sonido del botón Atrás (seleccione la escena ---> escena de inicio, gire la escena de la moneda de oro ---> seleccione la escena)

4. Se agregaron efectos de sonido para convertir monedas de oro.

5. Se agregaron efectos de sonido de victoria.

12. Optimización de proyectos

1. Las posiciones de los tres cambios de escena están configuradas para que sean las mismas, de modo que la posición de la escena no cambie después de cambiar

2. El logotipo debe tener asignado un valor inicial; de lo contrario, el sistema se inicializará aleatoriamente, lo que provocará que la moneda de oro no gire.

bool isAnimation  = false;//执行动画标志,这里一定要赋初值!!!
bool isWin = false;//判断是否胜利的标志

3. Antes de lanzar la moneda de oro, primero desactive el evento de clic del mouse de otras monedas de oro. Una vez completado el lanzamiento, habilite el evento de clic del mouse de otras monedas de oro para evitar clics rápidos. Otras monedas de oro se hacen clic durante el lanzamiento.

13. Empaquetado de proyectos y expansión de juegos

1. Seleccione la versión, compile el proyecto y genere el archivo .exe

2. Copie el archivo .exe en cualquier ruta y empaquételo para que pueda ejecutarse en cualquier computadora que no tenga el entorno QT instalado Antes de empaquetar, primero asegúrese de que haya windeployqt.exe en el directorio de instalación de QT.

3. Abra el terminal de comandos de Windows e ingrese el directorio .exe ( acceso directo: en la carpeta, haga clic en el espacio en blanco, shift + clic derecho y seleccione "abrir ventana aquí" ), ingrese windeployqt.exe [nombre de archivo .exe]

4. Una vez que la generación sea exitosa, se generarán algunos archivos en el directorio actual. Copie esta carpeta en cualquier computadora sin un entorno QT para ejecutar

3. Código fuente del programa y ruta de recursos de imágenes

La siguiente ruta es mi ruta de github, puede obtener el código fuente de todo el proyecto o puede chatear conmigo en privado para obtener recursos. Si cree que es útil, puede ayudar a señalar una pequeña estrella

https://github.com/denghengli/qt_study/tree/master/16_CoinFlip

 

 

Supongo que te gusta

Origin blog.csdn.net/m0_37845735/article/details/108437288
Recomendado
Clasificación