C++ Bowling Simulator Program - c++

I recently received an assignment to create a bowling program in C++ that simulates two people bowling and outputs the correct score for each frame. My program works by first generating all the throws for each frame and then accumulating the score afterwards in a separate method. I was able to get the program to work when the player bowls a non-perfect game and a perfect game, but I am having problems with when a player bowls all spares. I rigged the code to make it so I have 9 for a first throw and 1 for the second throw (this is in frame.cpp). The total should be 190, but I am getting 191 and I can't seem to find the error. Each bowling class contains an array of 11 frames. I know there are only 10 frames but this is to account for if the player gets a strike on the tenth frame. Any help would be appreciated, thanks.
Here is the frame. h file
#ifndef FRAME_H
#define FRAME_H
#include<iostream>
using namespace std;
class Frame
{
private: int throw1;
int throw2;
int score;
bool spare;
bool strike;
public: Frame();
int genThrow(int size);
int getFirstThrow();
int getSecondThrow();
int getScore();
void setScore(int);
void setFirstThrow(int value1);
void setSecondThrow(int value2);
void setStrike(bool value);
void setSpare(bool value);
bool getStrike();
bool getSpare();
};
#endif
Here is the frame.cpp file
#include "Frame.h"
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
Frame::Frame()
{
spare = false;
strike = false;
throw1 = 0;
throw2 = 0;
score = 0;
}
//generates a random throw
int Frame::genThrow(int size)
{
int randomNumber = 0;
if (size < 10 || throw1 != 10)
{
randomNumber = 0 + rand() % (11 - throw1); //generate a number between 0 and 10
}
else
{
randomNumber = 0 + rand() % (11);
}
//cout << randomNumber << endl;
return randomNumber;
}
//get first throw
int Frame::getFirstThrow()
{
return throw1;
}
//get second throw
int Frame::getSecondThrow()
{
return throw2;
}
//get the score of both throws
int Frame::getScore()
{
return score;
}
//set the score
void Frame::setScore(int value)
{
score = value;
}
//set the first throw
void Frame::setFirstThrow(int value1)
{
//throw1 = genThrow(value1); //normal generator
//throw1 = 10; //strike game rigged
throw1 = 9; //spare game rigged
}
//set the second throw
void Frame::setSecondThrow(int value2)
{
//throw2 = genThrow(value2); //normal generator
throw2 = 1; //spare game rigged
//throw2 = 10; //strike game rigged
}
//set the strike
void Frame::setStrike(bool value)
{
strike = value;
}
//set the spare
void Frame::setSpare(bool value)
{
spare = value;
}
//get the strike
bool Frame::getStrike()
{
return strike;
}
//get the spare
bool Frame::getSpare()
{
return spare;
}
Here is the bowling.h file
#ifndef BOWLING_H
#define BOWLING_H
#include "Frame.h"
#include<iostream>
using namespace std;
class Bowling
{
private: Frame a[11];
public: void accumulateScore();
void bowl();
void printData();
};
#endif
Here is the bowling.cpp file
#include "Bowling.h"
#include<iostream>
using namespace std;
//takes all of the throw values after bowling and accumulates the correct score
void Bowling::accumulateScore()
{
int totalSum = 0;
for (int x = 0; x < 10; x++)
{
if (a[x].getFirstThrow() + a[x].getSecondThrow() < 10) //not a strike or spare
{
totalSum += a[x].getFirstThrow() + a[x].getSecondThrow();
a[x].setScore(totalSum);
}
else if (a[x].getFirstThrow() == 10) //throws a strike
{
if (x < 9)
{
totalSum += 10 + a[x + 1].getFirstThrow() + a[x + 1].getSecondThrow();
if (a[x + 2].getStrike() == true)
{
totalSum += 10;
}
a[x].setScore(totalSum);
}
}
else if (a[x].getFirstThrow() + a[x].getSecondThrow() == 10) //throws a spare
{
if(x < 10)
{
totalSum += 10 + a[x + 1].getFirstThrow();
a[x].setScore(totalSum);
}
}
}
//player got the 11th frame
if (a[9].getStrike() == true)
{
totalSum += 10 + a[10].getFirstThrow() + a[10].getSecondThrow();
a[9].setScore(totalSum);
}
else if (a[9].getSpare() == true)
{
totalSum += 10;
a[9].setScore(totalSum);
}
}
void Bowling::bowl()
{
//generate all throws and store them in the frames
for (int x = 0; x < 10; x++)
{
a[x].setFirstThrow(x);
if (a[x].getFirstThrow() == 10)
{
a[x].setStrike(true);
}
if (a[x].getStrike() == false)
{
a[x].setSecondThrow(x);
if (a[x].getFirstThrow() + a[x].getSecondThrow() == 10)
{
a[x].setSpare(true);
}
}
a[x].setScore(a[x].getFirstThrow() + a[x].getSecondThrow());
}
//play the 11th frame if they got a strike on the tenth frame
if(a[9].getStrike() == true)
{
a[10].setFirstThrow(10);
if (a[10].getFirstThrow() == 10)
{
a[10].setStrike(true);
}
a[10].setSecondThrow(10);
cout << "The second throw is this value: " << a[10].getSecondThrow() << endl;
if (a[10].getSecondThrow() == 10)
{
a[10].setStrike(true);
}
else if (a[10].getFirstThrow() + a[10].getSecondThrow() == 10)
{
a[10].setSpare(true);
}
a[9].setScore(a[10].getFirstThrow() + a[10].getSecondThrow());
}
}
void Bowling::printData()
{
for (int x = 0; x < 10; x++)
{
cout << "*****************************" << endl;
cout << "Frame " << x + 1 << endl;
cout << "First throw: ";
if (a[x].getStrike() == true)
{
cout << "Strike!" << endl;
}
else
{
cout << a[x].getFirstThrow() << endl;
}
cout << "Second throw: ";
if (a[x].getStrike() == false)
{
if (a[x].getSpare() == true)
{
cout << "Spare!" << endl;
}
else if(a[x].getSpare() == false)
{
cout << a[x].getSecondThrow() << endl;
}
else
{
cout << endl;
}
}
cout << "Score: " << a[x].getScore();
cout << endl;
}
if (a[9].getStrike() == true)
{
cout << "*****************" << endl;
cout << "Frame 11" << endl;
cout << "First throw: ";
if (a[10].getStrike() == true)
{
cout << "Strike!" << endl;
}
else
{
cout << a[10].getFirstThrow() << endl;
}
cout << "Second throw: ";
if (a[10].getStrike() == false)
{
if (a[10].getSpare() == true)
{
cout << "Spare!" << endl;
}
else
{
cout << a[10].getSecondThrow() << endl;
}
}
else
{
cout << "Strike!" << endl;
}
//cout << "Score: " << a[10].getScore();
cout << endl;
}
}
Here is where I test it in main
#include "Bowling.h"
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int dummy = 0;
//create two players that can bowl
Bowling player1;
Bowling player2;
int player1Score = 0;
int player2Score = 0;
//have the players bowl their throws before accumulating score
player1.bowl();
player2.bowl();
//accumulate the score after all of the throws have been done
player1.accumulateScore();
player2.accumulateScore();
//print player 1 data
cout << "Here are the throws and score for the first player: " << endl;
player1.printData();
//spacing
cout << endl << endl;
//print player 2 data
cout << "Here are the throws and score for the second player: " << endl;
player2.printData();
cout << "Enter a dummy number:" << endl;
cin >> dummy;
return 0;
}

Related

Game exp and level up

I've been making my C++ text game. Gone fairly well so far. I had a few delays with some mistakes I have made. Got most of that fixed up. Now I am working on the level up and experience points system. And IDK how to keep that number updated so it's knowns that it reaches level 55. Here's the code:
(first program ever)
//#include <windows.h>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string.h>
using namespace std;
bool gameRunning = true;
char Yarra = 'P';
char Dragon = 'D';
char map[28];
class Player;
class Enemy {
private:
int lvl;
public:
int health;
Enemy() {
int randomNumber = rand();
int enemy_life = (randomNumber % 7) + 2;
health = enemy_life;
lvl = 1;
}
void attack(Player& p);
friend class Player;
};
class Final_dragon {
public:
int lvl;
int health;
Final_dragon() {
health = 10;
lvl = 2;
}
void attack(Player& p);
friend class Player;
};
class Player {
private:
public:
int health;
int exp;
int lvl;
Player(bool hero) {
if(hero) {
health = 100;
lvl = 1;
exp = 0;
} else {
health = 1;
}
}
void attack(Enemy& e);
void lvlUp(Player& p);
friend class Enemy;
friend class Final_boss;
};
void Player::attack(Enemy& e) {
int randomNumber = rand();
int dmg = (randomNumber % 2) + 0;
cout << "\nYou've done " << dmg << " damage!" << endl;
e.health -= dmg;
}
void Enemy::attack(Player& p) {
// int randomNumber = rand();
// int dmg = (randomNumber % 20) + 0;
int dmg = 2;
cout << "\nThe Enemy does " << dmg << " damage to you!\n" << endl;
p.health -= dmg;
}
void Player::lvlUp(Player& p) {}
int main() {
int display;
char playerInput{};
char move;
char action;
map[0] = Yarra;
map[27] = Dragon;
cout << "Map: " << map[0];
for(display = 1; display < 27; display++) {
map[display] = '*';
cout << map[display];
}
cout << map[27];
cout << endl
<< endl
<< "Press '1' Travel to another space on the board \n"
<< "Press '2' Dismount and explore the current space " << endl;
display = 0; // Start at map[0]
while(gameRunning == true) {
Player p(true);
do {
cin >> move; // Get user input
if(move == '1') // If input is '1'
{
srand(time(0));
int dice = (int)(1 + rand() % 6);
cout << "You moved: " << dice << " steps" << endl;
map[display] = '*'; // Remove old location of player
display = display + dice; // Increase display location
map[display] = 'P'; // Insert player in new map array location
cout << "Your current location: " << display
<< endl; // Player current location
}
if(move == '2') // If input is '2'
{
cout << "Your current location: " << display
<< endl; // Player current location
srand(time(0));
int monster_dice = (int)(1 + rand() % 14); // Random monster
cout << "Monster location: " << monster_dice << endl
<< endl; // monster location
if(display == monster_dice) {
cout << "You've encountered a Enemy! Press \"a\" to attack"
<< endl
<< endl;
Enemy e;
cout << "HP of the monster you encounter: " << e.health << endl;
cin >> action;
if(action == 'a' || action == 'A') {
do {
p.attack(e);
cin.ignore(1);
if(p.health <= 0) {
system("CLS");
cout << "\t\n\nYou have died..." << endl;
cout << "\t\nGAME OVER!" << endl << endl;
return 0;
}
if(e.health >= 1) {
e.attack(p);
cin.ignore(1);
}
} while(e.health >= 0);
if(e.health <= 0) {
cout << "\n\nYou defeat the Enemy! *Vistory Music*\n"
<< endl;
cout << "You gained " << 100
<< " experience from the Boar." << endl;
p.exp += 100;
}
if(p.exp >= 200 && p.exp <= 300) {
cout << "\nYou've gone up to level 2!" << endl;
p.lvl++;
p.health += 50;
}
if(p.exp >= 300 && p.exp <= 400) {
cout << "\nYou've gone up to level 3!" << endl;
p.lvl++;
p.health += 40;
}
if(p.exp >= 400 && p.exp <= 500) {
cout << "\nYou've gone up to level 4!" << endl;
p.lvl++;
p.health += 50;
}
if(p.exp >= 600 && p.exp <= 700) {
cout << "\nYou've gone up to level 5!" << endl;
p.lvl++;
p.health += 50;
}
}
}
}
} while(move != '1');
for(int x = 0; x <= 28; x++) {
cout << map[x];
}
if(display == 27 || display > 27) // If player at end of map array, end game
{
Final_dragon d;
if(p.lvl == 2) {
cout << "Ready for the fight" << endl;
} else {
system("CLS");
cout << "\nAlas, the dragons eyes stare at you and places you "
"under his spell. You try to move but fail to do so and "
"find yourself torched by the dragons fire.If only you had "
"more experience, you could have seen it coming."
<< endl;
cout << "\t\nGAME OVER!" << endl
<< endl; // Show text explaining why game ended
}
}
}
}
while(gameRunning == true) {
Player p(true);
You create a new hero player in each iteration. All experience and levels gained will be reset back to a newly created Player.
Create the Player before the loop:
Player p(true);
while(gameRunning == true) {
If you want the player to be able to fight the dragon if he/she is at least at the same level as the dragon, change the condition from if(p.lvl == 2) to if(p.lvl >= d.lvl).
You should seed the pseudo random number generator, i.e., call srand(), only once during the programs execution. Call it once when the program starts and never again.
If you are using C++11 or newer, you should use the <random> library instead of srand() and rand(). The same rule applies for those modern generators. Only seed them once.
A function to create a random number could look like this:
#include <random>
// A function to return a random number generator.
inline std::mt19937& generator() {
// the generator will only be seeded once since it's static
static std::mt19937 gen(std::random_device{}());
return gen;
}
// A function to generate int:s in the range [min, max]
int my_rand(int min, int max) {
std::uniform_int_distribution<int> dist(min, max);
return dist(generator());
}

Two different pointer arrays, but they both point to the same address

I'm making a blackjack game and I have a pointer arrays for my dealer's and player's hand. The issue is that when I randomly generate cards to be stored in the array, they both have the same cards. Not sure if it is because they both point to the same address or something I haven't noticed.
#include <iostream>
#include <ctime>
#include <random>
#include <iomanip>
#include <cstdlib>
using namespace std;
class Blackjack
{
public:
Blackjack();
void playGame();
int pbalance;
int betamount;
int loop= 1;
int *playerbalances;
int pbalan,pbal;
void firstbalance();
void clearhand();
private:
int dhandSize;
int phandSize;
int dhandSum;
int phandSum;
int phit;
int pstand;
bool playerDone;
bool dealerDone;
void addPlayerCard();
void addDealerCard();
void printHand();
void sumHands();
void playerbalance();
void playerbet();
int *dhand[];
int *phand[];
};
Blackjack::Blackjack()
{
srand(time(0));
dhandSize = 0;
phandSize = 0;
dhandSum = 0;
phandSum = 0;
playerDone = false;
dealerDone = false;
}
void Blackjack::playGame()
{
if (pbal>0)
{
// Start the player and dealer with two cards
playerbet();
addPlayerCard();
addPlayerCard();
addDealerCard();
addDealerCard();
sumHands();
printHand();
if (dhandSum == 21)
{
cout << "Dealer has blackjack. Dealer wins.\n";
clearhand();
return;
}
else if (phandSum == 21)
{
cout << "Player has blackjack. Player wins.\n";
clearhand();
return;
}
while (dealerDone == false || playerDone == false)
{
if (playerDone == false)
{
cout << "Would you like to hit? (1 - Yes, 2 - No)\n";
cin >> phit;
if (phit == 1)
{
addPlayerCard();
printHand();
sumHands();
if (phandSum > 21)
{
cout << "Player's hand exceeded 21. Player loses"<<endl;
pbalan =(pbalan - betamount);
cout <<"[you lose $"<<betamount<<" of money!]"<<endl;
cout <<"[your current balance is: $"<<pbalan<<"]"<<endl;
clearhand();
return;
}
}
}
if (playerDone == false)
{
cout << "Would you like to stand? (1 - Yes, 2 - No)\n";
cin >> pstand;
}
if (pstand == 1)
{
playerDone = true;
}
if (dhandSum < 17 && dealerDone != true)
{
addDealerCard();
printHand();
sumHands();
if (dhandSum > 21)
{
cout << "Dealer hand exceeded 21. Dealer loses.\n";
return;
}
}
else if (dhandSum >= 17)
{
dealerDone = true;
}
if (phandSum == 21 && dhandSum == 21)
{
cout << "Push, player and dealer reached 21.\n";
return;
}
else if (phandSum == 21)
{
cout << "Player reached 21. Player wins.\n";
return;
}
else if (dhandSum == 21)
{
cout << "Dealer reached 21. Dealer wins.\n";
pbalan =(pbalan - betamount);
cout <<"[you lose $"<<betamount<<" of money!]"<<endl;
cout <<"[your current balance is: $"<<pbalan<<"]"<<endl;
return;
}
if ((playerDone == true && dealerDone == true) || (phandSize == 5 && phandSize == 5))
{
if (dhandSum < phandSum)
{
cout << "Sum of your hand exceeds the dealer's sum of " << dhandSum << "! You win!";
return;
}
else if (phandSum == dhandSum)
{
cout << "Dealer sum of " << dhandSum << " is equal to the sum of your hand. Tie game.";
return;
}
else if (dhandSum > phandSum)
{
cout << "Sum of your hand is lower than the dealer's sum of " << dhandSum << ". You lose!"<<endl;
pbalan =(pbalan - betamount);
cout <<"[you lose $"<<betamount<<" of money!]"<<endl;
cout <<"[your current balance is: $"<<pbalan<<"]"<<endl;
return;
}
}
}
}
}
void Blackjack::clearhand()
{
for (int i = 0; i < dhandSize; i++) { delete dhand[i]; }
for (int i = 0; i < phandSize; i++) { delete phand[i]; }
phandSize = 0;
dhandSize = 0;
}
void Blackjack::firstbalance()
{
cout << "Welcome to Blackjack" <<endl;
cout << "please enter a starting balance: " <<endl;
cin >> pbal;
playerbalances = &pbalan;
*playerbalances = pbal;
}
void Blackjack::playerbet()
{
cout << "how much do you want to bet?"<<endl;
cin >> betamount;
}
void Blackjack::addPlayerCard()
{
if (phandSize <= 5)
{
*phand[phandSize] = 1 + (rand() % 13);
phandSize++;
}
else
{
cout << "Sorry. You have reached the maximum number of cards (5)." << endl;
playerDone = true;
}
}
void Blackjack::addDealerCard()
{
if (dhandSize <= 5)
{
*dhand[dhandSize] = 1 + (rand() % 13);
dhandSize++;
}
else
{
dealerDone = true;
}
}
void Blackjack::printHand()
{
cout << "Your current hand is...\n";
for (int i = 0; i < phandSize; i++)
{
cout << " -" << *phand[i] << "- \n\n";
}
cout << "Dealer's current hand is...\n";
for (int j = 0; j < dhandSize; j++)
{
cout << " -" << *dhand[j] << "- \n\n";
}
}
void Blackjack::sumHands()
{
dhandSum = 0;
phandSum = 0;
for (int i = 0; i < dhandSize; i++)
{
dhandSum += *dhand[i];
}
for (int j = 0; j < phandSize; j++)
{
phandSum += *phand[j];
}
cout << "Current player hand sum is: " << phandSum << endl;
}
using namespace std;
int main()
{
int exitGame = 1;
int i = 0;
Blackjack play;
if (i<1)
{
play.firstbalance();
i++;
}
do
{
play.playGame();
play.clearhand();
cout << "\nWould you like to play again? (1 - Yes, 2 - No)\n";
cin >> exitGame;
}
while (exitGame == 1);
cout << "\nThanks for playing!\n";
return 0;
}
The dealer cards should be different from the player cards but they are identical when you run the program.
The shows code declares a class with two members, as follows:
int *dhand[];
int *phand[];
These are the two members of the class, but this is not valid, standard C++. Variable-length arrays are not standard C++.
As such, the entire logic in this code becomes unspecified behavior. The behavior you observed was that the two arrays appear to be the same. Right. That's what unspecified behavior means, and this appears to be the behavior that results with your specific C++ compiler and implementation. Your C++ compiler appears to implement this by creating a class member whose size is a grand total of 0 bytes (after all, the size of the array is not specified, so it's nuthin'), with the expectation that this will be the last class member, and the application will be responsible for allocating some extra memory in addition to the one that's required for an instance of this object, in order to achieve a pseudo-array in this fashion.
But with two class members declares thusly, this ends up with two class members that are effectively one and the same. Which is the behavior you observed. Other C++ compilers may very well report a compilation error, since the program being ill-formed, with respect to the C++ standard.
To fix this issue you should replace these class members with proper arrays. Perusing the shown code, it looks like you expect these arrays to be, essentially, variably-sized arrays. This is what std::vector is for, and your C++ book should have one or more chapters that fully explain how to use std::vector to implement an array-like object that can grow and shrink in size, accordingly.

C++ Two dimensional array multiplication table

I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10). For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':
1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40
I can't get the user's input to calculate correctly when using the for loop.
Well you can try this to get that output
#include<iostream>
using namespace std;
int main()
{
int n; //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
table[i][0] = i + 1;
table[i][1] = n;
table[i][2] = table[i][0] * table[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}
Output
SOLVED: Everything seems to be working now!! Here's the code:
#include <iostream>
#include<cstdlib>
#include<iomanip>
#include <ctime>
using namespace std;
void displayTable(int table[10][3]);
bool testMe(int testTable[10][3]);
void createTables(int testTable[10][3], int ansTable[10][3], int
usersChoice);
bool AllAnswersAreTested(bool tested[10]);
void gradeMe(int testTable[10][3], int ansTable[10][3]);
void displayMenu();
int main()
{
srand(time(NULL));
int userInput = 0;
int tableChoice = 0;
int myTable[10][3] = {0};
int testTable[10][3];
int ansTable[10][3];
bool tested = false;
do
{
displayMenu(); //Display the menu of choices
cin >> userInput;
cout << endl;
switch (userInput) //Validate menu choices 1-4
{
case 1: //Display a users choice of table
displayTable(myTable);
break;
case 2: //Test user on users choice of table
cout << "What times table test would you like to take? > ";
cin >> tableChoice;
createTables(testTable, ansTable, tableChoice);
tested = testMe(testTable);
if (tested)
{
gradeMe(testTable, ansTable);
}
break;
case 3: //Display a new table of the users choice
displayTable(myTable);
break;
case 4: //Quit program menu option
cout << "Program ending.\n";
return 0;
default: //Invalid entry
cout << "You entered an invalid item number. Please enter a number from 1 to 4.\n";
cout << endl;
}
} while (userInput != 4);
return 0;
}
void displayTable(int myTable[10][3])
{
int num; //initialize local variables
//Ask the user what times table they would like to review
cout << "What times table would you like to review?" << endl;;
cout << "Please enter a value from 1 to 12 > \n";
cout << "\n";
cin >> num;
cout << endl;
for (int i = 0; i < 10; i++)
{
myTable[i][0] = i + 1;
myTable[i][1] = num;
myTable[i][2] = myTable[i][0] * myTable[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << setw(3)<< myTable[i][0] << " * " << myTable[i][1] << " = " << myTable[i][2] << endl;
}
cout << endl;
}
void createTables(int testTable[10][3], int ansTable[10][3], int usersChoice)
{
for (int i = 0; i < 10; i++)
{
testTable[i][0] = i + 1;
testTable[i][1] = usersChoice;
testTable[i][2] = 0;
ansTable[i][0] = i + 1;
ansTable[i][1] = usersChoice;
ansTable[i][2] = usersChoice * (i + 1);
}
}
bool testMe(int testTable[10][3])
{
bool tested[10] = { false, false, false, false, false,false, false, false, false, false };
while (!AllAnswersAreTested(tested))
{
int index = rand() % 10;
if (tested[index] == false)
{
int randomNum = testTable[index][0];
int tableChoice = testTable[index][1];
int answer;
cout << "What is " << randomNum << " X " << tableChoice << " = ";
cin >> answer;
testTable[index][2] = answer;
tested[index] = true;
}
}
return true;
}
bool AllAnswersAreTested(bool tested[10])
{
for (int i = 0; i < 10; i++)
{
if (tested[i] == false)
{
return false;
}
}
return true;
}
void gradeMe(int testTable[10][3], int ansTable[10][3])
{
int correctAnswers = 0;
for (int i = 0; i<10; i++)
{
if (testTable[i][2] == ansTable[i][2])
{
correctAnswers++;
}
}
int score = (correctAnswers * 10);
if (score == 100)
{
cout << "You passed the test! PERFECT SCORE!!" << endl;
cout << endl;
}
else if (score >= 70)
{
cout << "You passed the test. Your Score is: ";
cout << score;
cout << endl;
}
else if (score < 70)
{
cout << "You did not pass the test. Your Score is: ";
cout << score;
cout << endl;
}
}
//Display the menu function
void displayMenu()
{
cout << " Multiplication Tables" << endl;
cout << endl;
cout << " 1. Review MyTable" << endl;
cout << " 2. Test Me" << endl;
cout << " 3. Enter a New Multiplication Table (1-12)";
cout << " 4. Quit" << endl;
cout << " Enter a Menu Item > ";
}
#include <iostream>
using namespace std;
int main()
{
int a[100][100];
for(int i=1;i<10;i++){
for(int j=1;j<10;j++){
a[i][j] = (i)*(j);
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
There is how the output looks like:

Counter adding items to array with remainder

I am creating an RPG shop. It must have items, gold, and item price. Essentially creating an inventory. What i am trying to accomplish is, where the players gold is 0 they cannot add any more items to their inventory, and cannot have negative gold.
When running my code in debug mode it appears to be doing what i want, but when the function exits the amount the player requested has not been countered.
Keep in mind i am still new to c++.
Thanks
#include <iostream>
#include <string>
using namespace std;
// Global consts
const int numItems = 4;
const string items[numItems] = {"boots", "hats", "cats", "bats"}; // create string array of numItems items.
// Create stuct, that holds:
// Item, gold, price.
struct Inv {
int pInv[numItems] = {0, 0, 0, 0};
int gold = 100;
int itemPrice[numItems] = { 10, 6, 12, 15 };
}inv;
void iniItems();
void printItems();
bool buyItems();
bool sellItems();
int main() {
bool isDone = false;
iniItems();
while (isDone == false) {
printItems();
int choice;
bool x = false;
cout << "\nWhat would you like to do? Enter (" << 1 << "-" << 2 << "): " << endl;
cout << "1: Buy Items. \n2: Sell Items." << endl; cin >> choice; cout << endl;
while (x == false) {
if (choice == 1) {
x = buyItems();
}
if (choice == 2) {
x = sellItems();
}
}
}
system("pause");
// dynamic memory not implemented yet. Must wait for working fix of shoppe.cpp
}
void iniItems() {
cout << "** Shop Inventory: **" << endl;
for (int i = 0; i < numItems; i++) {
cout << i + 1 << " - " << items[i] << " - price: $" << inv.itemPrice[i] << endl;
}
}
void printItems() {
cout << "\n** Player Inventory: **" << endl;
cout << "Gold: $" << inv.gold << endl;
for (int i = 0; i < numItems; i++) {
cout << inv.pInv[i] << " x " << items[i] << endl;
}
}
bool buyItems() {
bool exit = false;
int amount;
const int remainder = 10;
printItems();
cout << "\nEnter -1 to quit." << endl;
cout << "What would you like to buy? Enter (" << 1 << "-" << 4 << "): " << endl;
// Get item info.
while (exit == false) {
int inp;
cout << "Item: "; cin >> inp; cout << endl;
cout << "Amount: "; cin >> amount; cout << endl;
// Check if input is valid.
if (inp > 0 && inp <= numItems) {
if (amount >= 0) {
inv.pInv[inp - 1] = 1 * amount;
inv.gold = inv.itemPrice[inp - 1] / amount;
}
// If gold is 0, make sure the user cannot gain more items.
if (inv.gold <= 0) {
int tmp;
inv.gold = 0;
tmp = remainder - amount;
for (int i = tmp; i >= 0; i++) {
inv.pInv[inp - 1]--;
}
return inv.pInv[inp - 1];
}
if (inp == -1) {
return true;
}
if (inp > numItems) {
cout << "Enter valid number." << endl;
return false;
}
else return false;
}
}
if (exit == true) {
return true;
}
}
So i limited the code down into a do while loop with a counter for the gold, in the buyItems() function.
Here it is, if anyone is interested.
do {
inv.gold -= inv.itemPrice[inp - 1];
++(inv.pInv[inp - 1]);
} while (inv.gold > 0);
if (inv.gold < 0) {
inv.gold = 0;
inv.pInv[inp - 1]--;
}
printItems();

Global and local variables

I was just wondering why playerHp doesn't stay at it's value but resets to 30 each time I call the function. Is it because the variable is local, and if so how do I make it go global from within the function?
I'm new to programming so easy explanations would be nice.
I'm also aware this is "spaghetti code", but if you have the time and energy, cleaning it up would be much appreciated.
#include <iostream>
#include <string>
#include <cstdlib>
//RETURN CODES 1=WON 2=RAN AWAY 3=SLAIN 4=globalWin 5=GlobalLose
using namespace std;
int playerHp;
int enemyHp;
string enemyName;
int dmg()
{
int modifier = rand() % 10 ; // 0-9
return 15 + modifier;
}
int playerDmg()
{
int modifier1 = rand() % 10 ; // 0-9
return 15 + modifier1;
}
int enemyDmg()
{
int modifier2 = rand() % 10 ; // 0-9
return 10 + modifier2;
}
int fight(int playerHp, int enemyHp, string enemyName)
{
int constwhile = 1;
string input;
cout << "You encountered a ";
cout << enemyName <<"\n";
while (constwhile = 1) {
cout << "What will you do?\n";
cout << "Options Fight or Flee: " << flush;
cin >> input;
cin.ignore();
cin.get();
if (input == "Fight" || input == "fight") {
int damageDone = playerDmg();
int finalEnemyHp = enemyHp - damageDone;
cout << "You did ";
cout << damageDone;
cout << " damage" << "\n";
enemyHp = finalEnemyHp;
if (enemyHp < 0) {
cout << "Congratulations! You won!"<<"\n";
return 1;
}
cout << "The monster now has ";
cout << enemyHp;
cout << " health"<<"\n";
} else if (input == "Flee" || input == "flee") {
cout << "You ran away...";
return 2;
} else {
cout<<"Invalid Input"<<"\n";
}
cout << "The enemy fights back!"<< "\n";
int damageDone = enemyDmg();
int finalPlayerHp = playerHp - damageDone;
cout << "It did ";
cout << damageDone;
cout << " damage" << "\n";
playerHp = finalPlayerHp;
if (playerHp < 0) {
cout << "You have been slain...";
return 3;
}
cout << "You now have ";
cout << playerHp;
cout << " health"<<"\n";
}
}
int main()
{
int playerHp = 30;
while(playerHp > 1) {
int fightOutcome = fight(playerHp, rand() % 30, "monster");
if (fightOutcome == 3) {
return 5;
} else if (fightOutcome == 2) {
return 5;
}
}
return 4;
}
The problem are that your global variable are shadow by local defined on function
int fight(int playerHp, int enemyHp, string enemyName)
A fast way to fix your problem is to pass the variables as reference if you want yo keep the value assigned inside function fight
int fight(int &playerHp, int &enemyHp, string &enemyName)
If you want to use a global variable, there must be no local variable or parameter with the same name.
The following will always change the local variable:
int myVar = 0;
void foo(int myVar)
{
myVar = 100;
}
int main()
{
foo(myVar);
cout << myVar;//0
return 0;
}
Now you could either accept a pointer instead of a value, or you could remove the parameter entirely. But I don't really like global pollution, so I would prefer the pointer:
with pointer:
int myVar = 0;
void foo(int* myVar)
{
*myVar = 100;
}
int main()
{
foo(&myVar);
cout << myVar;//100
return 0;
}
without pointer:
int myVar = 0;
void foo()
{
myVar = 100;
}
int main()
{
foo(myVar);
cout << myVar;//100
return 0;
}