基于图形视图框架的打砖块游戏

基于图形视图框架的打砖块游戏_第1张图片

密集恐惧症~


首先来创建上面的砖块,然后呢~设置一下碰撞模式

    QPixmap *Pixmap = new QPixmap(u8":/img/砖块.png");
    const int &Width = Pixmap->width();
    const int &Height = Pixmap->height();
    const int XCount = width() / Width;
    const int YCount = height() / Height -10;

    for(int x=0;xaddItem(Item);
            Item->setPos(x*Width,y*Height);
            Item->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
        }

再创建球和下面砖块

   m_Ball = new Ball(QPixmap(u8":/img/球.png"),size());
    m_Con = new Control(QPixmap(u8":/img/砖块.png"));
    m_Scene->addItem(m_Ball);
    m_Scene->addItem(m_Con);

    m_Con->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
    m_Con->setPos((width()-m_Con->pixmap().width())/2, height()-m_Con->pixmap().height());
    m_Ball->setPos((width()-m_Ball->pixmap().width())/2, m_Con->y()-m_Ball->pixmap().height());

利用时间设置球的移动

void Ball::timerEvent(QTimerEvent *event)
{
    if(m_Time->timerId() == event->timerId())
    {
        checkStage();//检测一下是否碰撞砖块
        moveBy(m_xSpeed,m_ySpeed);
        checkBaffle();//检查一下是否超出舞台
    }
}

再来就是唯一可以控制砖块的移动啦

void BlockBreaker::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_Left:
        if(m_Con->pos().x()<0)
            return;
        m_Con->moveLeft();
        if(!m_Ball->isState())
            m_Ball->moveBy(-m_Con->getSpeed(),0);
        break;

    case Qt::Key_Right:
        if(m_Con->pos().x()+m_Con->pixmap().width() > width())
            return;
        m_Con->moveRight();
        if(!m_Ball->isState())
            m_Ball->moveBy(m_Con->getSpeed(),0);
        break;

    case Qt::Key_Space:
        m_Ball->start();
    }
}



完整代码: http://download.csdn.net/detail/qq_17813937/9511229

你可能感兴趣的:(QT,图形视图框架,QT,图形视图框架,打砖块,游戏)