Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <linux/input.h>
- #include <stdlib.h>
- #define EV_PRESSED 1
- // bounds
- #define MAX_X 55
- #define MIN_X 25
- #define MAX_Y 20
- #define MIN_Y 10
- int is_possible_move(int y, int x) {
- return MIN_X < x && x < MAX_X && MIN_Y < y && y < MAX_Y;
- }
- int quit = 0;
- int keyboard;
- int init_keyboard() {
- /*
- * Check before start
- * command -> grep -E 'Handlers|EV=' /proc/bus/input/devices | grep -B1 '120013' | grep -Eo 'event[0-9]+'
- */
- char *device = "/dev/input/event4";
- if ((getuid()) != 0) {
- printf("You are not root! This may not work...\n");
- return -1;
- }
- if ((keyboard = open(device, O_RDONLY)) == -1) {
- printf("%s is not a valid device.\n", device);
- return -1;
- }
- return 0;
- }
- void * update_keyboard() {
- struct input_event event;
- const char ESC[] = "\033";
- char cmd[50];
- int y = 15;
- int x = 30;
- system("stty -echo");
- while (1) {
- read(keyboard, &event, sizeof(struct input_event));
- if (event.type == EV_KEY) {
- if (event.value == EV_PRESSED) {
- switch (event.code) {
- case KEY_UP: {
- if (is_possible_move(y - 1, x)) {
- y--;
- system("clear");
- sprintf(cmd, "printf '%s[%d;%dH*'", ESC, y, x);
- system(cmd);
- }
- break;
- }
- case KEY_DOWN: {
- if (is_possible_move(y + 1, x)) {
- y++;
- system("clear");
- sprintf(cmd, "printf '%s[%d;%dH*'", ESC, y, x);
- system(cmd);
- }
- break;
- }
- case KEY_LEFT: {
- if (is_possible_move(y, x - 1)) {
- x--;
- system("clear");
- sprintf(cmd, "printf '%s[%d;%dH*'", ESC, y, x);
- system(cmd);
- }
- break;
- }
- case KEY_RIGHT: {
- if (is_possible_move(y, x + 1)) {
- x++;
- system("clear");
- sprintf(cmd, "printf '%s[%d;%dH*'", ESC, y, x);
- system(cmd);
- }
- break;
- }
- case KEY_ESC: {
- quit = 1;
- }
- }
- }
- }
- }
- }
- int main() {
- if (init_keyboard() != 0) return -1;
- pthread_t thread;
- int id = 1;
- int result = 0;
- result = pthread_create(&thread, NULL, update_keyboard, &id);
- if (result != 0) {
- printf("Create thread failed\n");
- return -1;
- }
- while(!quit) {
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement