1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
#include <iostream> #include <vector> #include <cmath> #include <thread> #include <chrono> class Firework { public: Firework(int x, int y) : x(x), y(y), exploded(false) {} void launch() { for (int i = 0; i < 10; ++i) { if (exploded) break; // Simulate the ascent of the firework printFrame(x, y - i); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } explode(); } private: int x, y; bool exploded; void explode() { exploded = true; for (int i = 0; i < 20; ++i) { // Simulate the explosion effect printExplosionFrame(x, y, i); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } void printFrame(int x, int y) const { system("clear"); // For Linux or Mac // system("cls"); // Uncomment this line for Windows for (int i = 0; i < y; ++i) { std::cout << "\n"; } for (int j = 0; j < x; ++j) { std::cout << " "; } std::cout << "*\n"; // Firework representation } void printExplosionFrame(int x, int y, int radius) const { system("clear"); // For Linux or Mac // system("cls"); // Uncomment this line for Windows for (int i = 0; i < y; ++i) { std::cout << "\n"; } for (int j = 0; j < x; ++j) { std::cout << " "; } for (int i = 0; i < radius; ++i) { std::cout << "*"; } std::cout << "\n"; } }; int main() { int x, y; std::cout << "Enter the launch position (x y): "; std::cin >> x >> y; Firework firework(x, y); firework.launch(); return 0; } |
Explanation
- Class Definition (
Firework
):- Private Members:
x
andy
: Coordinates for the firework’s launch position.exploded
: A boolean flag indicating whether the firework has exploded.
- Public Methods:
Firework(int x, int y)
: Constructor to initialize the launch position.void launch()
: Simulates the ascent of the firework and triggers the explosion.- Calls
printFrame
to show the firework moving upwards. - Pauses for a short duration between frames using
std::this_thread::sleep_for
. - Calls
explode
when the ascent is completed.
- Calls
void explode()
: Simulates the explosion effect by creating a visual effect of expanding stars.- Calls
printExplosionFrame
to show the expanding effect. - Pauses between frames for the explosion effect.
- Calls
- Private Methods:
void printFrame(int x, int y) const
: Clears the console and prints the firework’s position.- Uses
system("clear")
for Linux/Mac orsystem("cls")
for Windows (comment/uncomment based on OS).
- Uses
void printExplosionFrame(int x, int y, int radius) const
: Prints the explosion effect by expanding the radius of stars.- Clears the console and prints stars in a radius pattern.
- Private Members:
main
Function:- Prompts the user for the firework’s launch position.
- Creates a
Firework
object with the specified position. - Calls
launch
to simulate the firework’s ascent and explosion.