2015-11-29 3 views
1

Итак, я построил эту очень простую игру на языке c, где вы - корабль, и вам нужно избегать пули, поднимающейся по экрану. Когда я запускаю его в терминале, каждый раз, когда я хочу переместить корабль, я ввожу (слева) s (прямое) или d (справа). Мне было интересно, если бы не было принудительного использования ключа ввода после каждого шага и, скорее, пуля постепенно поднималась, как одно место в секунду или что-то автоматически.Как автоматически выполнить код в терминале

Код:

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#include <time.h> 
#include <assert.h> 
#define height 20 
#define width 15 

int main (int argc, char *argv[]) { 
    printf("Beginning Game\n"); 
    printf("Press 's' to start\n"); 
    char move = 0; 
    int count = 6; 
    int turn = 0; 
    int row = 0; 
    int col = 0; 
    int left = 0; 
    int right = 14; 
    srand(time(NULL)); 
    int shootcol = rand() % (width - 3) + 2 ; 
    int shootrow = height + 1; 
    int shoot2col = rand() % (width - 3) + 2 ; 
    int shoot2row = height + 15; 



while (move != 'e') { 
    printf("\n"); 
    scanf(" %c", &move); 
    if (move == 's') { 
     turn++; 
    } 
    else if (move == 'a') { 
     count--; 
     turn++; 

    } else if (move == 'd') { 
     count++; 
     turn++; 

    } 
    row = 0; 
    col = 0; 
    printf("TURN: %d\n", turn); 
    while (row < height) { 
     while (col < width) { 
      //printf("%d", col); 
      if (((row == shootrow) && (col == shootcol)) || ((row == shoot2row) && (col == shoot2col))) { 
       printf(":"); 


      } else if (col == left) { 

       printf("|"); 


      } else if (col == right) { 
       printf("|"); 

      } else if (row < 5) { 
       printf(" "); 

      } else if (row == 5) { 

       if (col < count) { 
        printf(" "); 
       } else if (col == count) { 
        printf("|"); 

       } else if (col == count + 1) { 
        printf("-"); 

       } else if (col == count + 2) { 
        printf("|"); 

       } else if (col >= count + 3) { 
        printf(" "); 
       } 
      } else if (row == 6) { 

       if (col < count) { 
        printf(" "); 
       } else if (col == count) { 
        printf("\\"); 

       } else if (col == count + 1) { 
        printf(" "); 

       } else if (col == count + 2) { 
        printf("/"); 

       } else if (col >= count + 3) { 
        printf(" "); 
       } 

      } else { 
       printf(" "); 

      } 
      col++; 

     } 
     col = 0; 
     printf("\n"); 
     row++; 

    } 
    shootrow--; 
    shoot2row--; 
    if ((count == left) || (count == right - 2)) { 
     printf("YOU LOSE!!\n"); 
     move = 'e'; 
    } else if ((shootrow == 5) || (shootrow == 4)) { 
     if ((count == shootcol) || (count == shootcol - 2) || (count == shootcol - 1)) { 
      printf("YOU LOSE!!\n"); 
      move = 'e'; 
     } if ((count == shoot2col) || (count == shoot2col - 2) || (count == shoot2col - 1)) { 
      printf("YOU LOSE!!\n"); 
      move = 'e'; 
     } 

    } if (shootrow <= 0) { 
     shootrow = height - 1; 
     shootcol = rand() % (width - 3) + 2 ; 
    } if (shoot2row <= 0) { 
     shoot2row = height - 1; 
     shoot2col = rand() % (width - 3) + 2; 
    } 

} 

return 0; 
} 
+0

заметившие (нажатие неблокируемой): [Linux] (http://stackoverflow.com/questions/20349585/c-library -function-to-check-the-keypress-from-keyboard-in-linux), [Windows] (https://msdn.microsoft.com/en-us/library/236adc23%28v=vs.80%29. ASPX). Вы можете просто добавить 'sleep' ([windows] (http://stackoverflow.com/questions/3379139/sleep-function-in-windows-using-c), [linux] (http: //linux.die. net/man/2/nanosleep)) к вашему 'while'. – Kenney

+2

В стандарте C. нет способа использовать. Нестандартные средства, которые будут специфичны для вашей целевой среды, компилятора и т. Д. Такие, как упомянутые Кенни. – Peter

+0

Я использую mac, так что есть ли способ сделать это на mac, а также я не видел функцию сна раньше, где и что бы я вложил в свой код. благодаря –

ответ

2

Самый простой способ использует библиотеку Conio

#include <conio.h> 
#define DELAY 300 // define here the amount of milliseconds to sleep 

Если вы используете Linux или Mac

#include <unistd.h> 

Если вы используете Windows,

#include <windows.h> 

и это как начало вашего цикла будет выглядеть

while (move != 's') 
    scanf(" %c", &move); 

move = ' '; 

while (move != 'e') { 
    printf("\n"); 

    //Sleep(DELAY); // windows only sleep 's' lowercase for linux 
    usleep(DELAY);  // for mac 

    if (_kbhit()) 
    { 
     move = _getch(); 
    } 

    if (move == 's') { 
     turn++; 
    }