Introduction to Programming

Bounce


Filename: bounce.c
Compile: gcc bounce.c -o bounce
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void clear() 
{ 
    printf("\033[H\033[J"); 
} 

void clearLine() 
{ 
    printf("\033[K"); 
} 

void move(int x, int y) 
{ 
    printf("\033[%d;%dH", y, x); 
} 

void doColor(int c) 
{ 
    if (c >= 0 && c <= 7) 
        printf("\033[3%dm", c); 
} 

void undoColor() 
{ 
    printf("\033[m"); 
} 

void delay() 
{ 
    int i; 

    for (i=0; i<500; i++) 
        move(0, 21); 
} 

int main(int argc, char *argv[]) 
{ 
    float x, y, dx, dy, oldx, oldy; 

    srand(time(NULL)); 

    x = 10; 
    y = 10; 
    dx = 0.07; 
    dy = 0.03; 
    oldx = 10; 
    oldy = 10; 

    clear(); 
    move(0, 21); 
    doColor(2); 
    printf("______________________________" 
           "______________________________"); 

    while (1) 
    { 
        move((int) oldx, (int) oldy); 
        clearLine(); 
        move((int) x, (int) y); 
        doColor(3); 
        printf("*"); 
        undoColor(); 
        move(0, 21); 
        fflush(stdout); 
        delay(); 

        if (dx > 0 && x >= 60) 
           dx = -dx; 
        if (dx < 0 && x <= 0) 
           dx = -dx; 
        if (dy > 0 && y >= 20) 
           dy = -dy; 
        if (dy < 0 && y <= 0) 
           dy = -dy; 

        oldx = x; 
        oldy = y; 
        x += dx; 
        y += dy; 

        dy += 0.0005; 
    } 

    undoColor(); 
    move(0, 21); 
    return 0; 
}

Next: Bounce v2.0

Previous: Stars


Introduction to Programming

Home