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());
}
Related
I'm making a blackjack game and I have a pointer arrays for my dealer's and player's hand. The issue is that when I randomly generate cards to be stored in the array, they both have the same cards. Not sure if it is because they both point to the same address or something I haven't noticed.
#include <iostream>
#include <ctime>
#include <random>
#include <iomanip>
#include <cstdlib>
using namespace std;
class Blackjack
{
public:
Blackjack();
void playGame();
int pbalance;
int betamount;
int loop= 1;
int *playerbalances;
int pbalan,pbal;
void firstbalance();
void clearhand();
private:
int dhandSize;
int phandSize;
int dhandSum;
int phandSum;
int phit;
int pstand;
bool playerDone;
bool dealerDone;
void addPlayerCard();
void addDealerCard();
void printHand();
void sumHands();
void playerbalance();
void playerbet();
int *dhand[];
int *phand[];
};
Blackjack::Blackjack()
{
srand(time(0));
dhandSize = 0;
phandSize = 0;
dhandSum = 0;
phandSum = 0;
playerDone = false;
dealerDone = false;
}
void Blackjack::playGame()
{
if (pbal>0)
{
// Start the player and dealer with two cards
playerbet();
addPlayerCard();
addPlayerCard();
addDealerCard();
addDealerCard();
sumHands();
printHand();
if (dhandSum == 21)
{
cout << "Dealer has blackjack. Dealer wins.\n";
clearhand();
return;
}
else if (phandSum == 21)
{
cout << "Player has blackjack. Player wins.\n";
clearhand();
return;
}
while (dealerDone == false || playerDone == false)
{
if (playerDone == false)
{
cout << "Would you like to hit? (1 - Yes, 2 - No)\n";
cin >> phit;
if (phit == 1)
{
addPlayerCard();
printHand();
sumHands();
if (phandSum > 21)
{
cout << "Player's hand exceeded 21. Player loses"<<endl;
pbalan =(pbalan - betamount);
cout <<"[you lose $"<<betamount<<" of money!]"<<endl;
cout <<"[your current balance is: $"<<pbalan<<"]"<<endl;
clearhand();
return;
}
}
}
if (playerDone == false)
{
cout << "Would you like to stand? (1 - Yes, 2 - No)\n";
cin >> pstand;
}
if (pstand == 1)
{
playerDone = true;
}
if (dhandSum < 17 && dealerDone != true)
{
addDealerCard();
printHand();
sumHands();
if (dhandSum > 21)
{
cout << "Dealer hand exceeded 21. Dealer loses.\n";
return;
}
}
else if (dhandSum >= 17)
{
dealerDone = true;
}
if (phandSum == 21 && dhandSum == 21)
{
cout << "Push, player and dealer reached 21.\n";
return;
}
else if (phandSum == 21)
{
cout << "Player reached 21. Player wins.\n";
return;
}
else if (dhandSum == 21)
{
cout << "Dealer reached 21. Dealer wins.\n";
pbalan =(pbalan - betamount);
cout <<"[you lose $"<<betamount<<" of money!]"<<endl;
cout <<"[your current balance is: $"<<pbalan<<"]"<<endl;
return;
}
if ((playerDone == true && dealerDone == true) || (phandSize == 5 && phandSize == 5))
{
if (dhandSum < phandSum)
{
cout << "Sum of your hand exceeds the dealer's sum of " << dhandSum << "! You win!";
return;
}
else if (phandSum == dhandSum)
{
cout << "Dealer sum of " << dhandSum << " is equal to the sum of your hand. Tie game.";
return;
}
else if (dhandSum > phandSum)
{
cout << "Sum of your hand is lower than the dealer's sum of " << dhandSum << ". You lose!"<<endl;
pbalan =(pbalan - betamount);
cout <<"[you lose $"<<betamount<<" of money!]"<<endl;
cout <<"[your current balance is: $"<<pbalan<<"]"<<endl;
return;
}
}
}
}
}
void Blackjack::clearhand()
{
for (int i = 0; i < dhandSize; i++) { delete dhand[i]; }
for (int i = 0; i < phandSize; i++) { delete phand[i]; }
phandSize = 0;
dhandSize = 0;
}
void Blackjack::firstbalance()
{
cout << "Welcome to Blackjack" <<endl;
cout << "please enter a starting balance: " <<endl;
cin >> pbal;
playerbalances = &pbalan;
*playerbalances = pbal;
}
void Blackjack::playerbet()
{
cout << "how much do you want to bet?"<<endl;
cin >> betamount;
}
void Blackjack::addPlayerCard()
{
if (phandSize <= 5)
{
*phand[phandSize] = 1 + (rand() % 13);
phandSize++;
}
else
{
cout << "Sorry. You have reached the maximum number of cards (5)." << endl;
playerDone = true;
}
}
void Blackjack::addDealerCard()
{
if (dhandSize <= 5)
{
*dhand[dhandSize] = 1 + (rand() % 13);
dhandSize++;
}
else
{
dealerDone = true;
}
}
void Blackjack::printHand()
{
cout << "Your current hand is...\n";
for (int i = 0; i < phandSize; i++)
{
cout << " -" << *phand[i] << "- \n\n";
}
cout << "Dealer's current hand is...\n";
for (int j = 0; j < dhandSize; j++)
{
cout << " -" << *dhand[j] << "- \n\n";
}
}
void Blackjack::sumHands()
{
dhandSum = 0;
phandSum = 0;
for (int i = 0; i < dhandSize; i++)
{
dhandSum += *dhand[i];
}
for (int j = 0; j < phandSize; j++)
{
phandSum += *phand[j];
}
cout << "Current player hand sum is: " << phandSum << endl;
}
using namespace std;
int main()
{
int exitGame = 1;
int i = 0;
Blackjack play;
if (i<1)
{
play.firstbalance();
i++;
}
do
{
play.playGame();
play.clearhand();
cout << "\nWould you like to play again? (1 - Yes, 2 - No)\n";
cin >> exitGame;
}
while (exitGame == 1);
cout << "\nThanks for playing!\n";
return 0;
}
The dealer cards should be different from the player cards but they are identical when you run the program.
The shows code declares a class with two members, as follows:
int *dhand[];
int *phand[];
These are the two members of the class, but this is not valid, standard C++. Variable-length arrays are not standard C++.
As such, the entire logic in this code becomes unspecified behavior. The behavior you observed was that the two arrays appear to be the same. Right. That's what unspecified behavior means, and this appears to be the behavior that results with your specific C++ compiler and implementation. Your C++ compiler appears to implement this by creating a class member whose size is a grand total of 0 bytes (after all, the size of the array is not specified, so it's nuthin'), with the expectation that this will be the last class member, and the application will be responsible for allocating some extra memory in addition to the one that's required for an instance of this object, in order to achieve a pseudo-array in this fashion.
But with two class members declares thusly, this ends up with two class members that are effectively one and the same. Which is the behavior you observed. Other C++ compilers may very well report a compilation error, since the program being ill-formed, with respect to the C++ standard.
To fix this issue you should replace these class members with proper arrays. Perusing the shown code, it looks like you expect these arrays to be, essentially, variably-sized arrays. This is what std::vector is for, and your C++ book should have one or more chapters that fully explain how to use std::vector to implement an array-like object that can grow and shrink in size, accordingly.
I am creating an RPG shop. It must have items, gold, and item price. Essentially creating an inventory. What i am trying to accomplish is, where the players gold is 0 they cannot add any more items to their inventory, and cannot have negative gold.
When running my code in debug mode it appears to be doing what i want, but when the function exits the amount the player requested has not been countered.
Keep in mind i am still new to c++.
Thanks
#include <iostream>
#include <string>
using namespace std;
// Global consts
const int numItems = 4;
const string items[numItems] = {"boots", "hats", "cats", "bats"}; // create string array of numItems items.
// Create stuct, that holds:
// Item, gold, price.
struct Inv {
int pInv[numItems] = {0, 0, 0, 0};
int gold = 100;
int itemPrice[numItems] = { 10, 6, 12, 15 };
}inv;
void iniItems();
void printItems();
bool buyItems();
bool sellItems();
int main() {
bool isDone = false;
iniItems();
while (isDone == false) {
printItems();
int choice;
bool x = false;
cout << "\nWhat would you like to do? Enter (" << 1 << "-" << 2 << "): " << endl;
cout << "1: Buy Items. \n2: Sell Items." << endl; cin >> choice; cout << endl;
while (x == false) {
if (choice == 1) {
x = buyItems();
}
if (choice == 2) {
x = sellItems();
}
}
}
system("pause");
// dynamic memory not implemented yet. Must wait for working fix of shoppe.cpp
}
void iniItems() {
cout << "** Shop Inventory: **" << endl;
for (int i = 0; i < numItems; i++) {
cout << i + 1 << " - " << items[i] << " - price: $" << inv.itemPrice[i] << endl;
}
}
void printItems() {
cout << "\n** Player Inventory: **" << endl;
cout << "Gold: $" << inv.gold << endl;
for (int i = 0; i < numItems; i++) {
cout << inv.pInv[i] << " x " << items[i] << endl;
}
}
bool buyItems() {
bool exit = false;
int amount;
const int remainder = 10;
printItems();
cout << "\nEnter -1 to quit." << endl;
cout << "What would you like to buy? Enter (" << 1 << "-" << 4 << "): " << endl;
// Get item info.
while (exit == false) {
int inp;
cout << "Item: "; cin >> inp; cout << endl;
cout << "Amount: "; cin >> amount; cout << endl;
// Check if input is valid.
if (inp > 0 && inp <= numItems) {
if (amount >= 0) {
inv.pInv[inp - 1] = 1 * amount;
inv.gold = inv.itemPrice[inp - 1] / amount;
}
// If gold is 0, make sure the user cannot gain more items.
if (inv.gold <= 0) {
int tmp;
inv.gold = 0;
tmp = remainder - amount;
for (int i = tmp; i >= 0; i++) {
inv.pInv[inp - 1]--;
}
return inv.pInv[inp - 1];
}
if (inp == -1) {
return true;
}
if (inp > numItems) {
cout << "Enter valid number." << endl;
return false;
}
else return false;
}
}
if (exit == true) {
return true;
}
}
So i limited the code down into a do while loop with a counter for the gold, in the buyItems() function.
Here it is, if anyone is interested.
do {
inv.gold -= inv.itemPrice[inp - 1];
++(inv.pInv[inp - 1]);
} while (inv.gold > 0);
if (inv.gold < 0) {
inv.gold = 0;
inv.pInv[inp - 1]--;
}
printItems();
I recently received an assignment to create a bowling program in C++ that simulates two people bowling and outputs the correct score for each frame. My program works by first generating all the throws for each frame and then accumulating the score afterwards in a separate method. I was able to get the program to work when the player bowls a non-perfect game and a perfect game, but I am having problems with when a player bowls all spares. I rigged the code to make it so I have 9 for a first throw and 1 for the second throw (this is in frame.cpp). The total should be 190, but I am getting 191 and I can't seem to find the error. Each bowling class contains an array of 11 frames. I know there are only 10 frames but this is to account for if the player gets a strike on the tenth frame. Any help would be appreciated, thanks.
Here is the frame. h file
#ifndef FRAME_H
#define FRAME_H
#include<iostream>
using namespace std;
class Frame
{
private: int throw1;
int throw2;
int score;
bool spare;
bool strike;
public: Frame();
int genThrow(int size);
int getFirstThrow();
int getSecondThrow();
int getScore();
void setScore(int);
void setFirstThrow(int value1);
void setSecondThrow(int value2);
void setStrike(bool value);
void setSpare(bool value);
bool getStrike();
bool getSpare();
};
#endif
Here is the frame.cpp file
#include "Frame.h"
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
Frame::Frame()
{
spare = false;
strike = false;
throw1 = 0;
throw2 = 0;
score = 0;
}
//generates a random throw
int Frame::genThrow(int size)
{
int randomNumber = 0;
if (size < 10 || throw1 != 10)
{
randomNumber = 0 + rand() % (11 - throw1); //generate a number between 0 and 10
}
else
{
randomNumber = 0 + rand() % (11);
}
//cout << randomNumber << endl;
return randomNumber;
}
//get first throw
int Frame::getFirstThrow()
{
return throw1;
}
//get second throw
int Frame::getSecondThrow()
{
return throw2;
}
//get the score of both throws
int Frame::getScore()
{
return score;
}
//set the score
void Frame::setScore(int value)
{
score = value;
}
//set the first throw
void Frame::setFirstThrow(int value1)
{
//throw1 = genThrow(value1); //normal generator
//throw1 = 10; //strike game rigged
throw1 = 9; //spare game rigged
}
//set the second throw
void Frame::setSecondThrow(int value2)
{
//throw2 = genThrow(value2); //normal generator
throw2 = 1; //spare game rigged
//throw2 = 10; //strike game rigged
}
//set the strike
void Frame::setStrike(bool value)
{
strike = value;
}
//set the spare
void Frame::setSpare(bool value)
{
spare = value;
}
//get the strike
bool Frame::getStrike()
{
return strike;
}
//get the spare
bool Frame::getSpare()
{
return spare;
}
Here is the bowling.h file
#ifndef BOWLING_H
#define BOWLING_H
#include "Frame.h"
#include<iostream>
using namespace std;
class Bowling
{
private: Frame a[11];
public: void accumulateScore();
void bowl();
void printData();
};
#endif
Here is the bowling.cpp file
#include "Bowling.h"
#include<iostream>
using namespace std;
//takes all of the throw values after bowling and accumulates the correct score
void Bowling::accumulateScore()
{
int totalSum = 0;
for (int x = 0; x < 10; x++)
{
if (a[x].getFirstThrow() + a[x].getSecondThrow() < 10) //not a strike or spare
{
totalSum += a[x].getFirstThrow() + a[x].getSecondThrow();
a[x].setScore(totalSum);
}
else if (a[x].getFirstThrow() == 10) //throws a strike
{
if (x < 9)
{
totalSum += 10 + a[x + 1].getFirstThrow() + a[x + 1].getSecondThrow();
if (a[x + 2].getStrike() == true)
{
totalSum += 10;
}
a[x].setScore(totalSum);
}
}
else if (a[x].getFirstThrow() + a[x].getSecondThrow() == 10) //throws a spare
{
if(x < 10)
{
totalSum += 10 + a[x + 1].getFirstThrow();
a[x].setScore(totalSum);
}
}
}
//player got the 11th frame
if (a[9].getStrike() == true)
{
totalSum += 10 + a[10].getFirstThrow() + a[10].getSecondThrow();
a[9].setScore(totalSum);
}
else if (a[9].getSpare() == true)
{
totalSum += 10;
a[9].setScore(totalSum);
}
}
void Bowling::bowl()
{
//generate all throws and store them in the frames
for (int x = 0; x < 10; x++)
{
a[x].setFirstThrow(x);
if (a[x].getFirstThrow() == 10)
{
a[x].setStrike(true);
}
if (a[x].getStrike() == false)
{
a[x].setSecondThrow(x);
if (a[x].getFirstThrow() + a[x].getSecondThrow() == 10)
{
a[x].setSpare(true);
}
}
a[x].setScore(a[x].getFirstThrow() + a[x].getSecondThrow());
}
//play the 11th frame if they got a strike on the tenth frame
if(a[9].getStrike() == true)
{
a[10].setFirstThrow(10);
if (a[10].getFirstThrow() == 10)
{
a[10].setStrike(true);
}
a[10].setSecondThrow(10);
cout << "The second throw is this value: " << a[10].getSecondThrow() << endl;
if (a[10].getSecondThrow() == 10)
{
a[10].setStrike(true);
}
else if (a[10].getFirstThrow() + a[10].getSecondThrow() == 10)
{
a[10].setSpare(true);
}
a[9].setScore(a[10].getFirstThrow() + a[10].getSecondThrow());
}
}
void Bowling::printData()
{
for (int x = 0; x < 10; x++)
{
cout << "*****************************" << endl;
cout << "Frame " << x + 1 << endl;
cout << "First throw: ";
if (a[x].getStrike() == true)
{
cout << "Strike!" << endl;
}
else
{
cout << a[x].getFirstThrow() << endl;
}
cout << "Second throw: ";
if (a[x].getStrike() == false)
{
if (a[x].getSpare() == true)
{
cout << "Spare!" << endl;
}
else if(a[x].getSpare() == false)
{
cout << a[x].getSecondThrow() << endl;
}
else
{
cout << endl;
}
}
cout << "Score: " << a[x].getScore();
cout << endl;
}
if (a[9].getStrike() == true)
{
cout << "*****************" << endl;
cout << "Frame 11" << endl;
cout << "First throw: ";
if (a[10].getStrike() == true)
{
cout << "Strike!" << endl;
}
else
{
cout << a[10].getFirstThrow() << endl;
}
cout << "Second throw: ";
if (a[10].getStrike() == false)
{
if (a[10].getSpare() == true)
{
cout << "Spare!" << endl;
}
else
{
cout << a[10].getSecondThrow() << endl;
}
}
else
{
cout << "Strike!" << endl;
}
//cout << "Score: " << a[10].getScore();
cout << endl;
}
}
Here is where I test it in main
#include "Bowling.h"
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int dummy = 0;
//create two players that can bowl
Bowling player1;
Bowling player2;
int player1Score = 0;
int player2Score = 0;
//have the players bowl their throws before accumulating score
player1.bowl();
player2.bowl();
//accumulate the score after all of the throws have been done
player1.accumulateScore();
player2.accumulateScore();
//print player 1 data
cout << "Here are the throws and score for the first player: " << endl;
player1.printData();
//spacing
cout << endl << endl;
//print player 2 data
cout << "Here are the throws and score for the second player: " << endl;
player2.printData();
cout << "Enter a dummy number:" << endl;
cin >> dummy;
return 0;
}
This program should be accepting a bet, generating a set of cards for each player, and adding the bet to the winner's pool. This is a class project. I cannot figure out what the problem is on line 60.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct cards {
int value;
string face;
string suit;
bool facebool;
};
struct hand {
cards card[4];
int antiduplicate[52];
};
struct player {
string name;
int sum;
int money;
hand hand;
int bet;
};
struct points {
int player1;
int player2;
};
hand drawhand(int [52]);
points calcvalue(player, player);
int winner(player, player);
int main() {
points store = {};
player house = {"The House"};
player player1 = {};
srand (time(0));
cout << "Enter player 1's name:";
getline(cin,player1.name);
cout << "Enter player 1's money:";
cin >> player1.money;
cout << endl;
house.money = (player1.money + 1);
do{
int deckarray[52] = {0};
//do{
cout << "What do you want to bet?\n";
/* line 60 */ cin >> player1.bet;
cout << "check";
if (player1.bet < player1.money){
}
else if (player1.bet > player1.money){
cout << "\nYou cannot go into debt!!\n";
}
else if (player1.bet == 0){
cout << "\nYou ended the game!";
return 0;
}
//}while (bet > player1.money);
house.hand = drawhand(deckarray);
for (int i = 0; i < 52; i++) {
if (house.hand.antiduplicate[i] == 1)
deckarray[i] = 1;
}
player1.hand = drawhand(deckarray);
for (int i = 0; i < 52; i++) {
if (player1.hand.antiduplicate[i] == 1)
deckarray[i] = 1;
}
cout << "\nCheck check\n";
store = calcvalue(player1, house);
player1.sum = store.player1;
house.sum = store.player2;
cout << player1.name << "'s hand:\n" << player1.hand.card[1].face << " of " <<player1.hand.card[1].suit << endl
<< player1.hand.card[2].face << " of " <<player1.hand.card[2].suit << endl <<player1.hand.card[3].face << " of " <<player1.hand.card[3].suit << endl;
cout << ">> " <<player1.name << " scored " << player1.sum << " points!\n\n";
cout << house.name << "'s hand:\n" << house.hand.card[1].face << " of " <<house.hand.card[1].suit << endl
<< house.hand.card[2].face << " of " <<house.hand.card[2].suit << endl <<house.hand.card[3].face << " of " <<house.hand.card[3].suit << endl;
cout << ">> " << house.name << " scored " << house.sum << " points!\n";
int win;
win = winner(player1, house);
if (win == 1){
cout << "\n" << player1.name << " wins the round!!" << endl;
player1.money = (player1.money + player1.bet); house.money = (house.money - player1.bet);
}
else if (win == -1){
cout << "\n\n" << house.name << " wins the round!!";
house.money = (house.money + player1.bet);
player1.money = (player1.money - player1.bet);
}
else if (win == 0){
cout << "\n\n" << house.name << " wins the round!!";
house.money = (house.money + player1.bet);
player1.money = (player1.money - player1.bet);
}
cout << endl << "House money: " << house.money << endl << "Player money: " << player1.money << endl << endl;
}while (player1.money > 0 && house.money > 0 && player1.bet != 0);
cout << "Game over!";
return 0;
}
hand drawhand(int deckarray[52])
{
string tsuit, tface;
int tvalue;
int suitvalue, facevalue;
bool tfacebool;
hand thand;
for (int i = 0; i < 4; i++) {
for (int i = 0; i < 52; i++) {
if (deckarray[i] == 1)
thand.antiduplicate[i] = 1;
}
int index;
do {
index = rand()%52;
} while (thand.antiduplicate[i] == 1);
thand.antiduplicate[i] = 1;
facevalue = (index%13 + 1);
suitvalue = (index / 13);
switch (suitvalue)
{
case 0: tsuit = "Hearts";
break;
case 1: tsuit = "Diamonds";
break;
case 2: tsuit = "Clubs";
break;
case 3: tsuit = "Spades";
break;
}
switch (facevalue)
{
case 1: tface = "Ace";
tvalue = 1;
break;
case 11: tface = "Jack";
tvalue = 10;
tfacebool = true;
break;
case 12: tface = "Queen";
tvalue = 10;
tfacebool = true;
break;
case 13: tface = "King";
tvalue = 10;
tfacebool = true;
break;
}
if ((facevalue > 1) && (facevalue < 11))
tface = to_string(facevalue);
if (facevalue < 11) tvalue = facevalue;
thand.card[i].suit = tsuit;
thand.card[i].face = tface;
thand.card[i].value = tvalue;
thand.card[i].facebool = tfacebool;
}
return thand;
}
points calcvalue(player player1, player house)
{
points tpoints;
player1.sum = ((player1.hand.card[1].value + player1.hand.card[2].value + player1.hand.card[3].value) % 10);
if (player1.hand.card[1].facebool == true && player1.hand.card[2].facebool == true && player1.hand.card[3].facebool == true)
player1.sum = 10;
house.sum = ((house.hand.card[1].value + house.hand.card[2].value + house.hand.card[3].value) % 10);
if (house.hand.card[1].facebool == true && house.hand.card[2].facebool == true && house.hand.card[3].facebool == true)
house.sum = 10;
tpoints.player1 = player1.sum;
tpoints.player2 = house.sum;
return tpoints;
}
int winner(player player1, player house){
int winorlose;
if (player1.sum > house.sum)
{winorlose = 1;}
else if (player1.sum < house.sum)
{winorlose = -1;;}
else if (player1.sum == house.sum)
{winorlose = 0;}
return winorlose;
}
I see a lot of problems at first glance actually. eg: You've called a hand object 'hand' (thus redefining it), if you're going to call your object names the same as their class/struct, at least differentiate them with capitalization. eg: call your hand struct "Hand" instead of "hand"
cout << "What do you want to bet? ";
cin >> player1.bet; // <==== problem
cout << "check";
if (player1.bet < player1.money){
}
else if (player1.bet > player1.money){
cout << "\nYou cannot go into debt!!\n";
}
else if (player1.bet == 0){
cout << "\nYou ended the game!";
return 0;
}
That being said the issue you are having specifically relating to this section of code probably has something to do with a "\n" staying in the buffer and not getting cleared. Try using cin.ignore(numeric_limits::max(),'\n'); to solve this problem (don't forget to #include limits as well).
Similar problem here: c++ cin input not working?
Unfortunately I'm pressed for time and don't have time for a thorough look. :(
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()?