Newer
Older
textpong / textpong.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

#define ESC "\x1b["

void locate(int x, int y) {
    printf(ESC "%d;%dH", y, x);
}

int abs(int x) {
    return (x < 0)? -x: x;
}

int main(int argc, char const* argv[]) {
    int score = 0;
    int x=10, y=10, bx, by, vx=1, vy=1;
    int bar_x = 16, flag = 1;

    bx = x; by = y;
    fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
    printf(ESC "2J");

    while (y < 23) {
        int c = getchar();
        locate(bx, by); printf(" ");
        locate( x,  y); printf("o");
        locate(bar_x, 21);    printf(" ====== ");
        locate(35, 0);        printf("Sc: %04d", score);

        bar_x += (c == 'l')? +1: 
                 (c == 'h')? -1:
                 0;

        if (bar_x < 1) bar_x = 1;
        else if (bar_x > 30) bar_x = 30;

        if (flag) {
            bx = x; by = y;
            x += vx; y += vy;
            if (x == 0 || x >= 35) vx = -vx;
            if (y == 1 || (y == 20 && 
                     1 <= (x - bar_x) && (x - bar_x) < 7)) vy = -vy;
            if (y == 20) score++;
        }
        flag = !flag;
        usleep(60000);
    }
    printf("\n**** GAME OVER ****\n");
    return 0;
}