Hello, I am new to C++, basically I am trying to make a program that while you are holding spacebar a number decrements, once your health is equal to 0 I want to prompt the user saying they are dead and if they would like to restart enter y and if they would like to exit type n. I tried to do this with a while loop but I don't know what I should use to make it properly.. In my head I'm thinking there should be a class or thread or whatever you call it, basically there needs to be something like this
1 2 3 4 5 6 7 8 9 10 11
fullHealth
{
while(1)
{
if (GetAsyncKeyState(VK_SPACE))
{
health--;
cout << health << endl;
}
}
}
Then what I want to do in the main is call the fullHealth function or whatever it would be called, and once health is <= 0 I would like to output the restart question, saying something like "You are dead, would you like me to set your health back to 100? y/n".. If the users input is equal to y I want to jump back to the fullHealth function, if it is equal to n I just want to break the loop and exit the program.. I hope you understand what I am saying and if I am approaching this wrong please let me know, I don't have much coding experience and I don't have the mentality of a "coder" yet. Thanks for the help everyone.
#include <iostream>
#include <conio.h>
usingnamespace std;
#define SPACE 32 // ASCII for spacebar
int main()
{
int ch;
int health = 100;
char Y_N;
do
{
do
{
cout << health << "\b\b\b";
ch = _getch();
if(ch == SPACE)
{
health--;
cout << health << " \b\b\b\b"; // To put cursor back 4 spaces.
// Now overwrites previous output
}
}while(health >= 0);
cout << "You are dead. Would you like me to set your health back to 100? [Y or N] ";
do
{
cin >> Y_N;
Y_N = toupper(Y_N);
if(Y_N == 'Y')
health = 100;
}while(Y_N !='Y' && Y_N != 'N');
}while(Y_N == 'Y');
return 0;
}
int main()
{
int health{ 10 }; // Short for testing.
FullHealth(health);
return 0;
}
void FullHealth(int health)
{
char cont{ 'N' };
while (1)
{
if (GetAsyncKeyState(VK_SPACE))
{
health--;
std::cout << health << std::endl;
_getch(); // To clear the input buffer and wait for the next key press.
}
if (health < 1)
{
std::cout << "\n You are dead, would you like me to set your health back to 100? y/n. ";
std::cin >> cont;
if (toupper(cont) == 'Y')
{
std::cout << "\n\n";
health = 10; // Used 10 just to keep it short for testing.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
elsebreak;
}
}
}
Line 34 requires the header file "limits". On my setup I include the header file "Windows.h" and need to follow this "#undef max" and then include "limits" for max to work correctly.
The function works, but could use a little tweaking.