//using visual studio 2010 express
#include <iostream>
#include <cstdlib>
#include <time.h>
usingnamespace std;
int easygame(){
int enemyHealth = 5;
int hit;
hit = rand() % 5 + 1;
enemyHealth = -hit + enemyHealth;
return enemyHealth;
}
int medgame(){
int enemyHealth = 7;
int hit;
hit = rand() % 10 + 1;
enemyHealth = -hit + enemyHealth;
return enemyHealth;
}
void hardgame( unsignedint playerHealth = 10, unsignedint enemyHealth = 10){
cout <<"enemy: "<< enemyHealth << endl;
cout <<"player: "<< playerHealth << endl;
while(playerHealth>0){
unsignedint hit = rand() % 5 + 1;
unsignedint enemyhit = rand() % 5 + 1;
playerHealth = playerHealth - enemyhit;
enemyHealth = -hit + enemyHealth;
cout <<"enemy: "<< enemyHealth << endl;
cout <<"player: "<< playerHealth << endl;
system("pause");
}
}
int main()
{
cout <<"\tWelcome to my text based game!\n";
char userName[100];
cout <<"\nPlease enter your username: ";
cin >>userName;
cout <<"Hello, "<<userName<<"!\n\n";
cout <<"Please pick your gender: \n";
for (;;){
cout <<"1 - male\n";
cout <<"2 - female\n";
int gender;
cout <<"Pick your gender: ";
cin >>gender;
switch (gender)
{
case 1:
cout <<"You are male.\n";
break;
case 2:
cout <<"You are female.\n";
break;
default:
cout <<"Error - Invalid input; only 1 or 2 allowed.\n";
continue;
}
break;
}
for (;;){
int difficulty;
cout <<"\nPick your level difficulty: \n";
cout <<"1 - Easy\n";
cout <<"2 - Medium\n";
cout <<"3 - Hard\n";
cout <<"Pick your level difficulty: ";
cin >>difficulty;
switch (difficulty)
{
case 1:
cout <<"You picked Easy.\n\n";
system ("cls");
break;
case 2:
cout <<"You picked Medium.\n\n";
system ("cls");
break;
case 3:
cout <<"You picked Hard.\n\n";
system ("cls");
hardgame();
break;
default:
cout <<"Error - Invalid input; only 1,2 or 3 allowed.\n";
continue;
}
break;
}
system("PAUSE");
return 0;
}
I keep on getting really big numbers after three or four loops of "void hardgame" instead of the program ending.
I know this is probably a really simple and easy fix but I am new to C++.
What is wrong here?
You made everyone's health unsigned integers, so they can't be negative. Integers wrap, meaning that
1 2 3
unsigned x = 0;
x -= 1;
cout << x; //now x is a big number. 2^32-1, to be precise
It would be fine if health was a multiple of damage. That way, 0 would be reached. However that is not the case and wrapping happens. The solution is to use simple (signed) int.