#include #include #include #include #include #include #define WIN_SIZE 600 #define SPEED 10 #define RADIUS 15 #define PI 3.14159 int main() { Display *display; Window win; GC gc; int x = WIN_SIZE/2, y = WIN_SIZE/2; float direction; // Opens connection to X server display = XOpenDisplay(NULL); // Create a simple window, set the title and get the graphics context then // make is visible and get ready to draw win = XCreateSimpleWindow(display, RootWindow(display, 0), 0, 0, WIN_SIZE, WIN_SIZE, 0, 0x000000, 0xFFFFFF); XStoreName(display, win, "Bouncing Ball"); gc = XCreateGC(display, win, 0, NULL); XMapWindow(display, win); XFlush(display); usleep(20000); // sleep for 20 milliseconds. // Go into infinite loop srand(time(NULL)); direction = (rand()/(double)(RAND_MAX))*2*PI; while(1) { XSetForeground(display, gc, 0xFFFFFF); XFillRectangle(display, win, gc, 0, 0, WIN_SIZE, WIN_SIZE); XSetForeground(display, gc, 0x000000); // black XFillArc(display, win, gc, x-RADIUS, y-RADIUS, 2*RADIUS, 2*RADIUS, 0, 360*64); // Move the ball forward x = x + (int)(SPEED*cos(direction)); y = y + (int)(SPEED*sin(direction)); // Check if the ball collides with borders and adjust accordingly if (x >= (WIN_SIZE-RADIUS)) { direction = PI - direction; x = WIN_SIZE-RADIUS; } else if (x <= RADIUS) { direction = PI - direction; x = RADIUS; } if (y >= (WIN_SIZE-RADIUS)) { y = WIN_SIZE-RADIUS; direction *= -1; } else if (y <= RADIUS) { y = RADIUS; direction *= -1; } XFlush(display); usleep(5000); } // Clean up and close the window XFreeGC(display, gc); XUnmapWindow(display, win); XDestroyWindow(display, win); XCloseDisplay(display); }