I'm making a Dice Game in C++. I was wondering why it doesn't restart the loop. The game is Best of 3. It's supposed to restart the loop as long as the player wants to keep playing. However it only restarts the loop once. The second time I press 'Y' or yes in this case it just exits the program.
I've tried putting the restart in a nested while loop but it doesn't seem to work either.
restart:
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;
cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;
if (cDice1 > pDice1) {
cout << "Computer wins!" << endl << endl;
cWin++;
} if (pDice1 > cDice1) {
cout << "Player wins!" << endl << endl;
pWin++;
} if (pDice1 == cDice1) {
cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
cout << "Player wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}if (cWin > pWin) {
cout << "Computer wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}
}
First, is this all your code? I noticed most of your variables seem to be declared outside of the provided code block. If so, is your "Y" being declared as a char and not a string type to match your condition type?
It looks like you are failing to set your pWin and cWin back to zero when it returns to the top. You can fix with:
restart:
cWin = 0;
pWin = 0;
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;
cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;
if (cDice1 > pDice1) {
cout << "Computer wins!" << endl << endl;
cWin++;
} if (pDice1 > cDice1) {
cout << "Player wins!" << endl << endl;
pWin++;
} if (pDice1 == cDice1) {
cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
cout << "Player wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}if (cWin > pWin) {
cout << "Computer wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}
}
Because you don't reset pWin and cWin to zero after a game.
You should fix that but also turn the goto into another while loop and make the guts of that while loop into a function maybe.
Related
I've been working on my introduction to C++ project which is to make a game of NIM. I've written program and I thought it should run smoothly but I've countered the following errors.
I know too much code but I couldn't figure out what is the issue that is stopping me from running the program.
I'm new to the programming word so be understanding if the issue is very simple.
thank you in advance.
Error Message
#include <iostream>
#include <iomanip>
using namespace std;
int stonesNum;
char goFirst;
int turn = 0; // 0 = player, 1 = computer
int stonesRemove;
int main() {
do
{
cout << "Enter number of starting stones:" << endl;
cin >> stonesNum;
cout << "Would you like to go first? (y/n)" << endl;
cin >> goFirst;
if (goFirst == 'y' || goFirst == 'Y')
{
turn = 0;
}
else
{
turn = 1;
}
while (stonesNum > 0)
{
if (turn == 0)
{
cout << "How many would you like to remove: 1 or 2?" << endl;
cin >> stonesRemove;
stonesNum = stonesNum - 1;
cout << "The number of stones left is " << stonesNum << endl;
}
else
{
if (stonesNum % 3 == 0)
{
stonesNum = stonesNum - 2;
cout << "The computer removes 2 stones." << endl;
cout << "The number of stones left is " << stonesNum << endl;
}
else
{
stonesNum = stonesNum - 1;
cout << "The computer removes 1 stones." << endl;
cout << "The number of stones left is " << stonesNum << endl;
}
}
if (stonesNum == 0)
{
if (turn == 0)
{
cout << "The computer wins!" << endl;
}
else
{
cout << "you won!" << endl;
}
}
}
}
return 0;
}
You are missing an ending while condition after your do loop. The syntax is :
do{
//do stuff here
}while(condition);
In your case the condition would be (stonesNum!=0)
OR
Do
if (stonesNum == 0)
{
if (turn == 0)
{
cout << "The computer wins!" << endl;
return;
}
else
{
cout << "you won!" << endl;
return;
}
}
and put condition (true)
You actually don't require the do loop at all, are you trying to loop the game endlessly? If so then you should put an appropriate prompt at the beginning and put condition (true) in the do loop.
The complete code:
do
{
cout << "Enter number of starting stones:" << endl;
cin >> stonesNum;
cout << "Would you like to go first? (y/n)" << endl;
cin >> goFirst;
if (goFirst == 'y' || goFirst == 'Y')
{
turn = 0;
}
else
{
turn = 1;
}
while (stonesNum > 0)
{
if (turn == 0)
{
cout << "How many would you like to remove: 1 or 2?" << endl;
cin >> stonesRemove;
stonesNum = stonesNum - 1;
cout << "The number of stones left is " << stonesNum << endl;
}
else
{
if (stonesNum % 3 == 0)
{
stonesNum = stonesNum - 2;
cout << "The computer removes 2 stones." << endl;
cout << "The number of stones left is " << stonesNum << endl;
}
else
{
stonesNum = stonesNum - 1;
cout << "The computer removes 1 stones." << endl;
cout << "The number of stones left is " << stonesNum << endl;
}
}
}
if (turn == 0)
{
cout << "The computer wins!" << endl;
}
else
{
cout << "you won!" << endl;
}
}while(true);
I have written a code that displays a rock-paper-scissors game against the computer. I would like to add a feature where I can create a text file in order to store the person's score and the computer score and keep track of the score but I don't know how to do it. Thank you in advance!
Here is my code.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
void rock_paper_scissors()
{
static int userscore = 0;
static int computerscore = 0;
string playername;
int userchoice;
int computerchoice;
cout << "Hello to rock-paper-scissors!\n";
cout << "rock beats scissors, scissors beats paper and paper beats rock." << endl;
cout << "choose 1 for rock, 2 for paper, 3 for scissors.\n";
cout << "please enter your name." << endl;
cin >> playername;
cout << endl;
cout << "Please enter your choice\n";
cin >> userchoice;
cout << endl;
while (!(userchoice > 0 && userchoice <= 3))
{
cout << "invalid choice. please enter a number between 1 and 3\n";
cin >> userchoice;
}
if (userchoice == 1)
{
cout << playername << " picked rock." << endl;
}
else if (userchoice == 2)
{
cout << playername << " picked paper." << endl;
}
else if (userchoice == 3)
{
cout << playername << " picked scissors." << endl;
}
computerchoice = (rand() % 3) + 1;
if (userchoice == 1 && computerchoice == 3)
{
cout << playername << " wins!" << endl;
}
else if (userchoice == 2 && computerchoice == 1)
{
cout << playername << " wins!" << endl;
}
else if (userchoice == 3 && computerchoice == 2)
{
cout << playername << " wins!" << endl;
}
else if (userchoice == computerchoice)
{
cout << " draw!" << endl;
}
else
{
cout << "computer wins!" << endl;
}
cout << "thank you for playing!\n";
string restart;
cout << "Would you like to play again?" << endl << "(y)es / (n)o" << endl;
cin >> restart;
if (restart == "y")
{
rock_paper_scissors();
}
}
int main()
{
cout << "MAIN\n";
rock_paper_scissors();
return 0;
}
Why do you need to write the data into in file? Updating a simple txt file after each round could be cumbersome, as you always result in a single score at the end of the program. I would suggest changing the type of the rock_paper_scissors into int indicating the score achieved by the player in a single lot. The intermediate results are irrelevant. Just place the game loop into your main function and do not use a recursive function call and static function variables here. Otherwise, the player is forced to enter his name for every single lot.
Moreover, I tested your code and you have to change your error handling. I typed in "rock" and the program stuck in an infinity loop "invalid choice. please enter a number between 1 and 3\n" Whereby it is not possible to make another entry. As I entered a string instead of an integer, you have to reset the console. Beware of the dumbest possible user.
Moreover, you should seed your program to avoid identical computer choices in each game. This could be done with srand(time(NULL)).
Eventually, I write the tracked score into a score file at the end of the main function using the fstream standard library.
#include <iostream>
#include <string>
#include <algorithm> // min max
#include <fstream> // read/write from/to files
#include <time.h> // time
using namespace std;
int rock_paper_scissors(const std::string& playername);
int main()
{
srand(time(NULL));
cout << "MAIN\n";
cout << "Hello to rock-paper-scissors!\n";
cout << "rock beats scissors, scissors beats paper and paper beats rock." << endl;
cout << "choose 1 for rock, 2 for paper, 3 for scissors.\n";
int userscore = 0;
int computerscore = 0;
std::string playername;
std::string restart;
cout << "please enter your name." << endl;
cin >> playername;
cout << endl;
do
{
int result = rock_paper_scissors(playername);
cout << "thank you for playing!\n";
userscore += result;
computerscore += std::max(0, 3 - 2 * result);
cout << playername << "'s score: " << userscore;
cout << "\ncomputer's score: " << computerscore;
cout << "\nWould you like to play again?" << endl << "(y)es / (n)o" << endl;
cin >> restart;
} while (restart == "y");
std::ofstream ofile;
ofile.open("scorefile.txt");
ofile << "Scores:\n" << playername << ": " << userscore;
ofile << "\nComputer: " << computerscore;
ofile.close();
return 0;
}
int rock_paper_scissors(const std::string& playername)
{
int userchoice;
int computerchoice;
cout << endl << endl;
do {
cout << "Please enter your choice\n";
if (std::cin >> userchoice)
{
if (userchoice > 0 && userchoice <= 3)
{
break;
}
else
{
cout << "invalid choice. please enter a number between 1 and 3\n";
continue;
}
}
else if (!cin.bad() && !cin.eof())
{
// a non integer value entered
cerr << "invalid choice. please enter a number between 1 and 3\n";
// Reset error state
cin.clear();
// remove error input
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
} while (true);
if (userchoice == 1)
{
cout << playername << " picked rock." << endl;
}
else if (userchoice == 2)
{
cout << playername << " picked paper." << endl;
}
else if (userchoice == 3)
{
cout << playername << " picked scissors." << endl;
}
computerchoice = (rand() % 3) + 1;
if (userchoice == 1 && computerchoice == 3)
{
cout << playername << " wins!" << endl;
return 3;
}
else if (userchoice == 2 && computerchoice == 1)
{
cout << playername << " wins!" << endl;
return 3;
}
else if (userchoice == 3 && computerchoice == 2)
{
cout << playername << " wins!" << endl;
return 3;
}
else if (userchoice == computerchoice)
{
cout << " draw!" << endl;
return 1;
}
else
{
cout << "computer wins!" << endl;
return 0;
}
}
I'm currently in a class that wants me to make a craps game.
The problem is in int main on the second while statement comparing the point with the roll. It ignores the if statement and does the loop again, even though it hits the point or 7. Sometimes it works like it should and other times it repeats the loop a few times.
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int diceRoll() {
int x = 0, y = 0;
x = rand() % 6 + 1;
y = rand() % 6 + 1;
cout << "You rolled a " << x << " and a " << y << " which comes out to ------> " << x + y << " <-------" << endl;
return x + y;
}
bool playAgain() {
char ans;
cout << "Do you want to play again ?? Y to continue, N to quit." << endl;
cin >> ans;
while (ans != 'Y' || ans != 'y' || ans != 'n' || ans != 'N') {
if (ans == 'Y' || ans == 'y')
{
return true;
}
if (ans == 'N' || ans == 'n')
{
return false;
}
cout << "Do you want to play again ?? Y to continue, N to quit." << endl;
cin >> ans;
}
}
int main()
{
srand(time(NULL));
int dices, bid, point = 0;
int money = 50;
bool gameRunning = true;
bool didTheyWin;
while (gameRunning == true) {
if (money == 0) {
cout << "You have no money, ending game." << endl;
break;
}
cout << "Please enter a bid. You currently have $" << money << endl;
cout << "$";
cin >> bid;
while (bid > money) {
cout << "Please bet below your current balance: $" << money << endl;
cout << "$";
cin >> bid;
}
dices = diceRoll();
didTheyWin = false;
if ((dices == 7) || (dices == 11)) {
cout << "You won $" << bid << " !" << endl;
money = money + bid;
}
else if ((dices == 2) || (dices == 3) || (dices == 12)) {
cout << "You LOSE! You lost $" << bid << " !" << endl;
money = money - bid;
}
else {
point = dices;
cout << "The target number is > " << point << " <" << endl;
cout << "If you hit a 7 you lose, if you hit the target you win. \nYou automatically roll until one of these two things happen.\n";
while (didTheyWin == false) {
diceRoll();
dices = diceRoll();
if (dices == point) {
cout << "You won $" << bid << " !" << endl;
money = money + bid;
cout << "You now have $" << money << endl;
didTheyWin = true;
}
else if (dices == 7) {
cout << "You LOSE! You lost $" << bid << " !" << endl;
money = money - bid;
cout << "You now have $" << money << endl;
didTheyWin = true;
}
}
}
gameRunning = playAgain();
}
cout << "Thanks for playing. _END_" << endl;
return 0;
}
You call diceRoll twice, and ignore what you get back from the first call. You'll see the results of that first roll displayed, but they'll be ignored and you'll roll again.
I have a pig dice game where there are two modes (1 or 2 dice are rolled). It's played with 2 human players. When I run my program with 1 die selected it runs fine, but when I roll 2 dice it gets thrown into an infinite loop. I'm looking for a hint on where the problem lies and why it was thrown into a loop as in my mind both programs should be almost identical. Sorry in advance if the code looks strange.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int PLAYER1 = 0;
const int PLAYER2 = 1;
const int winningScore = 100;
int turn = PLAYER1;
void printIntro()
{
cout << " Welcome to the dice game: Pig! "<< endl;
cout << "The goal is to be the first player to reach 100. If playing with one die the rules are that each player can rol as many times as they choose. just dont roll a 1 or else you'll lose your turn AND all points accumulated in that round. If you're playing with 2 dies the same rules applies, but if you roll snake eyes (double 1's) you'll not only lose your turn but you'll also loose all your points. good luck and may the best player win!"<< endl;
}
int game1(string playerName, int playerScore)
{
int roll = rand() % 6 + 1;
cout << playerName << " You rolled: " << roll <<endl;
if(roll == 1)
{
cout << " OH NO! You rolled a 1. "<< endl;
cout << " Your turn is over. " << endl;
playerScore = 0;
}
else
{
playerScore +=roll;
cout << playerName << " Your score: " << playerScore <<endl;
}
if(roll == 1)
{
if(turn == PLAYER1)
turn = PLAYER2;
else
turn = PLAYER1;
}
else
{
char choice;
cout << " Would you like to roll again? (y/n): ";
cin >> choice;
if(choice != 'y')
{
if (turn == PLAYER1)
turn = PLAYER2;
else
turn = PLAYER1;
}
}
return playerScore;
}
int game2(string playerName, int playerScore)
{
int roll1 = rand() % 6 + 1;
int roll2 = rand() % 6 + 1;
cout << playerName << " You rolled: " << roll1 << " and " << roll2 <<endl;
if(roll1 || roll2 == 1)
{
cout << " OH NO! You rolled a 1. " << endl;
cout << " Your turn is over. " << endl;
playerScore = 0;
}
else if (roll1 && roll2 == 1)
{
cout << "OH CRAP! You rolled snake eyes!" << endl;
cout << " Your turn is over. " << endl;
playerScore == 0;
}
else
{
playerScore += roll1 + roll2 ;
cout << playerName << " Your score: " << playerScore <<endl;
}
if(roll1 || roll2 == 1)
{
if(turn == PLAYER1)
turn = PLAYER2;
else
turn = PLAYER1;
}
else if (roll1 && roll2 == 1)
{
if(turn == PLAYER1)
turn = PLAYER2;
else
turn = PLAYER1;
}
else
{
char choice;
cout << "Would you like to roll again? (y/n): ";
cin >> choice;
if(choice != 'y')
{
if (turn == PLAYER1)
turn = PLAYER2;
else
turn = PLAYER1;
}
}
return playerScore;
}
int main()
{
srand(time(0));
int player1score = 0;
int player2score = 0;
string player1name;
string player2name;
int dieRoll;
printIntro();
cout << " Player 1, Enter your name: ";
cin >> player1name;
cout << " Player 2, Enter your name: ";
cin >> player2name;
cout << "Wouild you like to roll with 1 or 2 dice?" << endl;
cin >> dieRoll;
if (dieRoll == 1)
{
while (player1score < winningScore && player2score < winningScore)
{
if (turn == PLAYER1)
{
player1score = game1(player1name, player1score);
}
else
{
player2score = game1(player2name, player2score);
}
}
if(player1score >= winningScore)
{
cout << player1name <<endl;
cout << " Your score is : " << player1score<<endl;
cout << player1name << " WINS! " << endl;
}
else
{
cout << player2name << endl;
cout <<" Your score: "<< player2score << endl;
cout << player2name << " WINS!" << endl;
}
}
else
{
while (player1score < winningScore && player2score < winningScore)
{
if (turn == PLAYER1)
{
player1score = game2(player1name, player1score);
}
else
{
player2score = game2(player2name, player2score);
}
}
if(player1score >= winningScore)
{
cout << player1name <<endl;
cout << " Your score is : " << player1score<<endl;
cout << player1name << " WINS! " << endl;
}
else
{
cout << player2name << endl;
cout <<" Your score: "<< player2score << endl;
cout << player2name << " WINS!" << endl;
}
}
return 0;
}
There are a couple issues in the following block which may be causing problems:
else if (roll1 && roll2 == 1)
{
cout << "OH CRAP! You rolled snake eyes!" << endl;
cout << " Your turn is over. " << endl;
playerScore == 0;
}
The way you have the conditional written, it just checks to see if roll1 is anything besides zero (that's the part before &&) and then it checks if roll2 is equal to 1. The conditional should probably read: else if (roll1 == 1 && roll2 == 1).
And I think you want to assign (=) playerScore at the bottom rather than evaluate for equality (==). You already know this, but this is what it should look like: playerScore = 0.
I am stuck on something I know should be really simple to fix but I just can't figure it out I've been Google-ing and gone through my text (Gaddis C++ Intro, Ch. 6) and tried a few things - mostly moving the loop around as I thought I placed it wrong; I've searched through several C++ forums as well and I have found examples where you ask the userj "do you want to continue/play again" but that is not what I am to do, I am to have it automatically restart if there is a tie. It keeps coming back to the variables not being defined/declared for use within the loop -- except I don't see how they aren't. I'm using VS 2010.
Here's the code. I appreciate any help. I feel kinda stupid for not being able to fix this myself. This is my first programming class and I'm also taking visual basic at the same time. It's been interesting.
The debug errors I'm getting are both C2065 "undeclared identifier" for both cpuChoice and userChoice.
[code]
#include <iostream>
#include <ctime>
using namespace std;
void outputChoice(int c)
{
switch(c)
{
case 1:
cout << "Rock";
break;
case 2:
cout << "Paper";
break;
case 3:
cout << "Scissors";
break;
case 4:
cout << "Lizard";
break;
case 5:
cout << "Spock";
break;
}
}
//bool for determining if win or if draw -- loss will be elseif
bool isWin(int userChoice, int cpuChoice)
{
bool result =
( (userChoice == 1 && cpuChoice == 3) ||
(userChoice == 1 && cpuChoice == 4) ||
(userChoice == 2 && cpuChoice == 1) ||
(userChoice == 2 && cpuChoice == 5) ||
(userChoice == 3 && cpuChoice == 2) ||
(userChoice == 3 && cpuChoice == 4));
return result;
}
bool isDraw(int userChoice, int cpuChoice)
{
bool result =
( (userChoice == cpuChoice));
return result;
}
int main()
{
do{
srand(time(NULL));
cout << "Welcome to Rock Paper Scissors Lizard Spock!" << endl;
cout << "The rules are the same as traditional Rock Paper Scissors with the additions as follows: Lizard";
cout << " beats Paper & Spock; Spock defeats Rock & Scissors.\n\n" << endl;
cout << endl;
{
int userChoice;
cout << "Please choose your move. Select 1-5: \n\n";
cout << "1) Rock" << endl;
cout << "2) Paper" << endl;
cout << "3) Scissors" << endl;
cout << "4) Lizard" << endl;
cout << "5) Spock\n\n" << endl;
cin >> userChoice;
if (!(userChoice >= 1 && userChoice <= 5))
{
cout << "Please choose 1, 2, 3, 4 or 5!" << endl;
}
else
{
int cpuChoice = rand() % 5 + 1;
cout << "You chose... ";
outputChoice(userChoice);
cout << endl;
cout << "The computer chose... ";
outputChoice(cpuChoice);
cout << endl;
cout << endl;
cout << "The result is..." << endl;
}
if (isWin(userChoice, cpuChoice))
{
cout << "You chose wisely! WINNER!!!!!" << endl;
}
else if (isDraw(userChoice, cpuChoice))
{
cout << "You chose well, but so did I - TIE!" << endl;
}
else
{
cout << "You chose poorly! You loose!" << endl;
}
}
while (userChoice == cpuChoice);
return 0;
}
[/code]
You problem is variable scope. change the first lines inside main():
int main()
{
int userChoice, cpuChoice;
do {
Then inside, instead of declaring these variables, just assign a value:
int cpuChoice = rand() % 5 + 1;
should be
cpuChoice = rand() % 5 + 1;
And get rid of the other declaration of userChoice altogether.
That should do it.
You declared these variables int the wrong scope. Move both declarations before the loop
int main()
{
int userChoice;
int cpuChoice;
do{
srand(time(NULL));
cout << "Welcome to Rock Paper Scissors Lizard Spock!" << endl;
cout << "The rules are the same as traditional Rock Paper Scissors with the additions as follows: Lizard";
cout << " beats Paper & Spock; Spock defeats Rock & Scissors.\n\n" << endl;
cout << endl;
{
cout << "Please choose your move. Select 1-5: \n\n";
cout << "1) Rock" << endl;
cout << "2) Paper" << endl;
cout << "3) Scissors" << endl;
cout << "4) Lizard" << endl;
cout << "5) Spock\n\n" << endl;
cin >> userChoice;
if (!(userChoice >= 1 && userChoice <= 5))
{
cout << "Please choose 1, 2, 3, 4 or 5!" << endl;
}
else
{
cpuChoice = rand() % 5 + 1;
cout << "You chose... ";
outputChoice(userChoice);
cout << endl;
cout << "The computer chose... ";
outputChoice(cpuChoice);
cout << endl;
cout << endl;
cout << "The result is..." << endl;
}
if (isWin(userChoice, cpuChoice))
{
cout << "You chose wisely! WINNER!!!!!" << endl;
}
else if (isDraw(userChoice, cpuChoice))
{
cout << "You chose well, but so did I - TIE!" << endl;
}
else
{
cout << "You chose poorly! You loose!" << endl;
}
}
while (userChoice == cpuChoice);
return 0;
}