Introduction to Programming

Bounce v2.0


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

// This function causes some small amount of time to go by. 
void delay() 
{ 
    int i; 

    for (i=0; i<100000; i++) 
    { 
    } 
} 

// This is the main program. This is where it all starts! 
int main(int argc, char *argv[]) 
{ 
    float x, y, dx, dy, oldx, oldy; 
    char ch = 0; 

    // Initialize curses 
    initscr(); 
    start_color(); 
    init_pair(1, 2, 0); 
    init_pair(2, 3, 0); 
    cbreak(); 
    noecho(); 
    nonl(); 
    intrflush(stdscr, FALSE); 
    keypad(stdscr, TRUE); 
    nodelay(stdscr, TRUE); 
    clear(); 

    // Random seed. 
    srand(time(NULL)); 

    // Starting values. 
    x = 10; 
    y = 20; 
    dx = 0.07; 
    dy = 0; 
    oldx = 10; 
    oldy = 10; 

    // A line at the bottom of the screen. 
    move(21, 0); 
    color_set(1, NULL); 
    addstr("______________________________" 
           "______________________________"); 

    // As long as the user doesn't quit, keep the loop going... 
    while (ch != 'q') 
    { 
        // Draw over the old star. 
        move((int) oldy, (int) oldx); 
        addch(' '); 
        // Draw the new star. 
        move((int) y, (int) x); 
        color_set(2, NULL); 
        addch('*'); 

        // Move the curser back to the bottom, and wait. 
        // (If we don't wait, stuff will move *way* too fast!) 
        move(22, 0); 
        refresh(); 
        delay(); 

        // If we hit a wall, bounce. 
        if (dx > 0 && x >= 60) 
           dx = -dx; 
        if (dx < 0 && x <= 0) 
           dx = -dx; 

        // If we hit the ceiling, bounce. 
        if (dy < 0 && y <= 0) 
           dy = -dy; 

        // If we hit the floor, stick. 
        if (dy > 0 && y >= 20) 
        { 
           y = 20; 
           dy = 0; 
        } 

        // Update x and y and their old values. 
        oldx = x; 
        oldy = y; 
        x += dx; 
        y += dy; 

        // Gravity 
        if (y != 20 || dy != 0) 
            dy += 0.0005; 

        // See if the user has a command. 
        ch = getch(); 

        // If the user says jump, then jump! 
        if (y == 20 && dy == 0 && ch == 'j') 
            dy -= 0.1; 
    } 

    // Clear the screen and shut down curses. 
    clear(); 
    endwin(); 

    // A kindly message to say farewell to the user... 
    printf("Thanks for playing!\n"); 

    // End of program. 
    return 0; 
}

Next: Speed Letters

Previous: Bounce v1.0


Introduction to Programming

Home