QT--QGraphicsView Whac-A-Mole 打地鼠(3)

QT–QGraphicsView Whac-A-Mole 打地鼠(1)
https://blog.csdn.net/weixin_43086497/article/details/104660708
QT–QGraphicsView Whac-A-Mole 打地鼠(2)
https://blog.csdn.net/weixin_43086497/article/details/104681956

单例模式

一个类,全局调用。
首先我们来完成显示分数的功能
这里我们定义一个新的类,让它专门负责发出打击老鼠的信号,让主窗口接收信号,实现更新分数的功能
如图,类名 score,
基类QObject
score.h
在这里插入图片描述
score.cpp
在这里插入图片描述
这里,score类中只有一个实例,给其他类使用
我这里instance函数名字为returnback
首先我们在打中老鼠的时候发出信号
所以在鼠标点击事件的代码更改如下:

void item::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    this->setCursor(QCursor(QPixmap(":/document/whacamolefile/picturedown.png")));

    if(this->isMouse()){
        this->setPixmap(QPixmap(":/document/whacamolefile/was_hit.png"));
        Score * score_cnt = Score::returnback();
        score_cnt->score_up();
        this->mouse = false;
    }
}

然后我们在MainWindow中添加槽 void update_score();去接收这个
mouse_hit()信号
在这里插入图片描述
槽函数内容:

void MainWindow::update_score()
{
    this->score += 10;
    this->ui->lcdNumber->display(this->score);
}

接收信号:

在这里插入图片描述
这样,显示分数的功能就完成了

开始和停止按钮

首先我们在scene类里定义两个槽函数去接收开始和停止按钮点击时发出的信号
在这里插入图片描述
两个槽函数的内容如下

void scene::game_start()
{
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            this->nightitem[i][j]->setMouse(false);
        }
    }
    this->ptimer->start(1000);
}

void scene::game_stop()
{
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            this->nightitem[i][j]->setMouse(false);
        }
    }

    for(int k=0;k<3;k++)
    {
        for(int m=0;m<3;m++)
        {
             this->nightitem[k][m]->setPic(":/document/whacamolefile/bg1.png");
             this->nightitem[k][m]->setMouse(false);
        }
    }
    this->ptimer->stop();
    score_clear();
}

在MainWindow里面进行连接

    connect(this->ui->btn_start,SIGNAL(clicked(bool)),this->sce,SLOT(game_start()));
    connect(this->ui->btn_stop,SIGNAL(clicked(bool)),this->sce,SLOT(game_stop()));

同时,当停止按钮按下的时候,分数需要清零
所以,在停止按钮按下的时候发出resetscore()信号
就是上面槽函数game_stop里的 score_clear()发出的
score_clear()的内容

void scene::score_clear()
{
    emit resetscore();
}

在MainWindow里进行连接

connect(sce,SIGNAL(resetscore() ),this,SLOT(reset_score()));

连接执行的重置分数的函数,

void MainWindow::reset_score()
{
    this->ui->lcdNumber->display(0);
}

至此,这个打地鼠就简单地完成了,当然存在很多问题,后面有时间会考虑再修改。

发布了8 篇原创文章 · 获赞 13 · 访问量 6774

猜你喜欢

转载自blog.csdn.net/weixin_43086497/article/details/104758504