Nimbin2git.christianimmanuel.de / Games / vier_gewinnt / keypress.c

vier_gewinnt git · main

git clone https://git.christianimmanuel.de/games/vier_gewinnt.gitwget https://git.christianimmanuel.de/games/vier_gewinnt/archive/vier_gewinnt.tar.gz
keypress.c 1.1 KB · 62 lines raw
#ifndef KEYPRESS_C
#define KEYPRESS_C

#include <stdio.h>

#ifdef WINDOWS

#include <windows.h>
#include <conio.h>

char get_keypress(){
    char c = getch();
    return c;
}

#else

#include <unistd.h>
#include <termios.h>

char get_keypress() {

    char buf = 0;
    struct termios old = {0};
    fflush(stdout);
    if (tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if (tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if (read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if (tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    return buf;
}

char get_saved_key(unsigned nr_moves, char *moves) {
    switch (moves[nr_moves]) {
        case 'u':
        case 'U':
            return 'w';
        case 'd':
        case 'D':
            return 's';
        case 'l':
        case 'L':
            return 'a';
        case 'r':
        case 'R':
            return 'd';
    }
    return 0;
}

#endif
#endif