Add ball deletion logic
This commit is contained in:
parent
87e2a0e9aa
commit
8949830a1b
4 changed files with 35 additions and 4 deletions
12
src/ball.cpp
12
src/ball.cpp
|
@ -1,6 +1,8 @@
|
|||
#include "ball.h"
|
||||
#include <QDebug>
|
||||
#include <QRect>
|
||||
#include <QWidget>
|
||||
#include <qglobal.h>
|
||||
#include <random>
|
||||
|
||||
#define RADIUS 15
|
||||
|
@ -41,15 +43,19 @@ void Ball::timerEvent(QTimerEvent*) {
|
|||
}
|
||||
// Bottom collision (only if no longer spawning)
|
||||
if (!m_isSpawning && m_y > rct.height() - RADIUS) {
|
||||
// TODO: Destroy ball
|
||||
emit deleted(this);
|
||||
stop();
|
||||
m_parent->update();
|
||||
return;
|
||||
}
|
||||
|
||||
m_x += m_kx;
|
||||
m_y += m_ky;
|
||||
|
||||
// Once we get into the window, we're no longer "spawning"
|
||||
if (m_isSpawning && m_y < rct.width() - RADIUS)
|
||||
// Once we get above half point of the window, we're no longer "spawning"
|
||||
if (m_isSpawning && m_y < rct.height() / 2.0 - RADIUS) {
|
||||
m_isSpawning = false;
|
||||
}
|
||||
|
||||
// Update the window
|
||||
m_parent->update();
|
||||
|
|
|
@ -3,13 +3,19 @@
|
|||
|
||||
#include <QPainter>
|
||||
#include <QTimer>
|
||||
#include <qobjectdefs.h>
|
||||
|
||||
class Ball : public QTimer {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
Ball(QWidget* parent);
|
||||
|
||||
void draw(QPainter& painter);
|
||||
|
||||
signals:
|
||||
void deleted(Ball* ball);
|
||||
|
||||
protected:
|
||||
virtual void timerEvent(QTimerEvent*) override;
|
||||
|
||||
|
|
|
@ -1,9 +1,13 @@
|
|||
#include "mainwindow.h"
|
||||
#include "./ui_mainwindow.h"
|
||||
#include <QDebug>
|
||||
|
||||
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
|
||||
ui->setupUi(this);
|
||||
balls.append(std::make_shared<Ball>(this));
|
||||
|
||||
auto ball = std::make_shared<Ball>(this);
|
||||
connect(ball.get(), &Ball::deleted, this, &MainWindow::onDeleteBall);
|
||||
balls.append(ball);
|
||||
}
|
||||
|
||||
MainWindow::~MainWindow() {
|
||||
|
@ -22,3 +26,15 @@ void MainWindow::paintEvent(QPaintEvent*) {
|
|||
ball->draw(painter);
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::onDeleteBall(Ball* ball) {
|
||||
// Remove the ball from the list by checking the raw pointer
|
||||
// This will also free it (smart ptrs).
|
||||
for (auto it = balls.begin(); it != balls.end(); ++it) {
|
||||
if (it->get() == ball) {
|
||||
qDebug() << "Deleting ball";
|
||||
balls.erase(it);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,6 +17,9 @@ class MainWindow : public QMainWindow {
|
|||
MainWindow(QWidget* parent = nullptr);
|
||||
~MainWindow();
|
||||
|
||||
private slots:
|
||||
void onDeleteBall(Ball* ball); // Slot to handle the ball deletion
|
||||
|
||||
protected:
|
||||
virtual void paintEvent(QPaintEvent*) override;
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue