Newer
Older
textpong / textpong.c
@Takayuki Kurosawa Takayuki Kurosawa on 19 Oct 2017 1003 bytes first release
#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) {
    if (x < 0)
        return -x; 
    else
        return x;
}

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

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

    while (y < 21) {
        int c = getchar();
        locate(bar_x, 21);    printf(" ====== ");
        locate(bx, by); printf(" ");
        locate( x,  y); printf("o");

        bar_x += c == 'l'? 1: c=='h'? -1: 0;
        if (bar_x < 1) 
            bar_x = 1;
        else if (bar_x > 30) 
            bar_x = 30;

        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;
        usleep(200000);
    }
    printf("GAME OVER\n");
    return 0;
}