check to see who wins in a dice game - c++

I have a dice game
int userGame()
{
cout << " User turn --- Press 2 to roll" << endl;
cin >> userInput;
if ( userInput == 2 )
{
Dice ();
cout << "The user rolled Dice 1 =" << die1 << " and Dice 2 = " << die2 << endl;
cout << "Total = " << die1 + die2 << endl;
}
else {
cout << "Wrong input. Try again";
//userGame();
}
return (die1 + die2);
}
and now in int main , I have -
int main ()
{
// set the seed
srand(time(0));
userGame();
while (true)
{
if (userGame() == 7 || userGame() == 11)
{
cout << "You won" << endl;
break;
}
else if (userGame() == 2)
{
cout << "You loose" <<endl;
break;
}
else
{
break;
}
}
return 0;
Dice ();
#include<iostream>
#include<ctime> // for the time() function
#include<cstdlib> // for the srand() and rand() functions
using namespace std;
int compInput;
int userInput;
int die1 = 0;
int die2 = 0;
int Dice ()
{
// roll the first die
die1 = (rand() % 6 ) + 1;
// roll the second die
die2 = (rand() % 6 ) + 1;
}
But the output for some reason is not showing up right. Once it will show that the user won when the output is 7 and other time, it would just continue with the game.
What am i doing with the loop in main()?
Thanks

if (userGame() == 7 || userGame() == 11)
This line is your problem. C++ uses short circuit evaluation. In this case, if userGame() == 7 succeeds, it doesn't check the second half. However, if it fails userGame() will be called again for the second half, meaning you'll play twice before going into the code section for the if.
while (true)
{
int result = userGame();
if (result == 7 || result == 11)
{
cout << "You won" << endl;
break;
}
else if (result == 2)
{
cout << "You loose" <<endl;
break;
}
else
{
break;
}
}

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());
}

C++ Putting a character into a cin for a while loop causes the loop to execute outside of it [duplicate]

This question already has answers here:
Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]
(4 answers)
Closed 5 years ago.
I decided to try to make a little game. It's a simple survival game. Part of it has people try to survive as long as they can by choosing options. I've scaled down the game as much as possible from 1000 lines to this for the minimum case.
At one part of the game it asks, "You were visited by a gifting clown. On a scale of 0-10, how badly do you want a gift?"
If they answer 0-10, the loop works fine. If they answer with a character, like y or n, the loop basically forces the game to execute where it no longer asks players for input on any other choices.
A previous while loop works, one where it will continue so long as the player is alive. This clown while loop is nested inside of it. I have broken up the while loop with the clown section to where I think the problem is... And also included the full code just in case it's not inside there.
My goal is simply if a character is put into it, that it doesn't break this game.
main.cpp - clown section
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
main.cpp - Condensed code
#include <iostream>
#include <iomanip>
#include <random>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand (time(NULL));
int randNumber = 0;
int food = 4;
int wood = 4;
int medicine = 2;
int bullets = 8;
int money = 25;
int randomEncounter = 0;
int hunt = 0;
bool axe = false;
int axeTemp = 0;
int axeBonus = 0;
int lumberTemp = 0;
int lumber = 0;
int findStore = 0;
int storeChoice = 0;
bool gun = false;
int gunSearch;
int gunTemp;
int gunBonus = 0;
int gunFind = 0;
// int searches;
// int searchesBonus;
int farmFind = 0;
int farmFood = 0;
int farmSearch = 0;
bool farm = false;
string description;
int foodTemp = 0;
int woodTemp = 0;
int medicineTemp = 0;
int bulletsTemp = 0;
int moneyTemp = 0;
int huntTemp = 0;
int huntSuccess = 0;
char huntChoice;
int encounterFood = 0;
int encounterWood = 0;
int encounterBullets = 0;
int encounterMedicine = 0;
int encounterHurt = 0;
unsigned int encounterChoice = 0;
int hurt = 0;
int health = 3;
int healthMax = 3;
int days = 1;
char action = '0';
char pause = '1';
char classChoice;
char mainChoice;
bool clown = true;
int clownHealth = 5;
char clownChoice;
int yourShot = 0;
int clownShot = 0;
string place;
//Food 1 per day per person. Can expand to include more people.
//Fuel 1 per day, takes that much to stay warm even if fewer people
//Medicine used one per wound
//Bullets 1 to hunt, though can spend more to increase chance of success.
//Days how many days that they have survied.
//Health, everyone starts with three health. Good, okay, bad, dead.
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets << " Health: " << health << endl;
while (health > 0){
cout << "\nDay: " << days;
cout << "\nFood: " << food
<< "\nWood: " << wood
<< "\nMedicine: " << medicine
<< "\nBullets: " << bullets
<< "\nHealth: " << health
<< "\nMoney: " << money << endl;
if (food >= 1){
food--;
}
if (wood >= 1){
wood--;
}
if (food <= 0){
health--;
cout << "Health lost due to lack of food" << endl;
}
if (health < healthMax && medicine > 0){
health++;
medicine--;
cout << "Health pack used to heal your character\nHealth : " << health << endl;
}
action = '0';
cout << "\n1: Find food" << endl;
cout << "What's your action? ";
cin >> action;
cout << endl;
if (action == '1'){
//
//Section for random sites to search.
//
//
randNumber = rand() % 4;
description = "";
//Maybe + days at the end, and subtract some, so that they eventually run out of places to check.
if (randNumber >= 0 && randNumber < 2) {
place = "supermarket";
foodTemp = (rand() % 4) + 1;
woodTemp = (rand() % 2) + 0;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 1;
moneyTemp = (rand() % 5) + 5;
}
if (randNumber >= 2 && randNumber < 4) {
place = "boat house";
foodTemp = (rand() % 2) + 1;
woodTemp = (rand() % 4) + 1;
bulletsTemp = (rand() % 2) + 0;
medicineTemp = (rand() % 2) + 0;
moneyTemp = (rand() % 3) + 0;
}
cout << "You have come to the " << place << "." << endl;
cout << description << endl;
food += foodTemp;
wood += woodTemp;
bullets += bulletsTemp;
medicine += medicineTemp;
money += moneyTemp;
if (foodTemp > 0)
cout << "You have found " << foodTemp << " food." << endl;
if (woodTemp > 0)
cout << "You have found " << woodTemp << " wood." << endl;
if (medicineTemp > 0)
cout << "You have found " << medicineTemp << " medicine." << endl;
if (bulletsTemp > 0)
cout << "You have found " << bulletsTemp << " bullets." << endl;
if (moneyTemp > 0)
cout << "You have found " << moneyTemp << " money." << endl;
cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets
<< " Health: " << health << " Money: " << money << endl;
//End of search rooms.
}
//Random encounter chance to see if they can gain additional items.
encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true){
encounterChoice = 1;
cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
while (encounterChoice >= 0 && encounterChoice <= 10){
cin >> encounterChoice;
encounterFood = (rand() % 3) + encounterChoice / 2;
encounterWood = (rand() % 3) + encounterChoice / 2;
encounterMedicine = (rand() % 2);
encounterBullets = (rand() % 2);
if (encounterChoice > 0){
encounterHurt = (rand() % 10) - encounterChoice;
if (encounterHurt <= 1){
health--;
cout << "The crazy clown stabs you, but still provides gifts.";
}
}
if (encounterFood > 0) {
cout << "\nYou were provided with " << encounterFood << " food." << endl;
food += encounterFood;
}
if (encounterWood > 0) {
cout << "\nYou were provided with " << encounterWood << " wood." << endl;
wood += encounterWood;
}
if (encounterMedicine > 0) {
cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
medicine += encounterMedicine;
}
if (encounterBullets > 0) {
cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
bullets += encounterBullets;
}
encounterChoice = 11;
}
//Option to attack clown
//
//
}
//End of random encounter from the clown.
//Pause mechanic to prevent the game from cycling.
// pause = 'b';
// while (pause != 'a'){
// cout << "\nEnter a to continue: ";
// cin >> pause;
// }
//End of game message
cout << endl;
if (days == 100){
cout << "You have made it to 100 days. You have beaten this game. You can quit now, or try to see how long you'll last." << endl;
}
//Add day at end of while loop.
days++;
}
cout << "You have died after " << days << " days" << endl;
}
From another Stack Overflow question...
When an error occurs when reading from a stream, an error flag gets
set and no more reading is possible until you clear the error flags.
That's why you get an infinite loop.
cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

C++: Expected a declaration

I am a complete noob at programming and I am having multiples errors that says "expected a declaration"
A project was assigned to us that required to create a text base game with characters attacking opponents.
We are to make characters and when we tell them to attack we must enter the correct key to attack.
This is what I have so far:
#include <cstdlib>
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
int Opponent;
int showOpponentHealth(int OpponentHealth, int Attack);
int showHealth(int Health, int OpponentAttack);
int showMagic(int Magic);
{ //Error: expected a declaration
public:
Opponent() : OpponentAttack(0), OpponentHealth(3);
{
OpponentAttack = rand() % 100;
OpponentHealth = rand() % 6 + 10;
}
}
int getAttack(Opponent);
{ //Error: expected a declaration
AttRoll = Rand() % 100
if (AttRoll < getAtt)
hit
{
AttType = 1 - 3
if (AttType == 1)
return 30
else if (AttType == 2)
return 50
else if (AttType == 3)
return 70
}
float character::getHeal()
{
magicCost = magic - 6;
Heal = rand() % 3 + 5;
cout << "Heal value= " << heal << ".\n";
return Heal;
}
}
void Battle()
{
int Health = rand() % 6 + 10;
int OpponentHealth = rand() % 6 + 10;
int hit;
}
long timeTest()
{
//seed the random number generator
srand(GetTickCount64());
//rand will give a number between 0 and max integer value
int waitTime = rand() % 5 + 1;
for (int i = waitTime; i>0; i--)
{
cout << "*";
Sleep(1000); //wait for 1 second
}
char typeThis = rand() % 26 + 97;
cout << typeThis << ":";
char playerResponse;
//this is the window function I'm using to get the time: ULONGLONG WINAPI GetTickCount64(void);
ULONGLONG startTime = GetTickCount64();
cin >> playerResponse;
ULONGLONG endTime = GetTickCount64();
if (playerResponse != typeThis)
return -1;
long deltaTime = endTime - startTime;
return deltaTime;
}
do //syntax error
{ //Error: expected a declaration
cout << " Attack Opponent? \n Yes = 1\n"
cin >> Attack Opponent;
if (AttackOpponent == 1)
{
OpponentHealth = showOpponentHealth(OpponentHealth, Attack);
Health = showHealth(health, OpponentAttack);
cout << "You attacked the Opponent with a light attack.";
cout << "The Opponent now has " << OpponentHealth << "health left.";
if (OpponentHealth <= 0)
{
cout << "You Win!";
}
else if (OpponentHealth > 0)
{
cout << "Opponent attacks back";
cout << "You have" << Health << "health left,";
}
else if (AttackOpponent == 2)
cout << "You attacked the Opponent with a medium attack.";
cout << "The Opponent now has " << OpponentHealth << "health left.";
{ //Error: expected a declaration
else if (AttackOpponent == 3)
cout << "You attadcked the Opponent with a heavy attack.";
cout << "The Opponent now has " << Opponent Health << "health left.";
}
} //Error: expected a declaration
int showOpponentHealth(int OpponentHealth, int Attack)
{
OpponentHealth = OpponentHealth - Attack;
return OpponentHealth;
}
int showHealth(int Health, int OpponentAttack)
{
Health = Health - OpponentAttack;
return Health;
}
}
int main()
{
cout << "Try the timeTest: " << timeTest() << endl;
int Health = rand() % 6 + 10;
if (Health <= 0)
cout << "You Died. Game Over." << endl;
int Magic = 10
else (Magic <= 0)
cout << "No more Magic." << endl;
system("Pause");
return0;
}
the errors pop up at the brackets and at "do"
Your do{ ... } loop is outside of any function. It must be inside of a function - the compiler is telling you it expects a declaration of a function like:
long timeTest()
Did you mean for the do-loop to be inside timeTest()?

Having problems with my one-armed bandit game in C++

Im currently making a one-armed bandit game and this is what it's supposed to do:
The user should be able to put money into the machine, 50, 100 or 500
The user should be able to bet money for each game
After the user have betted money symbols should be randomized in a field like this:
[ o ] [ p ] [ x ]
[ x ] [ x ] [ x ]
[ x ] [ o ] [ x ]
(1 columns/ lines wins 2x money, 2 columns/ lines wins 4x money etc.)
This field should each time be randomized with letters , also a two-dimensional array should be used to represent the gamearea.
I've ran into some problems, basically after I bet some money the game closes and I cant see any errors etc, any help that clarifies this problem would be greatly appreciated, aswell as any improvements I could do to my code etc.
This is my code:
#include <iostream>
#include <ctime>
using namespace std;
int main(int args, const char* argv[])
{
int svar = 0;
int bokstav = 0;
int insert;
int build;
int bet;
int credit;
int array;
int jackpot;
int tal;
int spin_1x = 0;
int spin_1y = 0;
int spin_2x = 0;
int spin_2y = 0;
cout << "Welcome to the one-armed bandit!" << endl;
cout << endl;
cout << "To play start by betting some money!" << endl;
cout << endl;
cout << "Insert 50/ 100/ 500 kr to your account!" << endl;
cout << endl;
cin >> insert;
while (insert < 50 || insert > 500)
{
cout << "You either inserted to little or to much" << endl;
cin >> insert;
}
cout << "You inserted" << insert;
cout << endl;
while (insert > 50)
{
cout << "Bet some money to play!" << endl;
cout << endl;
cin >> bet;
cout << endl;
while (bet !=50 && bet !=100 && bet !=500)
{
if (bet == 50) return 1;
{
cout << "You have betted 50 kr!" << endl;
}
{
if (bet == 100) return 2;
{
cout << "You have betted 100 kr!" << endl;
}
{
if (bet == 500)
{
cout << "You have betted 500 kr!" << endl;
}
char a = '£';
char b = '$';
char c = '*';
char build [4][4] = {
{ ' ', 'A', 'B', 'C',},
{ '1', ' ', ' ', ' ',},
{ '2', ' ', ' ', ' ',},
{ '3', ' ', ' ', ' ',},
};
int array();
cout << build[0][1] << " " << build[0][2] <<" "<< build[0][3] <<" " << endl;
cout << build[1][0] <<"|_|" <<"|_|" << "|_|" << endl
<< build[2][0] <<"|_|" <<"|_|" << "|_|" << endl
<< build[3][0] <<"|_|" <<"|_|" << "|_|" << endl;
return 0;
srand(time(0));
spin_1x=rand() % 4 + 1;
spin_1y=rand() % 4 + 1;
spin_2x=rand() % 4 + 1;
spin_2y=rand() % 4 + 1;
int y = 0;
int x = 0;
if (x == spin_1x && y == spin_1y)
{
build[x][y]='0';
cout << "Congrats you won!" << endl;
}
else if (x == spin_2x && y == spin_2y)
cout << "Congrats you won!" << endl;
cout << endl;
cout << "JACKPOT!" << endl;
{
if (insert <= 0)
{
cout << "You dont have any money left! Game's over!" << endl;
}
int insert;
if ((a == 7 && b == 7 && c == 7))
{
cout << "You have won x2 your bet!($" << ( bet*2) << ")" << endl;
credit = credit + (bet*2);
}
else if ((a == b == c) && ! (a == 7 && b == 7 && c == 7))
{
cout << "You have won x4 your bet!($" << (bet*4) << ")" << endl;
credit = credit + (bet*4);
}
else if ((a == b || a == c || b == c) && !(a == b == c) && !(a == 7 && b == 7 && c == 7))
{
credit = credit + (bet*8);
cout << "You have won x8 your bet!($" << (bet*8) << ")" << endl;
}
else if ((a == b || a == c || b == c) && ! (a == b == c) && ! (a == 7 && b == 7 && c == 7))
{
credit = credit + (bet*16);
cout << "You have won x16 your bet!($" << (bet*16) << ")" << endl;
}
else if (( a == b || a == c || b == c) && ! (a == b == c) && ! (a == 7 && b == 7 && c == 7))
{
credit = credit + (bet*128);
cout << "You have won x128 your bet!($" << (bet*128) << ")" << endl;
}
else
{
cout << "You have lost your betting!($-" << bet << ")" << endl;
credit = credit - bet;
}
return credit;
}
}
return 0;
}
}
}
}
The issue, as others stated, is that you are returning from your main which terminates the program. My suggestion:
Move your game logic into a separate method(s)
Place the logic call inside a while loop in the main that checks if the player wants to play again
Only return from main when the player wants to stop
Example partial code (you should get the idea):
void printWelcome( )
{
std::cout << "Welcome to the One-Armed Bandit!" << std::endl;
// etc.
}
int getBet( )
{
int betAmount;
std::cout << "To play start by betting some money!\n"
<< "Insert 50/ 100/ 500 kr to your account!" << std::endl;
std::cin >> betAmount;
return betAmount;
}
void playGame( )
{
// All of your game logic in here
}
bool wantsToPlay( )
{
std::cout << "Do you want to play again? (y/n)" << std::endl;
char response;
std::cin >> response;
if( response == 'y' )
{
return true;
}
else
{
return false;
}
}
int main( int argc, char** argv )
{
int betAmount = 0;
printWelcome( );
do
{
betAmount = getBet( );
if( betAmount != 50 && betAmount != 100 && betAmount != 150 )
{
// Restart the game loop (ask for bet again)
continue;
}
playGame( );
} while( wantsToPlay( ) );
std::cout << "Thank you for playing!" << std::endl;
return 0;
}
Your console is closing because the program is terminated when the main function hits a return , put a cin before each return. That will "pause" the application just before it terminates letting you see your traces.
Run your program by yourself instead of computer and you will see why its closing so fast. Remember that return in main() means "close program now".

C++ Tic Tac Toe - Problems detecting Tie

The title kind of says it all. I'm not sure exactly why the Tic Tac Toe program is not detecting a tie. I've attached the main function, additional functions, etc.. I'm not sure what im doing wrong. Any help is greatly appreciated.
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
string displayBoard(string board[9]); // displays tic tac toe board
bool isGameOver(string board[9]); // checks if game is over
void displayGameWelcome(); // displays welcome message
int main()
{
string board[9]; // tic tac toe, top row 0 thru 2, middle row 3 thru 5, bottom row 6 thru 8
int position = 0; // player's position
bool gameOver = false; // flag variable to mark end of the game
bool validMove = false; // determines if move is valid or not
displayGameWelcome();
// initializing board with blank spaces
for (int i = 0; i < 9; i++)
{
board[i] = " ";
}
while (!gameOver)
{
// player #1's turn **************************
validMove = false;
while (!validMove)
{
cout << "Enter your position: ";
cin >> position;
if (position >= 0 && position <= 8 && board[position] == " ")
{
validMove = true;
board[position] = "x"; // placing x in desired board location
}
else
{
cout << "That position is already occupied." << endl;
cout << displayBoard(board) << endl;
}
}
cout << displayBoard(board) << endl;
if (isGameOver(board))
{
gameOver = true;
}
// player #2's turn **********************************
validMove = false;
while (!validMove)
{
cout << "Enter your position: ";
cin >> position;
if (position >= 0 && position <= 8 && board[position] == " ")
{
validMove = true;
board[position] = "o"; // placing o in desired board position
}
else
{
cout << "That position is already occupied." << endl;
cout << displayBoard(board) << endl;
}
}
cout << displayBoard(board) << endl;
if (isGameOver(board))
{
gameOver = true;
}
}// end of validMove while loop
system("pause");
return 0;
}// end of main
// ************************** functions *************************
void displayGameWelcome()
{
cout << "Welcome to Tic Tac Toe v3.2" << endl;\
cout << "by Brett Singley & Nick Canarelli" << endl;
cout << "****************************\n\n\n";
}// end of displayGameWelcome
// checks if game is over
bool isGameOver(string board[9])
{
if (board[0] == "x" && board[1] == "x" && board[2] == "x")
{
cout << endl << "The game is over - x wins" << endl;
return true;
}
else if (board[0] == "o" && board[1] == "o" && board[2] == "o")
{
cout << endl << "The game is over - o wins" << endl;
return true;
}
else if (board[3]=="x" && board[4]=="x" && board[5]=="x")
{
cout <<endl << "The game is over - X wins" <<endl;
}
else if (board[3]=="o" && board[4]=="o" && board[5]=="o")
{
cout <<endl << "The game is over - o wins" <<endl;
}
else if (board[0]=="x" && board[3]=="x" && board[6]=="x")
{
cout <<endl << "The game is over - X wins" <<endl;
}
else if (board[0]=="o" && board[3]=="o" && board[6]=="o")
{
cout <<endl << "The game is over - o wins" <<endl;
}
else if (board[6]=="x" && board[7]=="x" && board[8]=="x")
{
cout <<endl << "The game is over - X wins" <<endl;
}
else if (board[6]=="o" && board[7]=="o" && board[8]=="o")
{
cout <<endl << "The game is over - O wins" <<endl;
}
else if (board[1]=="x" && board[4]=="x" && board[7]=="x")
{
cout <<endl << "The game is over - X wins" <<endl;
}
else if (board[1]=="o" && board[4]=="o" && board[7]=="o")
{
cout <<endl << "The game is over - O wins" <<endl;
}
else if (board[2]=="x" && board[5]=="x" && board[8]=="x")
{
cout <<endl << "The game is over - X wins" <<endl;
}
else if (board[2]=="o" && board[5]=="o" && board[8]=="o")
{
cout <<endl << "The game is over - o wins" <<endl;
}
else if (board[0]=="x" && board[4]=="x" && board[8]=="x")
{
cout <<endl << "The game is over - X wins" << endl;
}
else if (board[0]=="o" && board[4]=="o" && board[8]=="o")
{
cout <<endl << "The game is over - o wins" <<endl;
}
else if (board[2]=="x" && board[4]=="x" && board[6]=="x")
{
cout <<endl << "The game is over - X wins" <<endl;
}
else if (board[2]=="o" && board[4]=="o" && board[6]=="o")
{
cout <<endl << "The game is over - o wins" <<endl;
}
else
{
cout << "WOAH!!!!! Tie Game" <<endl;
}
// more to do here (don't forget to check for draw)
return false;
}// end of isGameOver
// displays tic tac toe board in the format
// |0 1 2|
// |3 4 5|
// |6 7 8|
string displayBoard(string board[9])
{
string str = "";
for (int i = 0; i < 9; i++)
{
if (i == 0)
{
str = str + "|" + board[i];
}
else if (i == 2 || i == 5)
{
str = str + board[i] + "|\n|";
}
else if (i == 8)
{
str = str + board[i] + "|\n";
}
else
{
str = str + board[i];
}
}
return str;
}// end of displayBoard
You can simplify checking for a winner by using for loops and realizing that the value in the three spaces are equal (to something other than the initial value). Also, since there are 3 rows and 3 columns, the rows and columns can be checked inside the same for loop:
const char initial_value = ' ';
const unsigned int max_rows_or_columns = 3;
bool Is_Game_Over(int board[9], char& winner)
{
for (unsigned int i = 0; i < max_rows_or_columns; ++i)
{
// Check the row
if ( (board[(i * 3) + 0] == board[(i * 3) + 1])
&& (board[(i * 3) + 1) == board[(i * 3) + 2]))
{
// By transitive property, board[(i * 3) + 0] == board[(i * 3) + 2]
winner = board[(i * 3) + 0];
if (winner != initial_value)
{
break;
}
}
else // Check the columns
{
if ( (board[(0 * 3) + i] == board[(1 * 3) + i])
&& (board[(1 * 3) + i] == board[(2 * 3) + i]))
{
winner = board[(0 * 3) + i];
if (winner != initial_value)
{
break;
}
}
}
bool winner_found = true;
if (i >= max_rows_or_columns)
{
winner_found = false;
}
return winner_found;
}
The checking of the diagonals is left as an exercise for the reader.