Implementing Dynamic Wave Effects in C Language

Effect DemonstrationSource Code Sharing

#include <graphics.h>
#include <conio.h>
#include <cmath>
#include <vector>
using namespace std;
const int WIDTH = 800;
const int HEIGHT = 600;
const double PI = 3.1415926535;

int main(){
    initgraph(WIDTH, HEIGHT);
    vector<double> wave(200, 0);
    double time = 0;
    BeginBatchDraw();
    while (!_kbhit())
    {
        FlushBatchDraw();
        cleardevice();

        // Update wave
        for (int i = 0; i < wave.size(); i++) {
            double x = (double)i / wave.size() * 4 * PI;
            wave[i] = sin(x + time) * 100 + sin(x * 2 + time * 1.5) * 50;
        }
        // Draw wave
        for (int i = 0; i < wave.size() - 1; i++) {
            int x1 = i * (WIDTH / wave.size());
            int y1 = HEIGHT / 2 + (int)wave[i];
            int x2 = (i + 1) * (WIDTH / wave.size());
            int y2 = HEIGHT / 2 + (int)wave[i + 1];
            // Color gradient
            int blue = 128 + (int)(sin(time + i * 0.1) * 127);
            setlinecolor(RGB(0, 100, blue));
            setlinestyle(PS_SOLID, 3);
            line(x1, y1, x2, y2);
        }
        time += 0.05;
        Sleep(30);
    }
    EndBatchDraw();
    closegraph();
    return 0;
}

Leave a Comment