I'm teaching my self C++ on the side and i realize this question may seem remedial to some. In the game I'm making as part of the learning process I want the user to be able to pick a difficulty and when they pick one or the other the random number value range changes. The compiler I'm using is x-Code by the way. Here is the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
int secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
int secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
int secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
The 2 errors occur in case 2 and 3 where i try to redefine the value of secretNumber.
The case blocks do not open different scopes, but are rather part of the same block. Your code (considering only scopes) looks somehow similar to:
int secretNumber;
{
int secretNumber = rand() % 10 + 1;
...
int secretNumber = rand() % 50 + 1;
...
int secretNumber = rand() % 100 + 1;
}
Three different variables with the same name are being declared in the same scope, which is not allowed in the language. Note that all three declarations inside the switch would also hide the variable declared in the outer scope, which is probably not what you want anyway.
It looks like you have some background in some other languages - perhaps a functional language and perhaps some JavaScript.
One of the key features of C++ is scoping. Variables (named value holders) have a lifetime of the scope they are within, and variables are only visible within the scope they are defined. (Not to be confused with objects, which through pointers and allocation can be teased off the stack and into heap memory, only to be lost when the variables with their address go out of scope if they are not properly deallocated).
{
int i = 1;
}
std::cout << "i is " << i << std::endl; // compiler error, i does not exist here.
void foo() {
int i = 1;
}
void bar() {
foo();
std::cout << i << std::endl; // compiler error, i does not exist here.
}
Also, unless decorated as "const", C++ variables are mutable - they can be changed.
int i = 1;
i = 2;
std::cout << i << std::endl; // writes 2, not 1.
So: your code is not 'redefining' secretNumber, it is shadowing the previous definition, hiding it for the duration of the current scope. Thus when you assign a value to the inner version, the "secretNumber" visible to code outside the scope is untouched.
#include <iostream>
int main()
{
int foo = 1; // outer foo
std::cout << "Originally, foo = " << foo << std::endl;
{
int foo = 2; // inner foo
std::cout << "Inside the inner scope, foo = " << foo << std::endl;
}
// inner foo doesn't exist here, so it references outer foo.
std::cout << "But the original foo still exists, " << foo << std::endl;
}
What you actually want to do is simply assign a new value to the original secretNumber variable you declared in the outer scope, since that is the only variable named "secretNumber" available to code in that scope.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
This is one reason why many C++ programmers choose to use prefix and suffix notations to distinguish certain types of variables:
#include <iostream>
class Foo {
public:
int m_i; // member variable, m_xxx
Foo(int); // constructor taking an int.
};
static int s_i;
Foo::Foo(int i_) // arguments use _ suffix
{
int i = i_; // local value of i
i *= 3;
m_i = i; // we're assigning it the local value, not the argument.
}
int main()
{
int i = 1;
Foo foo(2);
s_i = 3;
std::cout << "i = "<<i<<", foo.m_i = "<<foo.m_i<<", s_i = "<<s_i<< std::endl;
}
Live Demo: http://ideone.com/dSTwPT
You are getting the compile time error because you are redeclaring the same variable within the same scope (case statement block level scope). You need to delete int before secretNumber in all the case statements. Doing otherwise, the secretNumber variable declared at the while loop block level will stay undefined.
Related
I must write a program where the user can choose to practice with topic addition or topic multiplication that starts with a self-driven menu.
It must keep track of questions answered right, wrong and the number of questioned asked.
Which my current program is doing within each module(topic). Example Addition keeps track of the questions while the user is practicing Addition only and Multiplication does the same.
However, they are not being feedback to main, so they are not being added or displayed before the user can select another topic to practice or to exit the program.
Currently it is only to keeping track of the question (right /wrong/ total of questions) for each module (topic).
My goal is for the values to be passed to main and display the total number (right /wrong/ total of questions) before the user exits the program, but at the same time I must display the number of question in the Additional Topic and the Multiplication topic and provide a total.
Example Table of Addition, Multiplication and Totals ?
This is the code I have to start with. Can someone help me in how to code to return values of the (right /wrong/ total of questions) of the two topics and accomplish to display something like the table information.
******************************************************************************* /
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string> // String managment funtions.
#include <iostream> // For input and output
#include <cmath> // For math functions.
#include <math.h>
#include <cstdlib>
using namespace std;
////////////////////////////////////////////////////////////////////////
// Implementing menu driven programs.
// Function Prototypes.
int menu();
void sums();
void products();
int main()
{
srand(time(0));
int option;
do {
option = menu();
switch (option) {
case 1: {
sums();
break;
}
case 2: {
products();
break;
}
default:
cout << "Program exit" << endl;
}
} while (option != 6);
return 0;
}
int menu()
{
cout << "Please select an option" << endl;
cout << "1) Practice with Addition " << endl;
cout << "2) Pratice with Multiplication " << endl;
cout << "3) Exit the program " << endl;
int option;
cin >> option;
return option;
}
void sums()
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValue = 10;
const int maxValue = 99;
int y = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is x "<< x << endl;
cout << "What is " << x << " + " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x + y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
void products()
{
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValueOne = 0;
const int maxValueOne = 9;
const int minValueTwo = 10;
const int maxValueTwo = 99;
int y = (rand() % (maxValueOne - minValueOne + 1)) + minValueOne;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValueTwo - minValueTwo + 1)) + minValueTwo;
// cout<< " the random number is x "<< x << endl;
cout << " What is " << x << " x " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x * y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
}
I would create a structure that contains the number of total answers and number of correct answers—the incorrect ones can be inferred—and then pass a reference to an instance of the structure to the respective sums() and products() functions.
Those functions can then populate the structure elements and when they return, your main function can read them out, knowing exactly how many questions were asked, how many were answered, or whatever other information you want to record and retrieve.
When the user inputs 'Y' to try again, the game runs but only gives the user 1 try instead of 3 tries. Program works fine the first time it runs with 3 tries. I'm guessing something is wrong with my loop that it does not reset the number of tries? Let me know if there's any other way I could write my code to make it cleaner/better. Thanks a bunch.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int guessNum;
int randomNum;
int Tries = 0;
int startGame()
{
cout << "Number: ";
cin >> guessNum;
return guessNum, Tries;
}
int main(int a, int b)
{
while (true) {
a = guessNum;
b = Tries;
char ans;
// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;
// Introduction
cout << "Guess a number between 1 to 20. You have three attempts." << endl;
do
{
startGame();
if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}
else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}
Tries++;
}
while (guessNum != randomNum && Tries < 3);
if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}
else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}
cout << "Try again?";
cin >> ans;
cin.ignore();
if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}
}
}
EDITED V1
#include <iostream>
#include <ctime>
using namespace std;
int guessNum;
int startGame()
{
cout << "Number: ";
cin >> guessNum;
return guessNum;
}
int main()
{
while (true) {
int randomNum;
int Tries = 0;
char ans;
// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;
// Introduction
cout << endl << "Guess a number between 1 to 20. You have three attempts." << endl;
do
{
startGame();
if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}
else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}
Tries++;
}
while (guessNum != randomNum && Tries < 3);
if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}
else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}
cout << "Try again? Y/N: ";
cin >> ans;
cin.ignore();
ans = toupper(ans);
if (ans == 'N')
{
cout << endl << "Thanks for playing!";
break;
}
else
{
Tries = 0;
}
}
}
Actually, your program has several defects.
Firstly, If you wonder why the game behaves unexpected way after the first one, You did not set back the Tries to 0 after playing the game.
And, int startgame() should return only one variable. You are trying to return guessnum and Tries at the same time. The only reason the first game is running as expected is that you are using global variables, which is also considered as a bad practice(Some company may fire you if you use it without any good reason).
Furthermore, you are getting two int function arguments from main call, which is not valid. (main function signature should be int main(void) or int main(int argc, char* argv[])). I am surprised that the compiler did not catch this error.
And the variables (int a, int b) are actually not used. When you find unused variables, it is usually a good practice to remove them for maintainability.
So int Tries = 0; is a global variable. It's set before main().
You basically have
int Tries = 0;
main()
{
while (true) {
do
{
Tries++;
} while(Tries < 3);
}
}
Do you see that for each iteration in while, the value of Tries from the previous iteration is used? You would need to reset it before iterating again.
But there is no reason to have "Tries" as a global variable since you only need to know about it in the while(true)-loop. This is generally the case for a variable - put it to the closest scope possible:
main()
{
while (true) {
int Tries = 0;
do
{
Tries++;
} while(Tries < 3);
}
}
Now it's correctly reset between loops, and it is clear it is only needed for the loop logic.
Try to do the same for you other variables.
Try:
if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}
else
{
Tries = 0;
}
I need help for looping back on the start of the program [C++].
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
int rand_number = rand() % 101;
int number;
int counter = 1;
cout << "NUMBER GUESSING" << endl;
cout << "Try to guess number from 1 to 99: " << endl;
do
{
cout << "Input number: ";
cin >> number;
if (number < rand_number)
{
cout << "Number is too small." << endl;
}
else
{
if (number > rand_number)
{
cout << " Number is too big." << endl;
}
}
number++;
} while (number != rand_number);
cout << "Great! You guessed it in " << number << "th try." << endl;
cout << "Do you want to play again [Y/N]: ";
cin >> Y;
cin >> N;
// dont know how to proceed
return 0;
}
I need help for looping back on the start when it asks me if I want to play again and answer Yes "Y", if I answer No "N" it says Goodbye. Any help would be appreciated, Thanks.
Similar to how you are using a do while, try adding an outer while loop that checks if the N key was pressed
You could create a boolean playAgain which would start as true. If the player says no, set it to false. You can then put your do while in another do while(playAgain). This would loop the game until the player says he does not want to play again.
It is not the most orthodox method but it works :) Use goto.
int main()
{
mylabel:
...
if( <condition> )
{
goto mylabel;
}
...
}
If you want to have a more structured program write your main in anther function, say int func() and loop in main based on the return of the function.
int func()
{
...
if( <condition> )
{
return 1;
}
...
return 0;
}
int main()
{
while(func())
{};
return 0;
}
A very easy way to do this is to use nested while loops. You can use what you already have as the inner loop, then have another outside that that checks if the user has put in a Y or not. It can look something like this:
do {
do {
//Get numbers and check them
//...
} while(number != rand_number);
std::cout << "Some message" << std::endl;
std::cin >> option;
} while(option != 'N');
This goes through your loop, then allows the user to choose to continue. If they choose to go again, it will take them back up to the top of the outer while loop, and keep going until they say to stop.
EDIT:
Here would be the complete code:
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
char option = 'a';
do
{
int rand_number = rand() % 101;
int number;
int counter = 1;
std::cout << "NUMBER GUESSING" << std::endl;
std::cout << "Try to guess number from 1 to 99: " << std::endl;
do
{
std::cout << "Input number: ";
std::cin >> number;
if (number < rand_number)
{
std::cout << "Number is too small." << std::endl;
}
else if (number > rand_number)
{
std::cout << " Number is too big." << std::endl;
}
counter++;
} while (number != rand_number);
std::cout << "Great! You guessed it in " << counter << "th try." << std::endl;
std::cout << "Do you want to play again [Y/N]: ";
std::cin >> option;
} while(option !='N');
std::cout << "Goodbye!" << std::endl;
return 0;
}
This code is working fine, however this whole time I've tried avoiding using the goto statements that you will see in the switch (dice_total) statement.
Without the goto statements, the program will not loop back to the beginning of while (again=='y' || again=='Y'), and instead it keeps looping itself when it reaches the do-while loop.
However, I believe that it is also important to say, that if dice_total is = to the point_total the first time around then the program will function properly, and loop back to the beginning. For example, when the program starts, the first round will generate the point_total, which we will say its 10. Which is a value that will allow the program to continue to the next round, and if the dice_total also gets the same number, 10, the program will say you win, and the loop will work properly. However, if the program reaches the do while loop, and generates a number that isn't 10, but generates a 10 after a few loops, then the program will not loop to the beginning. So what I want to ask, what is wrong with my switch(dice_total) statement, and how can I fix it, to give the program the same effect without using the goto statements?
#include "stdafx.h"
#include <iostream>
#include <random>
#include <string>
using namespace std;
int main()
{
//Declared Variables***********************************
char again = 'y';
int point1;
int point2;
int point_total;
int round_1=1;
int dice1;
int dice2;
int dice_total;
//*****************************************************
//RANDOM SEED******************************************
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int>dist(1, 6);
//*****************************************************
start://TEMPORARY
while (again == 'y'||again=='Y')
{
int round_1 = 1;
system("CLS");
cout << "WELCOME TO THE CRAPS GAME" << endl;
cout << "THROWING ROUND:" << round_1 << " DICES.............." << endl;
point1 = dist(mt);
point2 = dist(mt);
point_total = point1 + point2;
cout << "ROUND: " << round_1 << " First dice is: " << point1 << " and second dice is: " << point2 <<" and the total is:"<<point_total<< endl;
switch (point_total)
{
case 7:
case 11:
cout << "YOU WON CONGRATS PRESS Y TO PLAY AGAIN!!" << endl;
cin >> again;
break;
case 2:
case 3:
case 12:
cout << "YOU LOST, PRESS Y TO TRY AGAIN" << endl;
cin >> again;
break;
default:
do
{
++round_1;
cout << "ROUND " << round_1 << endl;
dice1 = dist(mt);
dice2 = dist(mt);
dice_total = dice1 + dice2;
cout << "THROWING ROUND: " << round_1 << " DICES.............." << endl;
cout << "ROUND 1 DICE TOTAL IS: " << point_total << endl;
cout << "ROUND: " << round_1 << " First dice is: " << dice1 << " and second dice is: " << dice2 << " and the total is:" << dice_total << endl;
switch (dice_total)
{
case 11:
cout << "YOU WON CONGRATS PRESS Y TO PLAY AGAIN!!" << endl;
cin >> again;
goto start;
case 2:
case 3:
case 7:
case 12:
cout << "YOU LOST, PRESS Y TO TRY AGAIN" << endl;
cin >> again;
goto start;
default:
if (dice_total == point_total)
{
cout << "YOU WON CONGRATS PRESS Y TO PLAY AGAIN!!<<endl;
cin >> again;
break;
}//if
else
{
cout << "Going to next round" << endl;
}
}//dice_total
}//do
while (dice_total != point_total);
break;
}//switch point
}//again while
}//main
The problem you're facing is usual when you have too many nested loops in the same function, and is an indicator that you need to refactor parts of your code to be in their own functions.
If you do this, then you have more possibilities to control the flow of your code: in each function you have break and return, and as you can return a custom value, you can use it to determine in the surrounding function if you need to break or return again.
Besides, this gives you the opportunity to put self-explanatory names to your functions, which makes your code clearer for people that look at it for the first time (as it's written, it's so dense that I can't understand it unless I stare at it for some minutes).
An example of what I mean in code:
Before
int main() {
start:
while (a) {
b1();
switch(c) {
case 1:
do {
d();
if (cond) goto start;
} while(e);
break;
}
b2();
}
}
After
int main() {
while (a) {
if (!doStuff1())
break;
}
...
}
bool doStuff1() {
b1();
while (a) {
bool res = doStuff2();
if (res) return true;
}
b2();
...
}
bool doStuff2() {
switch(c) {
case 1:
if (doStuff3()) return true;
}
return false;
}
bool doStuff3() {
do {
d();
if (cond) return true;
} while (e);
return false;
}
How about this design?
bool stop=false;
while(!stop && (again == 'y'||again=='Y'))
{
while(again == 'y'||again=='Y')
{
// ...
break; /* breaks inner while*/
// ...
stop=true;
break; /* breaks inner while, and prevents running outer loop*/
}
}
I am facing difficulties in my C++ code. I am a beginner. Like, only with very basic knowledge of C++. So, I really can't figure a way to do this. I thought of making an RPG game using C++ commands and am close to finishing it. But somehow, I couldn't make a constant health for the hero. Taking a look at the code,
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class player
{ public:
int health = 100;
};
int battle();
void death();
int main()
{
int abc;
player hero;
hero.health = abc;
int a;
int replay = 1;
cout << "You have 100 Hp. \n";
while (replay == 1)
{
srand(time(0));
cout << "\n Press 1 to move forward; 2 To stay. \n";
cin >> a;
if (a == 2)
{
if (rand() % 4 + 1 != 1)
{
cout << "You stay at your place. \n";
}
else
{
cout << "Enemy Attacks! (20 Hp) \n";
//battle(hero.health);
//cout << "\n Press 1 to continue. \n";
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else if (a == 1)
{
if (rand() % 2 + 1 != 1)
{
cout << "You moved forward. No one around. \n";
}
else
{
cout << "You move forward. Enemy attacks! (20 Hp) \n";
battle(abc);
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else
{
cout << "Sorry. Please enter a valid move. \n";
}
}
return 0;
}
int battle(int x)
{
player enemy;
enemy.health = 20;
player hero;
int y;
while (enemy.health >= 0)
{
int eattack = rand() % 15 + 7;
int attack = rand() % 10 + 1;
int escape = rand() % 4 + 1;
cout << "\n Press 1 to attack. 2 to flee \n";
cin >> y;
if (y == 2)
{
if (escape != 1)
{
cout << "Can't escape! \n";
cout << "Enemy attacked! Dealing a damage of: " << eattack << " Hp. \n";
hero.health = hero.health - eattack;
cout << "Your Hp is: " << hero.health;
}
else
{
goto Aftermath;
}
}
else if (y != 1)
{
cout << "Sorry. Please enter a valid response. \n";
}
else
{
cout << "You attack the enemy. \n";
cout << "You deal a damage of: " << attack;
enemy.health = enemy.health - attack;
if (enemy.health >= 0)
{
cout << "\n Enemy attacks you, dealing: " << eattack << " Hp damage.";
hero.health = hero.health - eattack;
cout << "\n You have: " << hero.health << " Hp left.";
}
}
if ((hero.health <= 0) || (hero.health == 0))
{
death();
enemy.health = -1;
}
}
if (hero.health > 0)
{
cout << "\n Enemy fainted!";
//cout << "You found Hp Potion! Your Hp was refilled.";
}
Aftermath:
if ((hero.health > 0) && (enemy.health > 0))
{
cout << "Escaped Successfully! \n";
}
return x;
}
void death()
{
cout << "You died!";
}
As you see, I have called for battle(abc) and battle(hero.health) [which I have commented for now] but the problem is, it says "Too many arguments to function int battle(). Previously, I simply avoided parameters and created object "hero" in the battle method itself. But every time you get through a battle sequence, it comes back and declares it again, thus making its health refill. [Look at if (hero.health > 0) ]
I really don't know about global variables and all that. I just want to know if there is a workaround or a way to solve this parameter problem. Any other suggestions to have health as a 'constant' and not declared every time is also warmly accepted. Thank you so much!
P.S. Suggestions for shortening the code also accepted but please, I am a beginner. So advanced strategies are beyond my skills right now. I take time to grasp concepts.
You declare the function before the main method, and then you implement the function after the main method.
The problem is, you implement the function as:
int battle(int x)
but this doesn't match your declaration:
int battle();
Just change your function declaration block so the battle function matches the expected signature:
int battle(int x);
void death();
That will get your code compiling, but you are still a number of steps from getting this to work.
I'll give you one starter: instead of passing in the hitpoints into battle, pass the entire player.
void battle(Player &player)
{
// ...
}
Then you can modify the player's hitpoints directly in the battle function.
You would then call this with:
battle(hero);