From 8949830a1bee497eab3859b220c6cb00c7093f27 Mon Sep 17 00:00:00 2001 From: ItsDrike Date: Tue, 11 Mar 2025 13:53:03 +0100 Subject: [PATCH] Add ball deletion logic --- src/ball.cpp | 12 +++++++++--- src/ball.h | 6 ++++++ src/mainwindow.cpp | 18 +++++++++++++++++- src/mainwindow.h | 3 +++ 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/ball.cpp b/src/ball.cpp index 0030277..6992f11 100644 --- a/src/ball.cpp +++ b/src/ball.cpp @@ -1,6 +1,8 @@ #include "ball.h" +#include #include #include +#include #include #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(); diff --git a/src/ball.h b/src/ball.h index e895f91..896b89a 100644 --- a/src/ball.h +++ b/src/ball.h @@ -3,13 +3,19 @@ #include #include +#include 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; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 1f0d95b..2e2fe7b 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,9 +1,13 @@ #include "mainwindow.h" #include "./ui_mainwindow.h" +#include MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); - balls.append(std::make_shared(this)); + + auto ball = std::make_shared(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; + } + } +} diff --git a/src/mainwindow.h b/src/mainwindow.h index 41dc4a2..9f66533 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -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;