how to make a continous loop with second while statement - c++

okay here is my code for a game called pig. I having trouble because the code for the computers turn will only got through one time and once the second turn is reached the first line is only printed. is there any soluction to this or am I just screwed?
`int main () {
int humanTurn=0;
int humanTotalScore=0;
int computerTotalScore=0;
int computerTurn=3;
float diceRoll = 0;
int score = 0;
int computerScore = 0;
int answer = 0;
int humanScore = 0;
int pause = 0;
float computerDiceRoll = 0;
srand(time(0));
cout << "Welcome to the game of pig, the first player to reach to 100 wins."<< endl;
cout << "if you roll a one no score will be recorded and your turn will go the computer"<< endl;
cout << " If you choose to hold, the total score accumilated will be recorded" << endl;
while ((humanTotalScore < 100) && (computerTotalScore < 100)) {
cout << endl;
cout << endl;
cout << "press 1 to roll or 2 to save your score: ";
cin >> answer;
for (int i=0; i<1; i++) {
diceRoll = rand() % 6 + 1;
}
if ((diceRoll > 1) && ( answer == 1)){
cout << endl;
cout << endl;
cout << "your current roll is: " << diceRoll << endl;
cout << endl;
cout << endl;
score += diceRoll;
cout << "Score for this turn is: " << score << endl;
cout << "your total score is: " << humanTotalScore << endl;
cout << endl;
cout << endl;
}
else if (answer == 2){
cout << "your score of: " << score << " will be saved" << endl;
humanTotalScore += score;
score = 0;
}
else {
cout << endl;
cout << endl;
cout << "you rolled a ONE. You lose your turn and any points that were with it" <<endl;
cout << endl;
cout << endl;
score = 0;
computerTurn = score;
}
if ((computerTurn == 0) || (answer == 2)){
computerDiceRoll = rand() % 6 + 1;
here is code that is giving me loop problems.
while ((computerDiceRoll > 1)&& (computerScore <= 20)){
if (computerDiceRoll == 1){
computerScore = 0;
computerTurn = 1;
cout << "Computer rolled a ONE, it is now your turn." << endl;
}
computerDiceRoll = rand() % 6 + 1;
cout << endl;
cout << endl;
cout << "computers roll is : " << computerDiceRoll << endl;
cout << endl;
cout << endl;
computerScore += computerDiceRoll;
if (computerScore >20){
computerTotalScore += computerScore;
computerTurn = 1;
}
cout << "computer current score is : " << computerScore << endl;
cout << "computer total score is: " << computerTotalScore << endl;
cout << endl;
cout << endl;
}
}
}
} `

Related

C++ Left Center Right Dice Game (Game Loop and connecting vectors/arrays to classes/header files)

So i have to code the dice game LCR for a final prject but am having some trouble. First off, I know the code is sloppy and really redundant, that's why im looking for help. I couldn't figure out how to connect the 'chips' int vector and 'name' array into the player.h file. I basically need help writing methods for the chip passing to make the code less redundant. But another problem of mine is having the game loop until just one person has chips. Thanks for any help or advice.
LeftCenterRight.cpp
#include <iostream>
#include <string>
#include <time.h>
#include "Dice.h"
#include "Player.h"
#include <vector>
#include <algorithm>
using namespace std;
void Player::gameRules()
{
cout << ("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n\n");
cout << ("Left Center Right is a multiplayer dice game");
cout << ("With a minimum of three players.");
cout << ("Dice containing letters L, C, R along\n"
"with dots on the remaining side are rolled each turn");
cout << ("\n-----Each Player starts with three chips-----\n");
cout << (">> For each L rolled, the player must pass one chip to the player to their left\n"
">> For each R rolled, the player must pass one chip to the player to their right\n"
">> For each C rolled, the player must pass a chip into the center pot (out of play)\n"
">> Dots are neutral and require no action");
cout << ("If a player has three or more chips, he/she rolls all three dice\n"
"If a player only has two chips, he/she rolles onlt two dice\n"
"If a player only has one chip, he/she rolls only one die\n"
"If a player is out of chips, he/she is still in the game,\n"
"\tbut does not roll any dice and passes their turn"
"\n\n >>> The last player with chips is the winner <<<");
cout << ("\n\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
};
int main()
{
int result = 0;
int currPlayer = 1;
srand((unsigned)time(NULL));
int numPlayers;
cout << "How many players are playing? (Please enter 3 or more): " << endl;
cin >> numPlayers;
if (numPlayers <= 2)
{
while (numPlayers <= 2)
{
cout << "More players needed.";
cout << "How many players are player?: ";
cin >> numPlayers;
}
}
std::string* names = new string[numPlayers]; // getting names and index is seat number
for (int i = 0; i < numPlayers; i++)
{
cout << "Please enter your name player " << i+1 << endl;
cin >> names[i];
std::string playerName = names[i];
}
vector<int>chips[1]; // intial 3 chips
for (int i = 0; i < numPlayers; i++)
{
int InitialChips = 3;
chips->push_back(InitialChips);
}
Player::gameRules();
int sum = 0;
for (int i = 0; i < chips->size(); i++)
{
int num = chips->at(i);
sum+=num;
}
int thePot = 0;
int i = 0;
while (sum > 0)
{
if ( i >=4 )
{
i = 0;
}
string currPlayer = names[i];
int currSeat = i;
cout << "It's " << currPlayer << "'s Turn!" << endl;
cout << "[1] Roll Dice [2] Quit :";
int choice;
cin >> choice;
if (choice == 1)
{
if (chips->at(currSeat) == 0)
{
break;
}
if (chips->at(currSeat) >= 3)
{
for (int k = 0; k <= 3; k++)
{
int outcome = Dice::rollDice();
if (outcome == 1)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == 0)
{
int j = (numPlayers - 1);
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i - 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 2)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == chips->size())
{
int j = chips->at(0);
int currChips2 = chips->at(0);
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i + 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 3)
{
thePot++;
cout << ">> +1 chip to the Center Pot" << endl;
cout << "There are now " << thePot << " chip(s) in the Center Pot " << endl;
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
break;
}
else if ((outcome == 4) || (outcome == 5) || (outcome == 6))
{
break;
}
}
}
// ^^basically copied and pasted most of the while loop for the other two numbers of dice to roll^^
// had redundant code for if the player had 2 chips, to roll two dice only ^^
// also redundant code for only one chip, to roll one die. ^^
}
}
else if (choice == 2)
{
break;
}
else
{
cout << ">> Input Error";
cout << "[1] Roll Dice [2] Quit";
cin >> choice;
}
i++;
}
return 0;
}
Dice.h
#pragma once
using namespace std;
class Dice
{
public:
static int rollDice();
static int diceOutcome;
};
int Dice::rollDice()
{
int diceOutcome;
diceOutcome = (rand() % 6) + 1;
switch (diceOutcome)
{
default:
cout << "Error, retry";
case 1:
if (diceOutcome == 1)
{
cout << " --- " << endl;
cout << "You rolled a | L | Move 1 chip left." << endl;
cout << " --- " << endl;
return 1;
}
break;
case 2:
if (diceOutcome == 2)
{
cout << " --- " << endl;
cout << "You rolled a | R | Move 1 chip right." << endl;
cout << " --- " << endl;
return 2;
}
break;
case 3:
if (diceOutcome == 3)
{
cout << " --- " << endl;
cout << "You rolled a | C | Move 1 chip to the center." << endl;
cout << " --- " << endl;
return 3;
}
break;
case 4:
if (diceOutcome == 4)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 5:
if (diceOutcome == 5)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 6:
if (diceOutcome == 6)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
}
}
To be fair, I'm quite new to programming, but I have been working on this project for days and kept running into conatiner problems and storing the name and chip values independently. So i've tried a lot of different things, probably not correctly though so I'm open to anything.

How to fix my C++ fighting game with Run-Time Check Error?

I have been receiving an issue that I do not understand. The issue is:
Run-Time Check Failure #3 - The variable 'win' is being used without being initialized.
I am struggling to comprehend where my error is within the code. From what I understand the run time error comes from win not being initialized meaning it hasn't been used or set, however, it clearly is set in the fightScene() function.
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include "Character.h"
#include "Item.h"
#include "Blacksmith.h"
using namespace std;
void startup();
void createCharacter();
void existCharacter();
void secondFighter();
void fightScene();
int fightMoves(int att, int sp, int num);
void roundWon();
void characterLost();
void use_bar();
void newlines();
void changeCase(string &convert);
void bSmith();
Character existingCharacter[4] = { Character("Shabu", 10, 10, 10, 0, "Empty"), Character("Calil", 15, 15, 15, 0, "Empty"), Character("Goltero", 20, 20, 20, 0, "Empty"), Character("Balrogg", 30, 30, 30, 0, "Empty") };
Character cCharacter[2] = { Character(), Character() };
Character cCharacterSave("Empty", 20, 0, 0, 100, "Empty");
Item bars(0, 0, 0);
int timesWon = 0;
int purposeIgnore = 0;
char repeat = 'y';
int main() {
startup();
while (repeat == 'y' || repeat == 'Y') {
fightScene();
if (repeat == 'y' || repeat == 'Y')
secondFighter();
}
return 0;
}
void startup() {
int playerChoice;
cout << "**************************" << endl;
cout << "* Loading Game *" << endl;
cout << "**************************" << endl;
cout << "Which Would You Prefer?" << endl;
cout << "1: New Character..." << endl;
cout << "2: Load Character..." << endl;
do {
cout << "Enter Selection: ";
cin >> playerChoice;
} while (playerChoice <= 0 || playerChoice >= 3);
if (playerChoice == 1)
createCharacter();
else if (playerChoice == 2)
existCharacter();
return;
}
void createCharacter() {
string Name;
string inventory;
int h, att, sp, gc;
cout << "***************************" << endl;
cout << "* Creating New Player *" << endl;
cout << "***************************" << endl;
cout << "What Shall We Call You?" << endl;
cout << "Enter Name Here: ";
cin >> Name;
changeCase(Name);
cout << Name << ", let's set your stats!" << endl;
cout << "Set your ATTACK between 1 - 10" << endl;
do {
cout << "Enter Attack Here: ";
cin >> att;
} while (att <= 0 || att >= 11);
cout << "Set your SPEED between 1 - 10" << endl;
do {
cout << "Enter Speed Here: ";
cin >> sp;
} while (sp <= 0 || sp >= 11);
h = 20;
gc = 100;
cout << "The HEALTH stat wil increase over time, but as of now, " << Name << ", has " << h << " health!" << endl;
cout << Name << " you have been granted " << gc << " gold!" << endl;
cCharacter[0] = Character(Name, h, att, sp, gc, inventory);
cin.ignore();
return;
}
void existCharacter() {
string characterChoice;
cout << "***********************" << endl;
cout << "* Existing Player *" << endl;
cout << "***********************" << endl;
for (int i = 0, j = 1; i >= 0 && i <= 3; i++, j++) {
cout << j << ": " << existingCharacter[i].getName();
cout << "\t" << "Health: " << existingCharacter[i].getHealth();
cout << "\t" << "Attack: " << existingCharacter[i].getAttack();
cout << "\t" << "Speed: " << existingCharacter[i].getSpeed();
}
cout << "Enter Selection: ";
cin.ignore();
getline(cin, characterChoice);
changeCase(characterChoice);
if (characterChoice == "1" || characterChoice == "Shabu") {
cCharacter[0] = existingCharacter[0]; cCharacterSave.setHealth(existingCharacter[0].getHealth());
}
else if (characterChoice == "2" || characterChoice == "Calil") {
cCharacter[0] = existingCharacter[1]; cCharacterSave.setHealth(existingCharacter[1].getHealth());
}
else if (characterChoice == "3" || characterChoice == "Goltero") {
cCharacter[0] = existingCharacter[2]; cCharacterSave.setHealth(existingCharacter[2].getHealth());
}
else if (characterChoice == "4" || characterChoice == "Balrogg") {
cCharacter[0] = existingCharacter[3]; cCharacterSave.setHealth(existingCharacter[3].getHealth());
}
else {
cout << "Program Failure....Invaid Input!" << endl;
}
secondFighter();
return;
}
void secondFighter() {
string cFighter;
cout << "***************" << endl;
cout << "* Fighter *" << endl;
cout << "***************" << endl;
cout << "Choose Who To Fight!" << endl;
for (int i = 0, j = 1; i >= 0 && i <= 3; i++, j++) {
cout << j << ": " << existingCharacter[i].getName();
cout << "\t" << "Health: " << existingCharacter[i].getHealth();
cout << "\t" << "Strength: " << existingCharacter[i].getAttack();
cout << "\t" << "Speed: " << existingCharacter[i].getSpeed();
cout << endl;
}
cout << "Enter Selection: ";
if (purposeIgnore >= 1)
cin.ignore();
getline(cin, cFighter);
changeCase(cFighter);
if (cFighter == "1" || cFighter == "Shabu")
cCharacter[1] = existingCharacter[0];
else if (cFighter == "2" || cFighter == "Calil")
cCharacter[1] = existingCharacter[1];
else if (cFighter == "3" || cFighter == "Goltero")
cCharacter[1] = existingCharacter[2];
else if (cFighter == "4" || cFighter == "Balrogg")
cCharacter[1] = existingCharacter[3];
else { cout << "Invalid Input! Program Failure....Please Close and Restart" << endl; }
return;
}
void fightScene() {
int fight_choice;
int i = 0;
int j = 5;
bool win;
if (timesWon >= 1)
j = 6;
while (cCharacter[0].getHealth() > 0 && cCharacter[1].getHealth() > 0) {
newlines();
cout << "\t\t" << cCharacter[0].getName() << " choose ";
if (i == 0)
cout << "an attack.";
else
cout << "another attack.";
do {
cout << "\n\n\t\t<1. Punch / 2. Kick>\n\t\t<3. Slam / 4. Drop kick>";
if (j == 6)
cout << "\n\t\t<5. Items>";
cout << endl << "\t\t";
cin >> fight_choice;
} while (fight_choice <= 0 || fight_choice >= j);
if (fight_choice == 1) {
cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 1));
cout << "\n\t\tYou Punched " << cCharacter[1].getName() << ", his health is now: ";
if (cCharacter[1].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
}
else
cout << cCharacter[1].getHealth() << endl << endl;
}
else if (fight_choice == 2) {
cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 2));
cout << "\n\t\tYou Kicked " << cCharacter[1].getName() << ", his health is now: ";
if (cCharacter[1].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
}
else
cout << cCharacter[1].getHealth() << endl << endl;
}
else if (fight_choice == 3) {
cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 3));
cout << "\n\t\tYou Slamed " << cCharacter[1].getName() << " on the ground, his health is now: ";
if (cCharacter[1].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
}
else
cout << cCharacter[1].getHealth() << endl << endl;
}
else if (fight_choice == 4) {
cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 4));
cout << "\n\t\tYou Drop Kicked " << cCharacter[1].getName() << ", his health is now: ";
if (cCharacter[1].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
}
else
cout << cCharacter[1].getHealth() << endl << endl;
}
else if (timesWon >= 1 && fight_choice == 5) { // Bars
use_bar();
}
// Second fighter attack
srand(time(NULL));
int ran_pick = rand() % 5 + 1;
if (cCharacter[1].getHealth() < 0) {
ran_pick = 0;
win = 1;
}
else if (cCharacter[1].getHealth() > 0) {
cout << "\n\t\t<" << cCharacter[1].getName() << "'s turn>" << endl;
win = 0;
}
if (ran_pick == 0)
continue;
else if (ran_pick == 1) {
cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 1));
cout << "\n\t\t" << cCharacter[1].getName() << " punched you! Your health is now: ";
if (cCharacter[0].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
}
else
cout << cCharacter[0].getHealth() << endl << endl;
}
else if (ran_pick == 2) {
cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 2));
cout << "\n\t\t" << cCharacter[1].getName() << " kicked you! Your health is now: ";
if (cCharacter[0].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
}
else
cout << cCharacter[0].getHealth() << endl << endl;
}
else if (ran_pick == 3) {
cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 3));
cout << "\n\t\t" << cCharacter[1].getName() << " slammed you on the ground! Your health is now: ";
if (cCharacter[0].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
}
else
cout << cCharacter[0].getHealth() << endl << endl;
}
else if (ran_pick == 4) {
cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 4));
cout << "\n\t\t" << cCharacter[1].getName() << " drop kicked you! Your health is now: ";
if (cCharacter[0].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
}
else
cout << cCharacter[0].getHealth() << endl << endl;
}
else if (ran_pick == 5)
cout << "\t\t" << cCharacter[1].getName() << " missed you! Your health is still: " << cCharacter[0].getHealth() << endl << endl;
if (cCharacter[0].getHealth() > 0) {
cout << "\n\t\t";
system("PAUSE"); // Lets them read the attacks
}
i++; // Increases i to change some wording
}
if (win == 1)
roundWon();
else
characterLost();
return;
}
int fightMoves(int st, int sp, int num) {
srand(time(NULL));
int rand_num;
int addition;
switch (num) {
case 1: {
rand_num = rand() % 40 + 1;
addition = (st + sp) / rand_num;
cout << "\n\t\tDamage inflicted: " << addition;
return addition; break;
}
case 2: {
rand_num = rand() % 20 + 1;
addition = (st + sp) / rand_num;
cout << "\n\t\tDamage inflicted: " << addition;
return addition; break;
}
case 3: {
rand_num = rand() % 30 + 1;
addition = (st + sp) / rand_num;
cout << "\n\t\tDamage inflicted: " << addition;
return addition; break;
}
case 4: {
rand_num = rand() % 30 + 1;
addition = (st + sp) / rand_num;
cout << "\n\t\tDamage inflicted: " << addition;
return addition; break;
}
}
}
int start()
{
while (repeat == 'y' || repeat == 'Y') {
fightScene();
if (repeat == 'y' || repeat == 'Y')
secondFighter();
}
return 0;
}
void roundWon() {
srand(time(NULL));
timesWon++;
purposeIgnore++;
cCharacter[0].setHealth(cCharacterSave.getHealth());
cCharacter[1].setHealth(100);
int item_won = rand() % 3 + 1;
cout << "\t\tYou won!";
cout << "\n\n\t\tYou have been rewarded ";
if (item_won == 1) {
cout << "a small protein bar! (+20 health)";
bars.bar_small++;
}
else if (item_won == 2) {
cout << "a medium protein bar! (+30 health)";
bars.bar_medium++;
}
else if (item_won == 3) {
cout << "a large protein bar! (+40 health)";
bars.bar_large++;
}
cout << "\n\n\t\tItems can be used in game at the cost of a turn.";
cout << "\n\n\t\t";
system("PAUSE"); // Lets them read
int ability_gain[3] = { rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1 };
cCharacter[0].setHealth(ability_gain[0] += cCharacter[0].getHealth());
cCharacterSave.setHealth(cCharacter[0].getHealth());
cCharacter[0].setAttack(ability_gain[1] += cCharacter[0].getAttack());
cCharacter[0].setSpeed(ability_gain[2] += cCharacter[0].getSpeed());
cout << "\n\t\tYour health is now: " << cCharacter[0].getHealth();
cout << "\n\t\tYour strength is now: " << cCharacter[0].getAttack();
cout << "\n\t\tYour speed is now: " << cCharacter[0].getSpeed();
cout << "\n\n\t\tWould you like to fight another person? (y/n) ";
cin >> repeat;
return;
}
void characterLost() {
cCharacter[0].setHealth(cCharacterSave.getHealth());
cCharacter[1].setHealth(100);
purposeIgnore++;
cout << "\n\n\t\tYou have lost.";
cout << "\n\t\tWould you like to fight another person? (y/n) ";
cin >> repeat;
return;
}
void use_bar() {
int choose_bar;
char another_bar;
do {
cout << "\n\n\t\tWhich bar would you like to use? ";
cout << "\n\t\t 1: Small Bar: " << bars.bar_small;
cout << "\n\t\t 2: Medium Bar: " << bars.bar_medium;
cout << "\n\t\t 3: Large bar: " << bars.bar_large;
do {
cout << "\n\n\t\tI choose: ";
cin >> choose_bar;
} while (choose_bar <= 0 || choose_bar >= 4);
if (choose_bar == 1 && bars.bar_small >= 1) {
cCharacter[0].setHealth(cCharacter[0].getHealth() + 20);
bars.bar_small--;
cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
}
else if (choose_bar == 2 && bars.bar_medium >= 1) {
cCharacter[0].setHealth(cCharacter[0].getHealth() + 30);
bars.bar_medium--;
cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
}
else if (choose_bar == 3 && bars.bar_large >= 1) {
cCharacter[0].setHealth(cCharacter[0].getHealth() + 40);
bars.bar_large--;
cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
}
else
cout << "\n\t\tNot enough bars!";
cout << "\n\n\t\tWould you like to use another bar? (y/n) ";
cin >> another_bar;
} while (another_bar == 'y' || another_bar == 'Y');
return;
}
void newlines() {
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}
void changeCase(string &convert) {
for (int i = 0; convert[i]; i++) {
if (isupper(convert[i]))
convert[i] = tolower(convert[i]);
else
continue;
}
convert.at(0) = toupper(convert.at(0));
return;
}
void bSmith()
{
Blacksmith shopKeeper; //The shop keeper
int responce; //Menu navigation
cout << "*******************************" << endl;
cout << "* Welcome to the Blacksmith *" << endl;
cout << "*******************************" << "\n" << endl;
cout << "*****************************" << endl;
cout << "* 1: Purchase Items *\n";
cout << "* 2: Sell Items *\n";
cout << "* 3: List Your Items *\n";
cout << "* 4: Currency *\n";
cout << "* 5: Exit *\n";
cout << "*****************************" << endl;
do
{
cout << "Enter Option Here: ";
cin >> responce;
switch (responce)
{
case 1:
shopKeeper.buyItem(cCharacter[0]);
cout << endl;
break;
case 2:
cout << "*****************************" << endl;
cout << "* Items To Sell *" << endl;
cout << "*****************************" << endl;
shopKeeper.sellItem(cCharacter[0]);
cout << endl;
break;
case 3:
cout << "*****************************" << endl;
cout << "* Character Inventory *" << endl;
cout << "*****************************" << endl;
cCharacter[0].listInv();
cout << endl;
break;
case 4:
cout << "*****************************" << endl;
cout << "* Current Gold Currency *" << endl;
cout << "*****************************" << endl;
cout << "\t" << cCharacter[0].getCurrency() << endl;
cout << endl;
break;
case 5:
cout << "*****************************" << endl;
cout << "* Thanks for shopping *" << endl;
cout << "*****************************" << endl;
return;
default:
cout << "Please enter valid data." << "\n";
break;
}
cout << "*****************************" << endl;
cout << "* 1: Purchase Items *\n";
cout << "* 2: Sell Items *\n";
cout << "* 3: List Your Items *\n";
cout << "* 4: Currency *\n";
cout << "* 5: Exit *\n";
cout << "*****************************" << endl;
} while (responce != 5);
return;
}
All I can see that sets win is this part of the code,
if (cCharacter[1].getHealth() < 0) {
ran_pick = 0;
win = 1;
}
else if (cCharacter[1].getHealth() > 0) {
cout << "\n\t\t<" << cCharacter[1].getName() << "'s turn>" << endl;
win = 0;
}
However, if cCharacter[1].getHealth()==0, win will be left unset.

Xcode C++ How to add a "Play Again?" function to my program

my program is all finished but I want to know how to add a "Play again" feature that uses "Yes" or "No" input to decide whether to run the program again or to end it. I am a little unsure of where to place it in my program since I use a handful of while loops and if/else statements. Any insight would be appreciated, thanks! Here is my code:
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main() // Setting up the code to follow.
{
srand(static_cast<unsigned int>(time(0)));
int Weapon_Selection; // Creating variables for the player and computer's weapon selection.
int Comp_Weapon;
bool Battle = true; // The variable to begin the battle.
while(Battle) // The main while loop to run the program code.
{
int Player_Health = 100; // More variables for both the player and the computer.
int Comp_Health = 100;
int Cannon_Ammo = 3;
int Grenade_Ammo = 4;
int Comp_Cannon_Ammo = 3;
int Comp_Grenade_Ammo = 4;
while(Player_Health > 0 && Comp_Health > 0) // The while loop to continue running the program while both combatants are alive.
{
bool Invalid = true;
bool Comp_Invalid = true;
while(Invalid)
{
cout << "Select a weapon using number keys 1, 2, and 3.\n"; // Weapon selection input from the player.
cout << "1. Cannon (Ammo left: " << Cannon_Ammo << ")\n";
cout << "2. Grenade (Ammo left: " << Grenade_Ammo << ")\n";
cout << "3. Rifle\n";
cout << "\n";
cout << "You select: ";
cin >> Weapon_Selection;
srand(static_cast<unsigned int>(time(0)));
if (Weapon_Selection == 1 && Cannon_Ammo > 0)
{
Cannon_Ammo -= 1;
Invalid = false;
int Player_Dmg = rand() % 5 + 10; // Randomly generated damage range.
cout << "You caused " << Player_Dmg << " cannon damage to your enemy!\n";
Comp_Health -= Player_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
break;
}
else if (Weapon_Selection == 2 && Grenade_Ammo > 0)
{
Grenade_Ammo -= 1;
Invalid = false;
int Player_Dmg = rand() % 5 + 7;
cout << "You caused " << Player_Dmg << " grenade damage to your enemy!\n";
Comp_Health -= Player_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
break;
}
else if (Weapon_Selection == 3)
{
Invalid = false;
int Player_Dmg = rand() % 5 + 3;
cout << "You caused " << Player_Dmg << " rifle damage to your enemy!\n";
Comp_Health -= Player_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
break;
}
else
cout << "You are out of ammo or you have entered an invalid number." << "\n"; // Output for wrong number input or no ammo.
cout << "\n";
}
if (Comp_Health <= 0) // Break point if the computer dies in battle.
break;
while(Comp_Invalid) // The computer's random weapon selection.
{
Comp_Weapon = rand() % 3 + 1;
if (Comp_Weapon == 1 && Comp_Cannon_Ammo > 0)
{
Comp_Cannon_Ammo -= 1;
Comp_Invalid = false;
int Comp_Dmg = rand() % 5 + 10; // Randomly generated damage range for the computer.
cout << "Your enemy used a cannon and caused " << Comp_Dmg << " damage to you!\n";
Player_Health -= Comp_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
}
else if (Comp_Weapon == 2 && Comp_Grenade_Ammo > 0)
{
Comp_Grenade_Ammo -= 1;
Comp_Invalid = false;
int Comp_Dmg = rand() % 5 + 7;
cout << "Your enemy used a grenade and caused " << Comp_Dmg << " damage to you!\n";
Player_Health -= Comp_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
}
else
{
Comp_Invalid = false;
int Comp_Dmg = rand() % 5 + 3;
cout << "Your enemy used a rifle and caused " << Comp_Dmg << " damage to you!\n";
Player_Health -= Comp_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
}
}
}
if(Player_Health < 0) // End of battle output, regardless of who wins or loses.
cout << "You have been defeated by your enemy!" << "\n" << endl;
else
cout << "Congratulations, you beat your enemy!" << "\n" << endl;
}
cin.ignore(2);
return 0;
}
To illustrate #NathanOliver's comment:
int main(void)
{
bool play_again = true;
while (play_again)
{
Play_Game();
std::cout << "\nWant to play again (y / n)?";
char answer;
std::cin >> answer;
if (tolower(answer) != 'y')
{
play_again = false;
}
}
return 0;
}
You could also use a do-while loop as well.

How to score yahtzee in c++

I am writing a yahtzee game for my c++ programming class. One of my difficulties I have ran into is the scoring system for different categories. I think I have figured out how to do it for adding 1s, 2s etc but I do not know how to have the program determine when a 3 of a kind, 4 of a kind, etc has been rolled. Here is my code so far.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//Declare variables
int players;
int turn = 1;
vector<string> names;
string playerName;
int dice[5];
int finalScore = 0;
char reroll[5];
char rollDice;
int tries = 1;
const int DICE = 5;
int roll[DICE];
int scorecard;
int scoreThisTurn(int scorecard);
int turnScore = 0;
//Introduction, get number of players.
cout << "Hello, welcome to Yahtzee! How many players are there?" << endl;
cin >> players;
if (players > 4) {
cout << "Sorry, the maximum number of players is 4." << endl;
cout << "How many players are there?" << endl;
cin >> players;
}
//Get player names
string getNames();
for (int i = 0; i < players; i++) {
cout << "Hello player " << i + 1 << ", please enter your name" << endl;
cin >> playerName;
names.push_back(playerName);
}
srand(time(NULL)); //random seed
cout << "Welcome to Yahtzee!\n";
while (turn <= 13) { //roll dice
cout << "Press 'r' to roll" << endl;
cin >> rollDice;
if (rollDice == 'r') {
for (int i = 0; i < DICE; i++) {
roll[i] = rand() % 6 + 1;
}
}
cout << "You rolled: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl;
cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4];
for (int i = 0; i < DICE; i++) {
if (reroll[i] == 'y') {
roll[i] = rand() % 6 + 1;
}
else if (reroll[i] == 'n') {
roll[i];
}
else cout << "Sorry you entered an invalid letter." << endl;
}
cout << "Your second roll is: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl;
cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4];
for (int i = 0; i < DICE; i++) {
if (reroll[i] == 'y') {
roll[i] = rand() % 6 + 1;
}
else if (reroll[i] == 'n') {
roll[i];
}
else cout << "Sorry you entered an invalid letter." << endl;
}
cout << "Your third roll is: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
//displays scorecard categories
cout << "Which category would you like to score this in" << endl;
cout << "1 - ones: " << endl;
cout << "2 - twos: " << endl;
cout << "3 - threes: " << endl;
cout << "4 - fours: " << endl;
cout << "5 - fives: " << endl;
cout << "6 - sixes: " << endl;
cout << "7 - 3 of a kind: " << endl;
cout << "8 - 4 of a kind: " << endl;
cout << "9 - small straight: " << endl;
cout << "10 - large straight: " << endl;
cout << "11 - full house: " << endl;
cout << "12 - yahtzee: " << endl;
cout << "13 - chance: " << endl;
//asks player to choose where to score
cout << "\nEnter 1-14 to choose a category." << endl;
cin >> scorecard;
//assigns points
for (int i = 0; i < DICE; i++) {
turnScore = 0;
if (scorecard == 1) {
if (roll[i] == 1) {
turnScore = turnScore + 1;
}
}
if (scorecard == 2) {
if (roll[i] == 2) {
turnScore = turnScore + 2;
}
}
if (scorecard == 3) {
if (roll[i] == 3) {
turnScore = turnScore + 3;
}
}
if (scorecard == 4) {
if (roll[i] == 4) {
turnScore = turnScore + 4;
}
}
if (scorecard == 5) {
if (roll[i] == 5) {
turnScore = turnScore + 5;
}
}
if (scorecard == 6) {
if (roll[i] == 6) {
turnScore = turnScore + 6;
}
if (scorecard == 7) {
if (roll[i] == 2) {
turnScore = turnScore + 2;
}
}
}
cout << scorecard << endl;
turn++;
}
system("pause");
return 0;
}
As you can see I've set up the scoring for the first 6 categories but don't know how to proceed.
I do not know how to have the program determine when a 3 of a kind, 4 of a kind, etc has been rolled.
Create a variable to help you keep track of the number of dice that have a given number.
int diceCount[DICE] = {0};
and fill up the array with:
for (int i = 0; i < DICE; i++) {
diceCount[roll[i-1]]++
}
Create helper functions to determine whether five, four, or three of a kind have been thrown.
int getNOfAKind(int diceCount[], int N)
{
// This will need moving DICE out of `main`
// making it a global variable.
for ( int i = 0; i < DICE; ++i )
{
if (diceCount[i] == N )
{
return i+1;
}
}
return -1;
}
int getFiveOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 5);
}
int getFourOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 4);
}
int getThreeOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 3);
}
and use it as:
int fiveCount = getFiveOfAKind(diceCount);
if ( fiveCount != -1 )
{
}
int fourCount = getFourOfAKind(diceCount);
if ( fourCount != -1 )
{
}
int threeCount = getThreeOfAKind(diceCount);
if ( threeCount != -1 )
{
}

Random Guessing Game in C++

My assignment is to create a guessing game where the computer guesses my number and one where I guess the computer's number. I have my code written out but It's incomplete. I want to create a menu so the user can choose which game he wants to play, and also i am having trouble joining the two programs into one so they both will run. Can someone please assist me. The first game works fine but from there I really don't know what I'm doing.
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
const int min = 1;
const int max = 100;
int num = 2 && 3 && 4;
int prevMin = 0;
int prevMax = 0;
int tries = 0;
int guess = 0;
int userNum = 0;
int userGuess = 0;
int systemNum = 0;
int systemGuess = 0;
cout << "Welcome to the Guessing Game!" << endl;
cout << "Enter a 2 to play Game 1 or a 3 to play Game 2. Or enter 4 to quit." << endl;
cin >> num;
if (num == 2)
{
cout << "Welcome to Game 1!" << endl;
cout << "User, enter a random number between " << min << " and " << max << " : "; cin >> userNum;
}
srand(time(0));
systemGuess = rand() % 100 + 1;
do
{
cout << "System, guess the user's number between " << min << " and " << max << ": " << systemGuess << endl;
cin.get();
++tries;
if (systemGuess > max || systemGuess<min)
{
cout << "I said guess a number between " << min << " and " << max << " stupid." << endl;
}
if (systemGuess > userNum)
{
cout << "Too high. Guess lower." << endl;
prevMax = systemGuess;
systemGuess = rand() % (prevMax - prevMin) + prevMin;
if (systemGuess == prevMin)
systemGuess++;
}
else if (systemGuess < userNum)
{
cout << "Too low. Guess higher." << endl;
prevMin = systemGuess;
systemGuess = rand() % (prevMax - prevMin) + prevMin;
if (systemGuess == prevMin)
systemGuess++;
}
} while (systemGuess != userNum);
cout << systemGuess << endl;
cout << " I guessed it right! It took me " << tries << " guess(es). " << endl;
srand(time(0));
systemNum = rand()% 100 + 1;
//Beginning of second game
do
{
if (num == 3)
{
cout << "Welcome to Game 2!" << endl;
cout << "User, try to guess the computer's number that's between " << min << " and " << max << " . " << endl;
}
cout << "Enter your guess." << endl;
cin >> userGuess;
tries++;
if (userGuess > systemNum)
{
cout << "Too high. Guess lower." << endl;
cin >> userGuess;
}
else if (userGuess < systemNum)
{
cout << "Too low. Guess higher." << endl;
cin >> userGuess;
}
else
{
cout << "Correct! It took you long enough! Lol... " << endl;
cin >> userGuess;
}
while (userGuess != systemNum);
}
system("pause");
return 0;
}
Make the two games two distinct functions (each with its own local variables), create a third one that is a loop that prompts for the games (and break when "quit" is selected), and call the corresponding function, then call the third one from main.
You can use if...else :
cout << "Welcome to the Guessing Game!" << endl;
cout << "Enter a 2 to play Game 1 or a 3 to play Game 2. Or enter 4 to quit." << endl;
cin >> num;
if (num == 2)
{//game1
}
else if(num==3)
{//game2
}
else if(num==4)
{return 0;
}else
{
cout<<"Invalid choice!";
system("pause");
return 1;
}
//print highscores
system("pause");
return 0;
Your whole code:
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
const int min = 1;
const int max = 100;
int num = 2 && 3 && 4;
int prevMin = 0;
int prevMax = 0;
int tries = 0;
int guess = 0;
int userNum = 0;
int userGuess = 0;
int systemNum = 0;
int systemGuess = 0;
srand(time(0));
cout << "Welcome to the Guessing Game!" << endl;
cout << "Enter a 2 to play Game 1 or a 3 to play Game 2. Or enter 4 to quit." << endl;
cin >> num;
if (num == 2)
{
cout << "Welcome to Game 1!" << endl;
cout << "User, enter a random number between " << min << " and " << max << " : "; cin >> userNum;
systemGuess = rand() % 100 + 1;
do
{
cout << "System, guess the user's number between " << min << " and " << max << ": " << systemGuess << endl;
cin.get();
++tries;
if (systemGuess > max || systemGuess<min)
{
cout << "I said guess a number between " << min << " and " << max << " stupid." << endl;
}
if (systemGuess > userNum)
{
cout << "Too high. Guess lower." << endl;
prevMax = systemGuess;
systemGuess = rand() % (prevMax - prevMin) + prevMin;
if (systemGuess == prevMin)
systemGuess++;
}
else if (systemGuess < userNum)
{
cout << "Too low. Guess higher." << endl;
prevMin = systemGuess;
systemGuess = rand() % (prevMax - prevMin) + prevMin;
if (systemGuess == prevMin)
systemGuess++;
}
} while (systemGuess != userNum);
cout << systemGuess << endl;
cout << " I guessed it right! It took me " << tries << " guess(es). " << endl;
}
systemNum = rand()% 100 + 1;
//Beginning of second game
if (num == 3)
{
do
{
cout << "Welcome to Game 2!" << endl;
cout << "User, try to guess the computer's number that's between " << min << " and " << max << " . " << endl;
cout << "Enter your guess." << endl;
cin >> userGuess;
tries++;
if (userGuess > systemNum)
{
cout << "Too high. Guess lower." << endl;
cin >> userGuess;
}
else if (userGuess < systemNum)
{
cout << "Too low. Guess higher." << endl;
cin >> userGuess;
}
else
{
cout << "Correct! It took you long enough! Lol... " << endl;
cin >> userGuess;
}}
while (userGuess != systemNum);
}else if(num==4)return 0;
else{
cout<<"Invalid choice!";
system("pause");
return 1;
}
//print highscores
system("pause");
return 0;
}