C and C++ Computer Graphics

Program for moving circle in different directions

Program for moving circle in different directions
/* Moving Circle in Different Directions using graphics.h (BGI/WinBGI)
Works with Turbo C++ (DOS) or WinBGI on Windows.
*/
#include <graphics.h>
#include <conio.h>
#include <stdio.h>

int main() {
int gd = DETECT, gm;
int x, y, r = 25;
int step = 5;
int key;

initgraph(&gd, &gm, ""); // WinBGI: initwindow(width, height) can be used instead

// For WinBGI, you may prefer:
// initwindow(800, 600, "Moving Circle");

int maxX = getmaxx();
int maxY = getmaxy();

x = maxX / 2;
y = maxY / 2;

setbkcolor(BLACK);
cleardevice();
setcolor(WHITE);

outtextxy(10, 10, "Use Arrow Keys to move. ESC to exit.");

while (1) {
// Non-blocking: update only if key pressed
if (kbhit()) {
key = getch();

if (key == 27) { // ESC
break;
}

// Extended keys (arrow keys) return 0 or 224 first
if (key == 0 || key == 224) {
int k2 = getch();
switch (k2) {
case 75: x -= step; break; // Left
case 77: x += step; break; // Right
case 72: y -= step; break; // Up
case 80: y += step; break; // Down
default: break;
}
}
}

// Clamp to bounds so circle stays visible
if (x - r < 0) x = r;
if (y - r < 0) y = r;
if (x + r > maxX) x = maxX - r;
if (y + r > maxY) y = maxY - r;

// Draw frame
cleardevice();
setcolor(WHITE);
circle(x, y, r);
floodfill(x, y, WHITE); // optional fill if fill style set

// HUD text
setcolor(LIGHTGRAY);
char buf[64];
sprintf(buf, "x=%d y=%d | Arrows to move, ESC to exit", x, y);
outtextxy(10, 10, buf);

delay(16); // ~60 FPS
}

closegraph();
return 0;
}

Leave a comment

Your email address will not be published. Required fields are marked *