Hi I'm testing out what I can do with C++ and I want to eventually develop a simple text based game. So I'm trying to create my own health system. The problem in the coding is that once my health goes to 0 or negative it will not go to a death scene and that I added it'll just loop the program.
Any other suggestion in how to do this would be appreciated,
Thank you
#include <iostream>
usingnamespace std;
int main()
{
int hp = 9;
int enemyattack = 2
;get_attacked:
;system("cls");
cout << "You have 9 health, everytime you press a button it drops by two";
_getch();
hp = hp - enemyattack;
cout << "You now have " << hp << "HP left.\n\n";
_getch();
if ('hp' <= 0 ) {
goto dead;
}
elseif ('hp' > 0) {
goto get_attacked;
}
_getch();
dead:
cout << "You have no more health, you dead";
_getch();
#include <iostream>
#include <conio.h>
#include <windows.h>
usingnamespace std;
void clrscr()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
int main()
{
int health = 10;
int EnemyAttack = 2;
cout << "you have 10 health, each time you pressed a button, your health decreased by 2";
getch();
do
{
clrscr();
cout << "you have " << health << " health left";
getch();
health -= EnemyAttack;
} while (health > 0);
clrscr();
cout << "you are dead";
}
coders tend to get angry whenever someone uses goto
Not angry, I just cry tears of blood. And only when misused. (It is being misused now...) :'(
As a beginner I would recommend that you don't use it. The circumstances in which its use is warranted are relatively rare, and the potential for misuse is high.
goto is occasionally useful for various low-level micro optimizations, and for multi-level breaks in certain very limited situations. Using it because you're too lazy to re-structure your code leads quickly to a fragile and generally unmaintainable pile of overcooked spaghetti. Try not to do that. https://en.wikipedia.org/wiki/Spaghetti_code
P.S.: If the only control-structure you're aware of is goto and if it's essentially impossible to not use goto. The solution is to get a basic understanding of the language, first.
Ok thanks guys, I got it working (thx shadder). Btw Flaze07 I'm using Dev C++, just cause my computer is really shit so I need something that won't slow it down. P.S I used goto and cls a lot cause I'm more familiar with cmd.