getchar() while user is writing - c

I'm simulating a tv game in a C prompt program. The player has 60 seconds to guess a word, and when he finds it, he has to press enter to get a new one: the word changes, and the number of words and the time left upgrade.
Because the "enter listener" part is a getchar, I was guessing if it could be possible to do a real-time upgrading of the time left second by second, while waiting for the enter pressing with 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;

try kbhit(),
It's part of the conio.h library.
It basically checks if a key is pressed. If it isn't you can update the time. if it is you can input the answer.
if(kbhit()){
a = getch();
}
else{
//update time
}
you might want to use getch(), it doesn't need the player to press enter.
There might be better ways to do this than c. (Don't ask me, I don't do stuff like this)
But if It's just a cool project, go ahead.

you can use delay of dos.h with the kbhit() of conio.h
the delay(time) take integer as time to pause the program from execution for that 'time' amount
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");```

Related

Always running a line/Running 2 lines at once in C

Im hoping to make a clicker game from C. I already have the clicking mechanics down and im pretty confident i can do everything else but I can seem to find any articles or help regarding having a running line in the background. For example I have a line of code that allows whenever I click a key i get +1 money, but like most clicker games I want a auto klicker to be running every second or so. So i can just be normally clicking while at the same time theirs a function or line of code that adds +5 money every so often. Ive made my own (delay) code so thats not an issue, its just running a line in the background. Heres what I have so far...
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
int main()
{
int menu;
char ch;
int klicks;
int klickses;
klicks=0;
void delay(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
printf("Welcome to Key Klicker! This game is a idle game where you slowly gain more and more klicks over time.\n The game is never ending but their are milestones to reach.\n A menu will open up to help navigate through the game.\n");
do{
printf(" 1: Clicking\n 2: Shop\n 3: Exit\n\n");
scanf("%d", &menu);
if(menu == 1)
{
klickses=0;
{
char ch;
printf("Klick as fast as you can! (ESC to exit)\n");
while (1) { //define infinite loop for taking keys
if (kbhit) {
ch = getch(); // Get typed character into ch
klicks=klicks+1;
klickses=klickses+1;
if ((int)ch == 27) //when esc button is pressed, then it will comeout from loop
break;
printf("+1\n");
}
}
}
printf("You have a total of %d klicks!\n", klicks);
printf("You earned %d klicks that session!\n\n", klickses);
}
else if(menu == 2)
{
printf("work in progress\n");
}
else if (menu == 3)
{
printf("exit work in progress\n");
}
}while (1);
}
Hey guys I got it to work! Basically instead of having a auto adder every so seconds I decided to make a stopwatch that starts at the beginning and ends when I go out of the auto clicker. I then minus the end time from the start time and just calculate the auto clicks from their!
I also think with a new variable I just learned called time_t I could make an if statement that if a certain time is passed it would add 5 but anyhoo im not going to vere onto another path. This communities super helpful keep it going!

Constantly check for keyboard input while theres already a loop

Im creating a little game thats like a keyboard version of guitar hero. I'm almost done, but i'm just confused over one thing. I want to constantly be checking if the player is pressing anything on the keyboard and to see if they are pressing the correct key, but I already have a loop that sleeps every 1 second to update the game, so I cant have another loop running at the same time to constantly check the keyboard input (or can I?). I tried putting the keyboard check inside the game loop, but since it sleeps every second, it sometimes doesnt catch when the player presses the key.
This is my while loop:
while (playing)
{
updateBoard(score, game);
checkKeyPress(game);
Sleep(time);
if (rand() % 2 == 1)
spawnNewLetter(game);
}
updateBoard just prints out the new board, spawnNewLetter is just to spawn a new letter to fall down the board, and checkKeyPress is to check the keyboard input, this is it:
void checkKeyPress(char game[GAME_ROW][GAME_COL])
{
if (_kbhit())
{
switch (_getch())
{
case 97:
checkLetter(game, 'a');
break;
case 98:
checkLetter(game, 'b');
break;
The function goes on, but its just repeating to check for all the letters.
Any help would be appreciated, thanks!

Re-execute program based on user input in C

Hi i'm trying to learn programming in C on my own and have managed to make a verry, verry simple program that calculates the surface of a circle based on user input.
However the program runs only one time and then closes it.
This was initially the intention because it is only for learning but i want to expand on this program to increase my skills/knowledge and hope someone can point me in the right direction.
What i want to do now is instead of terminating the program after running it once; i would like to offer the user a choise to either stop the program or to continue it and to calculate a new circle.
I understand that it has to be done with an if else statment with the getchar function but i have some issues wrapping my mind around it on how to put it in a program flow. I hope someone can give me some directions on how to tackle this problem or can point me to some documentation that explains this properly.
Currently i have this:
int main(void){
float diameter;
double straal;
double oppervlakte;
char ch;
printf("Type de diameter van de cirkel:\t");
scanf("%g", &diameter);
printf("\n");
straal = diameter / 2;
oppervlakte = PI * (straal * straal);
printf("De straal =\t%g \n\n", straal );
printf("De oppervlakte =\t%f \n\n" , oppervlakte);
printf("Druk enter om af te sluiten.");
scanf("%c",&ch);
getchar();
return 0;
}
and im trying to accomplish something like this(below) but i can't get it to work properly (i get the warning that the label "diameter" is not defined while trying to compile it.)
#include <stdio.h>
#define PI 3.14
int main(void){
float diameter;
double straal;
double oppervlakte;
char ch;
printf("Type de diameter van de cirkel:\t");
scanf("%g", &diameter);
printf("\n");
straal = diameter / 2;
oppervlakte = PI * (straal * straal);
printf("De straal =\t%g \n\n", straal );
printf("De oppervlakte =\t%f \n\n" , oppervlakte);
printf("Druk 'd' om door te gaan of druk enter om af te sluiten.");
if(getchar() == 'd')
{
goto diameter; /* tried to use main(void) here but that also doesnt work */
}
else{
scanf("%c",&ch);
getchar();
}
return 0;
}
i do understand that goto is not the best practise to use but in this case it seemed the easyest way to solve this issue. (and the program is not that complex ofc). However if im wrong in this please let me also know.
Option 1: (likely the best choice): use a do..while loop. Place a do { above your primary code block, and add a } while (<repeat condition>); at the end. The program will run through the code once, check the repeat condition (which will be "did the user enter yes"), and if so repeat, otherwise not.
Option 2: recursively call main(). You said you "tried that", but I'm not sure if you tried it by attempting to use a goto or not. Just use the line main() to call the function again. Note that if you do this too many times you can end up with a stack overflow, because the computer keeps track of each call. It takes a lot to have it be a problem, but with enough repeats it can happen.
You can do something like:
while(true) //this is an endless loop
{
//display a menu like
1. calc area
2. [anything else if you want to add in future]
.
.
.
0. exit
//take user input (e.g 1 for calculating the area)
switch(user input)
{
case 1:
//code to calculate area
break;
case 2:
//code for anything else
break
case 0:
exit(0); //this will terminate the program
}
}
If you follow this pattern, you can add more options to your program in future. You just need to add a case in your switch statement and include that operation in your menu. You can search for menu driven c program to get more details. Try reading about while loop and switch... case statements.
I actually managed to make work in both ways.
Thanks for the tips and suggestions.

Using `sleep()` for a time delay [duplicate]

This question already has answers here:
Sleep for milliseconds
(20 answers)
Closed 8 years ago.
I an trying to delay program execution for 200ms and then test if a key was pressed during the delay. How do I do this?
I am tryint to create a simple computer game similar to flappy birds, using C. I want the user to have tiny bit of time (~200ms) to press a key for the bird to jump, or it will fall down, but I am having trouble with implementing the delay.
I've read on some forums [where?] that sleep(100) should give a 100ms delay, but when I do it, I get 100 seconds.
I also tried using sleep(1/5), but the function only takes integers.
Additionally, I need to be able to test if a key was pressed during the 200ms; I read somewhere[where?] that the kbhit function can be used for that, but I have no idea how to use it.
while(!dead) {
sleep(200); // what do I put here to get 200ms?
if (keyWasPressedDuringWait()){ //what do I put here?
notDeadAnimation():
}else{
dead=true;
deadAimation()
}
}
To perform the desired delay, #include <unistd.h> and use usleep(microseconds). (To sleep for 200ms, the call is usleep(200000)).
To test the keyboard strike, #include <conio.h> and use _kbhit() in your test (short for keyboard hit). _kbhit tests if there is a key in the key buffer, but does not get rid of it. You also need to use _getch to retrieve the key, removing it from the key buffer. I'd recommend defining a helper function here:
int clearKeyBuffer(){
int count = 0;
while(_kbhit()){
_getch();
count++;
}
return count;
}
This method will clear all keys currently in the key buffer, and return the number of keys cleared. You can then use this in your test, as if(clearKeyBuffer()) to test if a key has been presses since the last time you tested it.
As for your program flow, you have a lot of extra stuff there. You can get rid of most of it and still be functionally identical:
do {
notDeadAnimation();
usleep(200000);
} while(clearKeyBuffer());
deadAnimation();
However, this has the obvious issue that someone could just
Use usleep() instead of sleep(). The former works in micro seconds.
And use _kbhit()+getch() to discover if a key was pressed and which key was it:
while (!dead) {
usleep(200*1000); // 200 msec
if (_kbhit()) { // if key was pressed during sleep
int key = getch();
// you can check key value here
notDeadAnimation();
} else {
dead = true;
deadAnimation();
}
}

C: Do-While Loop Repeating Too Much!

I have a small program that which is confusing me. I am trying using a loop to take input from user. In case input is wrong, it is repeated again but if it is right, it exits.
The code snippet is:
void main()
{
char user_status; // Checks User Status q = Quiz Master and p = Participant
int valid_status = '0'; // Checks If User Status Is Valid Or Not. Used In Some Loops. 0 = Invalid, 1 = Invalid.
printf("Welcome to General Knowledge Quiz Management System.\nThis application has been designed to help you conduct a quiz or test your GK.");
do
{
user_status = '0';
printf("\n\nPlease enter your role.\nQuiz Master = \'q\'\nParticipant = \'p\'\n");
scanf("%c", &user_status);
if (user_status == 'q'|| user_status == 'Q')
{
printf("Initializing Quiz Master Segment\n\n________________________________\n");
initiate_qm();
valid_status = '1';
}
else if (user_status == 'p' || user_status == 'P')
{
printf("Initializing Participant Segment");
initiate_pa();
valid_status = '1';
}
}
while (valid_status != '1')
printf("\nProgram Will Exit Now. Press Any Key To Return To Windows.");
getch();
}
I am expecting this output:
Please Enter Your Role
Quiz Master = 'q'
Participant = 'p'
Till now, it works great. When I input q/Q/p/P, it works great. But when I input something wrong, it does not give required output.
For example, if I input "abc", I should get the above text again asking me to input q or p. But instead, I get this:
Please Enter Your Role
Quiz Master = 'q'
Participant = 'p'
Please Enter Your Role
Quiz Master = 'q'
Participant = 'p'
Please Enter Your Role
Quiz Master = 'q'
Participant = 'p'
Please Enter Your Role
Quiz Master = 'q'
Participant = 'p'
_ (I have to input here)
Now, why is it repeating 3 extra times. One interesting thing to note is that if I input something that is 2 characters long, it repeats 2 extra times and if I leave it blank(just hit return), it does not repeat extra times.
I have to use only C. I am using Visual C++ 2010 to compile.
Thanks.
Because you have given scanf three characters to process. It removes first first character the first time it calls scanf getting 'a', but still has 'bc' left in the stdin buffer.
You need to check for leftover stuff in your buffer before you look for input again. And I'd avoid flushing the stdin buffer because it's undefined behavior. (http://www.gidnetwork.com/b-57.html)
You can read the remaining characters and discard them with
do{
scanf("%c", &user_status);
}while(user_status!='\n'); //This discards all characters until you get to a newline
right after you read the character you want.
You want
do
{
} while (condition);
As your forgot the semicolon, you get:
do
{
....
}
while(condition)
do something else;
You could have noticed that just by auto-indenting your code in an editor like I did on your question.
Also when you do some scanf you should rather include the \n in the format specification.
First of all, # include <stdio.h> and use getc(stdin) to get a character. It'll help you to prevent cursor from moving and putting unnecessary characters to console.
Secondly, write the welcome message before the loop.

Resources