double arrow

Gameplay. cpp

#include "gameplay.h"#include <QGraphicsItem>#include <QTimer>#include <QEvent>#include <QKeyEvent> Gameplay::Gameplay(QGraphicsScene & scene, QGraphicsItem *p1, QGraphicsItem *p2, QGraphicsItem *ball, QObject *parent): QObject(parent), Scene (scene), P1 (p1), P2 (p2), Ball (ball), BallDirection (-3, -3), P1Direction(0), P2Direction(0){ Scene.setSceneRect(0, 0, 410, 330); Scene.addItem(P1); Scene.addItem(P2); Scene.addItem(Ball); P1->setPos(165, 310); P2->setPos(165, 0); Ball->setPos(150, 150); Timer = new QTimer(this); Timer->start(12); QObject::connect(Timer, SIGNAL(timeout()), this, SLOT(tick()));} void Gameplay::tick(){ qreal newX = Ball->pos().x() + BallDirection.x(); qreal newY = Ball->pos().y() + BallDirection.y(); qreal p1newx = P1->pos().x() + P1Direction; qreal p2newx = P2->pos().x() + P2Direction; if ((newX < 0) || (newX + Ball-> boundingRect ().right() > Scene.sceneRect().right())) {   BallDirection.rx() *= -1; } if ((newY < 0) || (newY + Ball-> boundingRect ().bottom() > Scene.sceneRect().bottom())) {   emit goal(newY / abs(newY));   BallDirection.ry() *= -1; } if ((p1newx < 0) || (p1newx + P1-> boundingRect ().right() > Scene.sceneRect().right())) {   P1Direction = 0; } if ((p2newx < 0) || (p2newx + P1-> boundingRect ().right() > Scene.sceneRect().right())) {   P2Direction = 0; } if ((P1-> collidesWithItem (Ball)) && (BallDirection.y() > 0)) {   BallDirection.ry() *= -1; } if ((P2-> collidesWithItem (Ball)) && (BallDirection.y() < 0)) {   BallDirection.ry() *= -1; } Ball->moveBy(BallDirection.x(), BallDirection.y()); P1->moveBy(P1Direction, 0); P2->moveBy(P2Direction, 0);} bool Gameplay:: eventFilter (QObject *target, QEvent *e){ Q_UNUSED(target); bool handled = false; if (e->type() == QEvent::KeyPress) {   QKeyEvent *keyEvent = (QKeyEvent *)e;   if (keyEvent->key() == Qt::Key_Left)   {       P1Direction = (P1Direction == 0? -5: 0);       handled = true;   }   else if (keyEvent->key() == Qt::Key_Right)   {       P1Direction = (P1Direction == 0? 5: 0);       handled = true;   }    if (keyEvent->key() == Qt::Key_A)   {       P2Direction = (P2Direction == 0? -5: 0);       handled = true;   }   else if (keyEvent->key() == Qt::Key_D)   {       P2Direction = (P2Direction == 0? 5: 0);       handled = true;   } } return handled;

}

 

 


Понравилась статья? Добавь ее в закладку (CTRL+D) и не забудь поделиться с друзьями:  



Сейчас читают про: