getchar () пока пользователь пишет - PullRequest
1 голос
/ 08 июня 2019

Я моделирую телевизионную игру в программе на C.У игрока есть 60 секунд, чтобы угадать слово, и когда он находит его, он должен нажать клавишу ввода, чтобы получить новое: слово меняется, а также количество слов и оставшееся время обновления.Поскольку часть «enter listener» - это getchar, я догадывался, можно ли выполнить обновление времени, оставленного секундой, в режиме реального времени, ожидая нажатия клавиши enter с помощью getchar ().

while(1) {
        system("clear"); //RAND WORD
        parola = parole[rand() % n]; //PRINT WORDS, NEW WORD, SECONDS LEFT
        printf("\n\n[%d]\t\t%s\t\t%d", indovinate, parola, secLeft);

        gettimeofday(&initTime, NULL);
        int initSec = initTime.tv_sec; //WAIT FOR PAYLER TO PRESS ENTER
        getchar();

        gettimeofday(&tookTime, NULL);
        int tookSec = tookTime.tv_sec - initSec; //UPGRADE TIME TOOK
        secLeft -= tookSec;

Ответы [ 3 ]

0 голосов
/ 09 июня 2019

Вы можете использовать задержку dos.h с помощью kbhit () conio.h задержка (время) принимает целое число как время, чтобы приостановить выполнение программы на эту «временную» сумму

int i=0;
while (i<60||!kbhit())       // wait till i reach value 60 or key is pressed
 {//doing the stuff
  i++;}
if (i==60)
printf("\n sorry but the time out you may try next time");```

0 голосов
/ 09 июня 2019

ncurses можно использовать. timeout() важен, поскольку он меняет getchar() для предотвращения блокировки.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <ncurses.h>

#define WAIT 60.0
#define MILLION 1E6

int main ( void)
{
    char ch = 0;
    char *words[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", NULL};
    int row = 0;
    int line = 0;
    int col = 0;
    int counting = 1;
    char text[80] = {""};
    float elapsed = 0.0f;
    struct timeval start;
    struct timeval stop;

    srand ( time ( NULL));
    int items = sizeof words / sizeof words[0];//number of words
    items--;//to keep NULL at the end
    while ( items > 1) {//shuffle words pointers
        items--;
        int swap = rand ( ) % items;
        char *temp = words[swap];
        words[swap] = words[items];
        words[items] = temp;
    }
    items = 0;

    initscr ( );
    noecho ( );
    timeout ( 100);//so getchar does not block
    getmaxyx ( stdscr, row, col);//screeen size
    line = row / 2;//center vertically
    snprintf ( text, sizeof ( text), "press x to exit or Enter to reset");
    mvprintw ( line - 1, ( col - strlen ( text)) / 2,"%s", text);//center horizontally
    mvprintw ( line + 1, ( col - strlen ( words[items])) / 2,"%s", words[items]);
    gettimeofday ( &start, NULL);
    while ( 1) {
        if ( counting) {
            gettimeofday ( &stop, NULL);

            elapsed = (float)(stop.tv_sec - start.tv_sec)
             + ( (float)(stop.tv_usec - start.tv_usec) / MILLION);

            move ( line, 0);//move to start of line
            clrtoeol ( );//clear to end of line
            snprintf ( text, sizeof ( text), "%f", WAIT - elapsed);
            mvprintw ( line, ( col - strlen ( text)) / 2,"%s", text);//center text
        }
        else {
            move ( line, 0);//move to start of line
            clrtoeol ( );//clear to end of line
            snprintf ( text, sizeof ( text), "paused press x or Enter");
            mvprintw ( line, ( col - strlen ( text)) / 2,"%s", text);
        }
        if ( elapsed > WAIT || ( ch = getch ( )) == 'x' || ch == '\n') {
            if ( elapsed > WAIT || ch == '\n') {
                gettimeofday ( &start, NULL);
                elapsed = 0.0f;
                counting = !counting;
                if ( counting) {
                    items++;
                    if ( words[items]) {
                        move ( line + 1, 0);
                        clrtoeol ( );
                        mvprintw ( line + 1, ( col - strlen ( words[items])) / 2,"%s", words[items]);
                    }
                    else {
                        break;
                    }
                    gettimeofday ( &start, NULL);
                }
            }
            if ( ch == 'x') {
                break;
            }
        }
    }
    endwin ( );
    return 0;
}
0 голосов
/ 09 июня 2019

попробуй kbhit(), Это часть библиотеки conio.h. Это в основном проверяет, нажата ли клавиша. Если это не так, вы можете обновить время. если это так, вы можете ввести ответ.

if(kbhit()){
    a = getch();
}
else{
    //update time
}

Вы можете использовать getch(), игроку не нужно нажимать клавишу ввода.

Возможно, есть лучшие способы сделать это, чем c. (Не спрашивайте меня, я не делаю такие вещи)

Но если это просто классный проект, продолжайте.

...