Advertisement
Guest User

Untitled

a guest
Nov 18th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <linux/input.h>
  6. #include <stdlib.h>
  7.  
  8. #define EV_PRESSED 1
  9.  
  10. // bounds
  11. #define MAX_X 55
  12. #define MIN_X 25
  13. #define MAX_Y 20
  14. #define MIN_Y 10
  15.  
  16.  
  17. int is_possible_move(int y, int x) {
  18. return MIN_X < x && x < MAX_X && MIN_Y < y && y < MAX_Y;
  19. }
  20.  
  21.  
  22. int quit = 0;
  23. int keyboard;
  24.  
  25. int init_keyboard() {
  26. /*
  27. * Check before start
  28. * command -> grep -E 'Handlers|EV=' /proc/bus/input/devices | grep -B1 '120013' | grep -Eo 'event[0-9]+'
  29. */
  30. char *device = "/dev/input/event4";
  31. if ((getuid()) != 0) {
  32. printf("You are not root! This may not work...\n");
  33. return -1;
  34. }
  35.  
  36. if ((keyboard = open(device, O_RDONLY)) == -1) {
  37. printf("%s is not a valid device.\n", device);
  38. return -1;
  39. }
  40.  
  41. return 0;
  42. }
  43.  
  44. void * update_keyboard() {
  45. struct input_event event;
  46. const char ESC[] = "\033";
  47. char cmd[50];
  48.  
  49. int y = 15;
  50. int x = 30;
  51.  
  52. system("stty -echo");
  53. while (1) {
  54. read(keyboard, &event, sizeof(struct input_event));
  55. if (event.type == EV_KEY) {
  56. if (event.value == EV_PRESSED) {
  57. switch (event.code) {
  58. case KEY_UP: {
  59. if (is_possible_move(y - 1, x)) {
  60. y--;
  61. system("clear");
  62. sprintf(cmd, "printf '%s[%d;%dH*'", ESC, y, x);
  63. system(cmd);
  64. }
  65. break;
  66. }
  67. case KEY_DOWN: {
  68. if (is_possible_move(y + 1, x)) {
  69. y++;
  70. system("clear");
  71. sprintf(cmd, "printf '%s[%d;%dH*'", ESC, y, x);
  72. system(cmd);
  73. }
  74. break;
  75. }
  76. case KEY_LEFT: {
  77. if (is_possible_move(y, x - 1)) {
  78. x--;
  79. system("clear");
  80. sprintf(cmd, "printf '%s[%d;%dH*'", ESC, y, x);
  81. system(cmd);
  82. }
  83. break;
  84. }
  85. case KEY_RIGHT: {
  86. if (is_possible_move(y, x + 1)) {
  87. x++;
  88. system("clear");
  89. sprintf(cmd, "printf '%s[%d;%dH*'", ESC, y, x);
  90. system(cmd);
  91. }
  92. break;
  93. }
  94. case KEY_ESC: {
  95. quit = 1;
  96. }
  97. }
  98. }
  99. }
  100. }
  101. }
  102.  
  103. int main() {
  104. if (init_keyboard() != 0) return -1;
  105.  
  106. pthread_t thread;
  107. int id = 1;
  108. int result = 0;
  109.  
  110. result = pthread_create(&thread, NULL, update_keyboard, &id);
  111. if (result != 0) {
  112. printf("Create thread failed\n");
  113. return -1;
  114. }
  115.  
  116. while(!quit) {
  117. }
  118.  
  119. return 0;
  120. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement