whitecards (lowercase) skips other players in PlayerVector but the first - why? - c++

I have tried for several days to find a solution to this but I am at a loss.
I am creating a Cards Against Humanity game that makes use of a Player class. This player class has functions to add white cards, retrieve a white card, get rid of a white card, get name, set name, and others.
The program goes:
Main menu (goes to gameplay, how to play, credits, and quit)
Chooses number of players.
Creates vector of players
Sets player names.
Assigns eight cards to each player's whitecards vector.
Begins game.
The main issue I have is with the assigning eight cards to each player's whitecards vector.
This is the code for the part of the program that distributes cards.
for (i = 0; i < playercount; i++) /* Adds eight white cards to each player's vector of cards */
{
PlayerVector.at(i).addwhitecard();
PlayerVector.at(i).addwhitecard();
PlayerVector.at(i).addwhitecard();
PlayerVector.at(i).addwhitecard();
PlayerVector.at(i).addwhitecard();
PlayerVector.at(i).addwhitecard();
PlayerVector.at(i).addwhitecard();
PlayerVector.at(i).addwhitecard();
}
This is the section of Player.cpp that assigns a white card.
bool Player::addwhitecard()`{
whitecard_ptr = fopen("WhiteCards.txt", "r");
if (whitecard_ptr != NULL)
{
std::cout << "This Part Worked" << std::endl;
if (maxwhitecardcount >= whitecards.size())
{
std::cout << "Yes Continue Pls" << std::endl;
srand(time(0));
randomnumber = rand() % 398;
randomnumber2 = rand() % 398;
randomnumber3 = rand() % 398;
randomnumber4 = rand() % 398;
randomnumber5 = rand() % 398;
randomnumber6 = rand() % 398;
randomnumber7 = rand() % 398;
randomnumber8 = rand() % 398;
while (getline(WhiteCards, line))
{
++LineNo;
if (LineNo == randomnumber || LineNo == randomnumber2 || LineNo == randomnumber3 || LineNo == randomnumber4 || LineNo == randomnumber5 || LineNo == randomnumber6 || LineNo == randomnumber7 || LineNo == randomnumber8)
{
whitecards.push_back(line);
std::cout << "Yes! This size is: " << whitecards.size() << std::endl;
return true;
}
}
}
else
{
std::cout << name << "has too many white cards!";
return false;
}
}
}
This is the constructor for the player class.
Player::Player(std::string name, int points)
{
this->points = 0;
this->name = "PlayerName";
this->whitecards;
}
And this is the player class itself in the header file
class Player
{
public:
Player();
Player(std::string name, int points);
void drawwhitecard();
std::string getwhitecard();
void ridwhitecard();
void addpoint();
int getpoints();
bool addwhitecard();
void namechar();
bool showwhitecards();
bool setname();
std::string getname();
protected:
int points;
std::vector<std::string> whitecards;
std::string name;
int whitecardcount;
int maxwhitecardcount = 8;
int whitecardchoicenumber = 0;
};
I tried to put the whitecards vector as an argument in player, but I wasn't able to use the vector in the arguments list when creating a player object in the main code.
Can someone tell me where I went wrong? Whether I do actually need to put the vector in the arguments and how to use it in an arguments list.
Thanks in advance.

I found a solution to this, though it's somewhat long.
I had to add 56 other randomnumber variables that all the other players can use.
Sorry I couldn't provide a MCVE due to time constraints.

Related

c++ String returning with an extra char

I have tested my program and am certain right before being returned the string in my function equals "card001". But the returned value equals "card0011". I have no idea how this even happens. Help me before I lose my mind. ;)
std::string function_cardTexture(int card) {
//removes the last 1
card = card - 10000;
int ctr = 0;
card = floor(card / 10);
std::cout << card << std::endl;
//turn int card into a string
std::string a = static_cast<std::ostringstream*>(&(std::ostringstream() << card))->str();
//combines card and string a into one string
std::string nametext = "card00" + a;
std::cout << nametext << std::endl;
return (nametext);
}
void function_Battle(tempPlayer &Player, tempCard &card001) {
if (Player.Start == true) {
//Draw hand
for (int i = 0; i < Player.numDrawn; i++) {
int x = rand() % Player.deckSize + 0; ;
Player.Hand[i] = Player.Deck[x];
Player.Discarded[x] = 1;
}
Player.Start = false;
}
std::map<std::string, tempCard> Vars;
//draw hand
for (int i = 0; i < Player.handMax;i++) {
if (Player.Hand[i] != 0) {
sf::RectangleShape Card(sf::Vector2f(80.0f, 128.0f));
std::string nametext = function_cardTexture(Player.Hand[i]);
std::cout << nametext;
sf::Texture texture = Vars[nametext].Art;
Card.setTexture(&texture);
window.draw(Card);
}
}
}
Your problem is how you're printing things out without a newline in the function_Battle() function, so you're likely "smashing together" your new value with an old one. If you replace your main function with just a loop with clearer printing of values, you can see you don't have a problem:
http://coliru.stacked-crooked.com/a/8d1e4f51643b84b9
That link will go to an online compiler where I just replaced the calling function with a loop that makes numbers. It even supplies a negative one.

Terminate called after throwing an instance of 'std::bad_alloc' while using standard vector functions

I'm working on an assignment which asks us to model an 'elimination voting' procedure for a reality game. For that we use one class (Vote) for recording the name of the player to be eliminated and another (Voting) which doesn't get instanced anywhere, because its members are static (we need them to be). The votes are stored on a vector inside the Voting class.
The problem is that even when I use the push_back function to store the votes in the vector, after running the program for a few times I get an std::length_error with what(): basic_string::_M_create. After I close it and rerun, the first time I get an error like the one on the title (std::bad_alloc).
Any ideas? I'm suspecting that it has to do with the vector not deallocating memory correctly, but I'm not sure.
My code (Voting.h):
#ifndef VOTING_H_INCLUDED
#define VOTING_H_INCLUDED
#include <vector>
#include <map>
#include "Vote.h" //ignore this one
#include "Team.h" //this one too
class Voting
{
public:
static vector <Vote> votes; //votes cast during voting procedure
static map <string, int> results; //voting results (key: name, value: number of votes)
static void votingProcess(Team &team); //the whole voting procedure
};
#endif // VOTING_H_INCLUDED
Voting.cpp:
#include <vector>
#include <map>
#include <cstdlib>
#include "Vote.h"
#include "Voting.h"
using namespace std;
vector <Vote> Voting::votes(1); //initialize the vector for the votes
void voteCast(Team &team);
void Voting::votingProcess(Team &team)
{
voteCast(team);
}
void voteCast(Team &team)
{
int playerNumber = team.getNumberOfPlayers(); //number of players right now still in the team
int votingPlayer = 0; //index of the currently voting player
int votedPlayerIndex = -1; //index of the player to be voted for elimination
int reasonIndex = -1; //index of the selected reason for voting
Vote draft; //temporary empty vote
srand(time(NULL)); // initialize the RNG
Voting::votes.clear(); //clear the vector of any past votes
string reasons[4] = {"Den ta pame kala metaxi mas", "Einai ikanoteros/i apo emena kai ton/ti theoro apeili", "Den exei na prosferei kati stin omada", "Prospathei sinexeia na sampotarei tis prospatheies mas"};
//some reasons for elimination (i've tried smaller strings and even chars and it didn't work, so don't bother)
do
{
if (team.getPlayers()[votingPlayer].getAge() != 0 && team.getPlayers()[votingPlayer].getVotes() > 0)
//if the player with index votingPlayer has not been eliminated and has still votes to cast
{
do
{
votedPlayerIndex = rand() % 11; //select a random player for elimination
reasonIndex = rand() % 5; //select a random reason for it
}
while ((team.getPlayers()[votedPlayerIndex].getAge() == 0) || (votedPlayerIndex == votingPlayer) || (team.getPlayers()[votedPlayerIndex].getImmunity() == true));
// selection continues if the selected player has already been eliminated,
//if the selected player is the same as the voting player or if the selected player has immunity from elimination
team.getPlayers()[votingPlayer].setVotes(team.getPlayers()[votingPlayer].getVotes() - 1); //reduce the player's available votes by 1
draft.setVotedPlayer(team.getPlayers()[votedPlayerIndex].getName()); //write the name of the player to be voted in an empty Vote object
draft.setReason(reasons[reasonIndex]); //and the reason too
Voting::votes.push_back(draft); //push the Vote obj. in the vector
}
else
{
votingPlayer++; //ignore and get to the next player
}
}
while (votingPlayer < playerNumber); //vote casting continues until every player has casted a vote
}
Vote.h:
#ifndef VOTE_H_INCLUDED
#define VOTE_H_INCLUDED
#include <string>
#include <iostream>
using namespace std;
class Vote
{
string voted; //name of the player to be eliminated
string reason; //reason for elimination
public:
Vote() { voted = ""; reason = ""; } //constructor without parameters
Vote(string player, string reason) { voted = player; this -> reason = reason;} //constructor with parameters (this one is used)
~Vote() { cout << "Vote object destroyed" << endl; }; //destructor
string getVotedPlayer() { return voted; } //getters
string getReason() { return reason; }
void setVotedPlayer(string player) { voted = player; } //setters
void setReason(string reason) { this -> reason = reason; }
void status() { cout << "Voted player: " << voted << endl << "Reason: " << reason << endl;} //status function
};
#endif // VOTE_H_INCLUDED
The reason is that you have an array with 4 elements (so only indices 0..3 are valid) and you are allowing yourself to index it with the 5 possible values (0..4), where 4 is not a valid index.
Here is the definition of the array:
string reasons[4] = {"Den ta pame kala metaxi mas", "Einai ikanoteros/i apo emena kai ton/ti theoro apeili", "Den exei na prosferei kati stin omada", "Prospathei sinexeia na sampotarei tis prospatheies mas"};
Here is the selection of the index:
reasonIndex = rand() % 5;
Here is the use of that index:
draft.setReason(reasons[reasonIndex]);
That is why you are seeing an error from basic_string::_M_create because you are copying from a value that you have no idea is actually a string.
In the line that sets reasonIndex just change the 5 to a 4.

Connect 4 PVP Function

I can't seem to find something that specifically answers my question. I am looking for a solution to my problem. The connect 4 player versus player seems to just ask the first player to drop then the second player to drop, but the first if statement is no longer true so it continues to ask the second player to drop. I am using eclipse for mac osx although the game is programmed for ASCII character set.
display();
int hold;
int hold2 = 0;
int charsPlaced = 0;
bool gamewon = false;
char player = 15;
string r;
while (!gamewon)
{
if (hold2 != -1)
{
if (player == 15)
{
cout << ax << " what column would you like to drop in?";
player = 178;
}
else
{
cout << bx << " what column would you like to drop in?";
player = 176;
}
}
You need to switch the players' turn after each action. If P1 took an action, you need to update the "turn" so that the next time the code loops it will ask for P2. Then, after you've done the stuff you need to do for P2, you need to update the "turn" so that the next time it loops it will ask for P1 action.
Here's a different approach on your code by using an enum. You can use a bool type variable which is false for P1 and true for P2, or an int that's 1 or 2, but that's a bit harder to understand from the outisde.
// omitted code
enum PlayerTurn { ePlayer1 = 0, ePlayer2 };
// omitted code
PlayerTurn plTurn = ePlayer1;
while (!gamewon)
{
if (pTurn == ePlayer1)
{
cout << ax << " what column would you like to drop in?";
// TODO: stuff to do for Player #1
}
else
{
cout << bx << " what column would you like to drop in?";
// TODO: stuff to do for Player #2
}
// TODO: decide if game has been won, mechanics etc.
// move to the next player without overflowing the 2 possible values (0 and 1)
plTurn = (plTurn + 1) % 2;
}
Then, on your display() function, you can show any ASCII character you wish.

Linking/Integration Issue. I need a direction of where to go?

So I have a 2 games running side by side.
proj2/main.cpp (main that gets run that then can call either game)
proj2/spades/display.cpp
proj2/spades/gameplay.cpp
proj2/spades/otherFiles.cpp
proj2/hearts/display.cpp (this is the same display class as in the spades game with the same functions just sightly altered.)
proj2/hearts/hearts.cpp
proj2/hearts/otherFiles.cpp
What basically happened is I am trying to integrate 2 games, 1 I created and another that uses the same display.cpp and display.h files slightly altered. In order to do this I created 2 seperate namespaces, hearts and spades. Everything I have compiles fine but a few of the .cpp files do not link correctly and I get errors such as the following.
./gamePlay.o: In function `__static_initialization_and_destruction_0(int, int)':
gamePlay.cpp:(.text+0x396): undefined reference to `spades::display::display()'
./gamePlay.o: In function `__tcf_3':
gamePlay.cpp:(.text+0x480): undefined reference to `spades::display::~display()'
./gamePlay.o: In function `spades::gamePlay::storeBid(std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >&)':
gamePlay.cpp:(.text+0x1507): undefined reference to `spades::display::captureInput()'
What am I doing wrong here?
Below are some of the files I am using. Let me know if there are anymore I should add. (Dont want to bloat this post anymore than I have to)
gameplay.cpp
#include <iostream>
#include <sys/ioctl.h>
#include <cstdio>
#include <unistd.h>
#include <locale.h>
#include <ncursesw/ncurses.h>
#include <fstream>
#include "gamePlay.h"
#include <cstdlib>
#include <sstream>
#include <ctime>
namespace spades {
vector <spades::player> players(4);
vector <spades::card> deck(52);
spades::display monitor;
spades::card center[4];
vector <spades::card> gamePlay::getDeck(){return deck;}
vector <spades::player> gamePlay::getplayers(){return players;}
//sorts the cards in the players hand into diamonds, clubs, hearts, spades
void gamePlay::handSort(){
int spades[13];
int hearts[13];
int clubs[13];
int diamonds[13];
int index;
int i;
for(i=0; i<13; i++){ //determines the card number and places them into corresponding indexes
index = (players.at(0).hand.at(i).getCardNum()+11)%13; //cause the cards to be placed based on their number with 2 being index 0 and 1(ace) being index 12
switch(players.at(0).hand.at(i).getSuit())
{
case 1: spades[index] = 1;
break;
case 2: hearts[index] = 1;
break;
case 3: clubs[index] = 1;
break;
case 4: diamonds[index] = 1;
break;
default: mvprintw(3,2,"!!!!!!!we have a problem!!!!!!!!!!");
break;
}
}
i = 0;
while(i<13){ //being placing the ordered cards back into the players hand
int j = 0;
while(j < 13){
if(diamonds[j] == 1){ //if a card has been placed in this index for the diamonds only array
if(j+2 == 14) //if the card is an ace
players.at(0).hand.at(i).setCardNum(1);
else
players.at(0).hand.at(i).setCardNum(j+2); //add 2 to each index to get the card number
players.at(0).hand.at(i).setSuit(4);
i++;
}
j++;
}
j = 0;
while(j < 13){
if(clubs[j] == 1){
if(j+2 == 14)
players.at(0).hand.at(i).setCardNum(1);
else
players.at(0).hand.at(i).setCardNum(j+2);
players.at(0).hand.at(i).setSuit(3);
i++;
}
j++;
}
j = 0;
while(j < 13){
if(hearts[j] == 1){
if(j+2 == 14)
players.at(0).hand.at(i).setCardNum(1);
else
players.at(0).hand.at(i).setCardNum(j+2);
players.at(0).hand.at(i).setSuit(2);
i++;
}
j++;
}
j = 0;
while(j < 13){
if(spades[j] == 1){
if(j+2 == 14)
players.at(0).hand.at(i).setCardNum(1);
else
players.at(0).hand.at(i).setCardNum(j+2);
players.at(0).hand.at(i).setSuit(1);
i++;
}
j++;
}
}
}
//compares the center pile of 4 played cards to determine who wins the trick
int gamePlay::compareCenter(int leadplayer){
int highest = center[leadplayer].getCardNum();
if(center[leadplayer].getCardNum() == 1)
highest = 14;
int suit = center[leadplayer].getSuit();
int player = leadplayer;
for(int i = leadplayer+1; i < leadplayer+4; i++)
{
if(center[i%4].getSuit() == 1)
setSpadesBroken(true);
if((suit != 1) && (center[i%4].getSuit() == 1))
{
player = i%4;
suit = 1;
highest = center[i%4].getCardNum();
}
if(suit == center[i%4].getSuit()){
if(center[i%4].getCardNum() == 1){
player = i % 4;
highest = 14;
}
if(highest < center[i%4].getCardNum())
{
player = i%4;
highest = center[i%4].getCardNum();
}
}
}
players.at(player).setTricksTaken(players.at(player).getTricksTaken()+1); //increments the trick count of the winning player
return player; //return the player who won to determine who goes first next turn
}
//Create the deck of 52 cards by setting the suit and number of each card to a nonzero integer
void gamePlay::createDeck() {
for(int j = 0; j < 52; j++)
{
deck.at(j).setCardNum((j%13)+1);
deck.at(j).setSuit((j/13)+1);
}
random_shuffle(deck.begin(), deck.end());
}
//deal out 13 cards to each player by setting the
void gamePlay::deal(vector <spades::card> &newdeck, vector <spades::player> &newplayers){
for(int i = 0; i<52; i++){
newplayers.at(i/13).addCard(newdeck.at(i));
newdeck.at(i).setSuit(0);
newdeck.at(i).setCardNum(0);
}
}
//determines if the player still has a card of the same suit in their hand as the leading card played
bool gamePlay::containSuit(spades::card lead, spades::player players){
bool suit = false;
for(int i = 0; i < players.getHand().size(); i++){
if(lead.getSuit() == players.getHand().at(i).getSuit())
suit = true;
}
return suit;
}
//determines if the player has only spades cards left in their hand
bool gamePlay::onlySpade(spades::player play){
for(int i = 0; i<play.getHand().size(); i++){
if(play.getHand().at(i).getSuit()!=1)
return false;
}
return true;
}
//determines if the position the player is clicking on the screen actually points to a playable card
//and then returns the position of that card based on the player's hand vector of type <card>
int gamePlay::handCheck(int xevent, int yevent, vector <spades::player> players, int trickStart){
int i = xevent/6;
//first check to find the card on the display
if(i>=0 && i<players.at(0).getHand().size() && yevent>17 && yevent<23 &&
players.at(0).getHand().at(i).getSuit() != 0 &&
players.at(0).getHand().at(i).getCardNum() != 0)
{
spades::card playedCard = players.at(0).getHand().at(i);
//check to see if leading the current round or not and if spades are "broken"
if(trickStart==0 && !getSpadesBroken()){
if(onlySpade(players.at(0)))
return i;
else if(playedCard.getSuit() != 1)
return i;
else
return (-1);
}
if(trickStart == 0 && getSpadesBroken())
return i;
//if not leading, then call the containsuit method to see if your hand contains one of similar suit
if(trickStart > 0 && containSuit(center[trickStart],players.at(0))){
if(playedCard.getSuit()==center[trickStart].getSuit())
return i;
}
if(trickStart > 0 && !containSuit(center[trickStart],players.at(0)))
return i;
else
return (-1);
}
mvprintw(4,3,"invalid card");
return (-1);
}
//draws the cards in the player's hand if it contains a valid card, erase the card otherwise if invalid
void gamePlay::displayHand(){
int offset = 0;
for(int i =0; i<players.at(0).getHand().size(); i++){
if(players.at(0).getHand().at(i).getSuit() != 0)
monitor.displayCard(offset, 17, players.at(0).getHand().at(i).getSuit(), players.at(0).getHand().at(i).getCardNum(), 0);
else
monitor.eraseBox(offset, 17, 6, 5);
offset+=6;
}
}
void gamePlay::displayAdd(){
vector <string> lines;
int count12 = 0;
string line;
ifstream myfile ("advertisement.txt");
if ( myfile.is_open() )
{
while ( ! myfile.eof() )
{
getline (myfile, line);
lines.push_back(line);
count12++;
}
myfile.close();
int random1 = rand() % 6;
monitor.bannerBottom(lines.at(random1));
}
else{
monitor.bannerBottom("Unable to open Advertisement file.");
}
}
//determins the position of a mouse click and sends that to handcheck(), and then sends the card to the center pile array to be scored
void gamePlay::humanPlay(int trickStart){
int xevent, yevent;
for(;;){
mvprintw(3,2,"Please choose a card to play.");
int key = monitor.captureInput();
// if a mouse click occurred
if (key == -1) {
xevent = monitor.getMouseEventX();
yevent = monitor.getMouseEventY();
int handCh = handCheck(xevent, yevent, players, trickStart);
if(handCh != (-1)){ //if the card is valid
spades::card played = players.at(0).getHand().at(handCh);
players.at(0).hand.at(handCh).setCardNum(0);
players.at(0).hand.at(handCh).setSuit(0);
center[0]= played;
monitor.displayCard(39, 12, center[0].getSuit(), center[0].getCardNum(), 0);
displayHand();
//playedCards++; //Update Global Variable---- NEED TO HAVE THIS INITIATED GLOBALLY.
break;
}
else
mvprintw(4,3,"invalid card");
}
}
}
//loops through a computer players hand and checks to see if the random card is playable within the rules of the game
void gamePlay::CPUplay(int trickStart, int CPU){
bool goodCard = false;
spades::card playedCard =players.at(CPU).getHand().at(0);
int i;
for(i = 0; i < players.at(CPU).getHand().size(); i++){
if(players.at(CPU).getHand().at(i).getSuit() != 0 &&
players.at(CPU).getHand().at(i).getCardNum() != 0){
playedCard = players.at(CPU).getHand().at(i);
//check to see if leading or not
if(trickStart==CPU && !getSpadesBroken()){
if(onlySpade(players.at(CPU)))
break;
if(playedCard.getSuit()!=1)
break;
}
if(trickStart == CPU && getSpadesBroken())
break;
//if not leading use contains suit function
if(trickStart != CPU && containSuit(center[trickStart], players.at(CPU)))
if(playedCard.getSuit()==center[trickStart].getSuit())
break;
if(trickStart != CPU && !containSuit(center[trickStart], players.at(CPU)))
break;
}
}
players.at(CPU).hand.at(i).setCardNum(0);
players.at(CPU).hand.at(i).setSuit(0);
center[CPU]= playedCard;
if(CPU==1)
monitor.displayCard(29, 7, center[CPU].getSuit(), center[CPU].getCardNum(), 0);
if(CPU==2)
monitor.displayCard(39, 2, center[CPU].getSuit(), center[CPU].getCardNum(), 0);
if(CPU==3)
monitor.displayCard(49, 7, center[CPU].getSuit(), center[CPU].getCardNum(), 0);
}
//scores each team with the player being teamed with CPU 2 and the other team being CPU 1 and CPU 3
void gamePlay::score(spades::player &play, spades::player &play2){
int trickOver = play.getTricksTaken()-play.getBid(); // Calculate the difference between bid and actually taken.
if(play.getBid() == NULL)
trickOver = 0;
int trickOver2 = play2.getTricksTaken()-play2.getBid(); // Calculate the difference between bid and actually taken.
int totalBid = play.getBid()+play2.getBid();
int totalTrick = trickOver+trickOver2;
//Bidding Double Nil (if gets it 200 points other wise -200 points)
if(play.getDoubleNil()){
if(play.getTricksTaken()==0) //player did get Double Nil successfully
play.setScore(play.getScore()+200); // add 200 points
else
play.setScore(play.getScore()-200);
}
else if(play.getBid()==0){ //Bidding Nil (if gets it 100 points other wise -100 points)
if(play.getTricksTaken()==0) //player did get Nil successfully
play.setScore(play.getScore()+100); //add 100 points
else //player didnt get Nil
play.setScore(play.getScore()-100); //take away 100 points
}
if(totalTrick < 0){ //player bids more than number of tricks won
play.setScore(play.getScore()+(totalBid*(-10))); //decrease score by 10 poitns for every overtrick
}
else if(totalTrick >= 0){ //player bids less then number of tricks won
play.setSandBag(play.getSandBag() + totalTrick); //increase sandbag by 1
play.setScore(play.getScore()+totalTrick+(10*totalBid)); //increase 10 points per trick bid on and 1 point per trick over
}
if(play.getSandBag()>10){ //check for sandbagging
play.setScore(play.getScore()-100);
play.setSandBag(play.getSandBag()-10);
}
play.setBid(NULL); //reset players bid to NULL
play2.setBid(NULL); //reset players bid to NULL
play.setTricksTaken(0);
play2.setTricksTaken(0);
play.setDoubleNil(false); //Player has not yet bid double NILL.
}
//loops infinitely until a mouse click or key input is detected, then sets bid accordingly
void gamePlay::storeBid(stringstream &msg){
int xevent;
int yevent;
for(;;){
mvprintw(3,2,"Click the box bid Double Nil or type out your bid now. \n Use the keys 1-9, a for 10, b for 11, c for 12, and d for 13.");
int key = monitor.captureInput();
monitor.drawBox(2, 5, 3, 2, 0);
xevent = monitor.getMouseEventX();
yevent = monitor.getMouseEventY();
if (key == -1)
if((xevent>=2 && xevent<4)&&(yevent>=5 && yevent <7)){
msg.str("");
msg << "Your bid: double nil";
monitor.bannerTop(msg.str());
players.at(0).setDoubleNil(true);
break;
}
else{
msg.str("");
msg << "Your bid is horrible. Bid again!!!!";
monitor.bannerTop(msg.str());
}
if ((key-48) >= 0 && (key-48) <= 9){
msg.str("");
msg << "Your bid: " << (key-48);
monitor.bannerTop(msg.str());
players.at(0).setBid(key-48);
break;
}
else if(key>=97 && key<=100){
msg.str("");
msg << "Your bid: " << (key-87);
monitor.bannerTop(msg.str());
players.at(0).setBid(key-87);
break;
}
else if(key!=0 && key!=-1){
msg.str("");
msg << "Your bid is horrible. Bid again!!!!";
monitor.bannerTop(msg.str());
}
}
monitor.eraseBox(1, 1, 62, 16);
}
//main function that runs the entire game
void gamePlay::runGame(){
double startTime = clock();
stringstream messageString;
srand(time(NULL));
int count;
int handStart = 0;
int trickStart;
while(players.at(0).getScore()<500 && players.at(1).getScore()<500)
{
createDeck();
deal(deck, players); //deal out 13 cards to each player
handSort(); // sort the human players hand
displayHand();
storeBid(messageString); //asks for bid
//sets the bid randomly between 2-4 for each computer player
players.at(1).setBid(rand()%3+2);
players.at(2).setBid(rand()%3+2);
players.at(3).setBid(rand()%3+2);
//displays the current bid and scores of each team
messageString << " Partner: " << (players.at(2).getBid())
<< " CPU 1: " << players.at(1).getBid()
<< " CPU 3: " << players.at(3).getBid()
<< " Team Score = " << players.at(0).getScore()
<< " Enemy Score = " << players.at(1).getScore();
monitor.bannerTop(messageString.str());
displayAdd();
trickStart = handStart;
count = 0;
setSpadesBroken(false);
while(count<13){ // simulates the different cases where the human player plays 1st, 2nd, 3rd, last
bool success = true;
switch (trickStart)
{
case 0: humanPlay(trickStart);
CPUplay(trickStart,1);
CPUplay(trickStart,2);
CPUplay(trickStart,3);
break;
case 3: CPUplay(trickStart,3);
humanPlay(trickStart);
CPUplay(trickStart,1);
CPUplay(trickStart,2);
break;
case 2: CPUplay(trickStart,2);
CPUplay(trickStart,3);
humanPlay(trickStart);
CPUplay(trickStart,1);
break;
case 1: CPUplay(trickStart,1);
CPUplay(trickStart,2);
CPUplay(trickStart,3);
humanPlay(trickStart);
break;
default: mvprintw(3,2,"!!!!we have a problem!!!!");
success = false;
break;
}
monitor.eraseBox(3, 2, 20, 2);
for(;;){//pause to wait for an acknowledgment mouse click
int key = monitor.captureInput();
monitor.eraseBox(3, 2, 30, 4);
mvprintw(3,2,"click anywhere to continue");
if(key == -1){
break;
}
}
//if no errors appear, display the tricks taken
if(success){
monitor.eraseBox(1, 1, 62, 16);
trickStart = compareCenter(trickStart);
messageString.str("");
messageString << "Your Tricks= " << players.at(0).getTricksTaken()
<< " Partner= " << players.at(2).getTricksTaken()
<< " CPU 1= " << players.at(1).getTricksTaken()
<< " CPU 3= " << players.at(3).getTricksTaken();
displayAdd();
monitor.bannerAboveBottom(messageString.str());
count++;
}
}
//score the round and tally up for each team
for(int n =0; n<2;n++)
score(players.at(n),players.at(n+2));
messageString.str("");
monitor.bannerTop(messageString.str());
messageString << "Your Tricks = " << players.at(0).getTricksTaken()
<< " Partner = " << players.at(2).getTricksTaken()
<< " CPU 1 = " << players.at(1).getTricksTaken()
<< " CPU 3 = " << players.at(3).getTricksTaken();
handStart = (handStart +1) % 4;
}
double endTime = clock();
}
}
gameplay.h
#include "player.h"
#include "display.h"
#ifndef gamePlay_H
#define gamePlay_H
namespace spades {
using namespace std;
class gamePlay{
bool spadesBroken;
public:
vector <spades::card> getDeck();
vector <spades::player>getplayers();
bool getSpadesBroken() {return spadesBroken;}
void setSpadesBroken(bool b){spadesBroken = b;}
int compareCenter(int leadplayer);
void createDeck();
void deal(vector <spades::card> &deck, vector <spades::player> &players);
void handSort();
bool containSuit(spades::card lead, spades::player players);
bool onlySpade(spades::player play);
int handCheck(int xevent, int yevent, vector <spades::player> players, int trickStart);
void displayHand();
void displayAdd();
void humanPlay(int trickStart);
void CPUplay(int trickStart, int CPU);
void score(spades::player &play, spades::player &play2);
void storeBid(stringstream &msg);
void runGame();
};
}
#endif
player.h
#include <iostream> // Stream declarations
#include <vector> //Vectors used to store deck and players hands
#include <string> //String declarations
#include <algorithm> //Shuffle Method
#include "card.h"
#ifndef PLAYER_H
#define PLAYER_H
namespace spades {
using namespace std;
class player {
int score; //total score
int bid; //bid for that round
int tricksTaken; //score for thast round
int sandBag; //the number of points you win, more than what you bid, every 10th bag = -100
bool doubleNil;
//vector <card> hand;
public:
player();
vector <card> hand;
int getSandBag(){return sandBag;}
bool getDoubleNil() {return doubleNil;}
int getScore() {return score;}
int getBid() {return bid;}
int getTricksTaken() {return tricksTaken;}
vector<card> getHand() {return hand;}
void setSandBag(int i) {sandBag = i;}
void setBid(int i) {bid = i;}
void setTricksTaken(int i) {tricksTaken=i;}
void setScore(int i) {score = i;}
void setDoubleNil(bool i) {doubleNil = i;}
//add card to end of vector
void addCard(card b);
void removeCard(card a);
};
}
#endif
player.cpp
#include <iostream> // Stream declarations
#include <vector> //Vectors used to store deck and players hands
#include <string> //String declarations
#include <algorithm> //Shuffle Method
#include <sys/ioctl.h>
#include <cstdio>
#include <unistd.h>
#include <locale.h>
#include <ncursesw/ncurses.h>
#include "player.h"
namespace spades {
using namespace std;
player::player() {
score =0; //total score
bid = NULL; //bid for that round
tricksTaken = 0; //score for thast round
sandBag = 0; //the number of points you win, more than what you bid, every 10th bag = -100
doubleNil = false;
for(int i=0; i<13; i++)
hand.push_back(card());
}
void player::addCard(spades::card b){
for (int i=0; i<hand.size(); i++){
//compare card being played to the ones in your hand to search and determine which one to erase
if((hand.at(i).getCardNum() == 0) &&
(hand.at(i).getSuit() == 0))
{
hand.at(i).setCardNum(b.getCardNum());
hand.at(i).setSuit(b.getSuit());
return;
}
}
}
void player::removeCard(spades::card a) {
for (int i=0; i<hand.size(); i++){
//compare card being played to the ones in your hand to search and determine which one to erase
if((hand.at(i).getCardNum() == a.getCardNum()) &&
(hand.at(i).getSuit() == a.getSuit()))
{
hand.at(i).setCardNum(0);
hand.at(i).setSuit(0);
return;
}
}
}
}
What does your link line look like? It looks like when you're linking, you're missing spades.o?
If that's not it, use the nm command to see what symbols spades.o is providing - it's always possible
you've typo'd a namespace name or something:
nm -C spades.o | grep 'display::.*display'
(The -C option should put nm into C++/demangled mode - if it doesn't for your nm, add a "c++filt" or "dem" step to the pipe chain before grep).

Confusion using threads and thread techniques

There's a construction zone. 100m long for cars going East/West....10m across for pedestrians crossing N/S. Here are the rules that must be followed:
neither car nor pedestrians should wait if the intersection is empty;
cars cannot go in the opposite directions simultaneously on the one-lane section;
a pedestrian cannot cross the street while there is a car in the one-lane section, but
multiple pedestrians can cross the street at the same time;
a car may enter the one lane section if there is a car there going in the same direction, however, a car is not allowed to pass another car;
a car does not wait for more than two cars going in the opposite direction;
a pedestrian has to yield to cars BUT a pedestrian should not wait for more than two cars (in either direction).
The example file being used is as follows: (Each row is a separate entity. E means "car going east" and W is west. P is for pedestrians. The first column is the number of seconds after the previous entity arrived at which now the new entity is arriving. The third column is the speed (meters per second):
Example being used:
0 E1 10
1 P1 1
4 E2 15
5 W1 10
Currently my code is printing out E1 enters.... (next line) E1 exits.... This is repeated on and on. I'm pretty confused on using threads and the techniques included so at this moment I'm stuck. What do I need to change to get this to print out the correct order at which the entities should be arriving and leaving the construction zone? All help is appreciated.
#include <iostream>
#include <vector>
#include <fstream>
#include <chrono>
#include <thread>
#include <random>
#include <ctime>
#include <mutex>
#include <string>
#include <condition_variable>
using namespace std;
class Traffic{
public:
void set_time(int a) {prevArrival = a;}
void set_name(string a) {name = a;}
void set_speed(int a) {carSpeed = a;}
int get_time() {return prevArrival;}
string get_name() {return name;}
int get_speed() {return carSpeed;}
private:
int prevArrival;
string name;
int carSpeed;
};
condition_variable_any cE, cW, ped;
mutex mtx;
int east=0; //number of cars traveling East currently in the zone
int west=0; //...traveling West...
int peds=0; //# of pedestrians crossing the street
void sleep(int secs);
void carWest(int time, string name, int speed);
void carEast(int time, string name, int speed);
void pedestrian(int time, string name, int speed);
int main(void){
srand(time(NULL));
ifstream ifs;
ofstream ofs;
string info, title, temp;
int i=0, e=0, w=0, p=0, time, speed;
Traffic crossers[50];
vector <thread> eastCars, westCars, pedestrians;
ifs.open("traffic.txt");
while (!ifs.eof()){
ifs >> time; crossers[i].set_time(time);
ifs >> title; crossers[i].set_name(title);
temp = crossers[i].get_name();
if(temp[0] == 'E' || temp[0] == 'e') {e++;}
else if(temp[0] == 'W' || temp[0] == 'w') {w++;}
else {p++;}
ifs >> speed; crossers[i].set_speed(speed);
i++;
}
ifs.close();
for (int i=0; i < e; i++) eastCars.push_back(thread(carEast, crossers[i].get_time(), crossers[i].get_name(), crossers[i].get_speed())); //creating threads
for (int i=0; i < p; i++) pedestrians.push_back(thread(pedestrian, crossers[i].get_time(), crossers[i].get_name(), crossers[i].get_speed()));
for (int i=0; i < w; i++) westCars.push_back(thread(carWest, crossers[i].get_time(), crossers[i].get_name(), crossers[i].get_speed()));
for (thread& t: eastCars) t.join(); // waiting for eastCars, westCars, and pedestrians to finish
for (thread& t: pedestrians) t.join();
for (thread& t: westCars) t.join();
}
void pedestrian(int time, string name, int speed) {
while(true){
if(name[0] == 'P' || name[0] == 'p'){
if(time == 0 || (east == 0 && west == 0 && peds == 0))
mtx.lock();
cout << name << " entering construction" << endl;
while(peds>0 || west>0 || east>0)
ped.wait(mtx);
peds++;
mtx.unlock();
sleep(10/speed);
cout << name << " exiting construction" << endl;
mtx.lock();
peds--;
ped.notify_one();
cE.notify_all();
cW.notify_all();
mtx.unlock();
}
}
}
void carWest(int time, string name, int speed) {
while(true){
if(name[0] == 'W' || name[0] == 'w'){
if(time == 0 || (east == 0 && west == 0 && peds == 0))
mtx.lock();
cout << name << " entering construction" << endl;
while(peds>0 || west>0 || east>0)
cW.wait(mtx);
west++;
mtx.unlock();
sleep(100/speed);
cout << name << " exiting construction" << endl;
mtx.lock();
west--;
cW.notify_one();
ped.notify_all();
cE.notify_all();
mtx.unlock();
}
}
}
void carEast(int time, string name, int speed) {
while(true){
if(name[0] == 'E' || name[0] == 'e'){
if(time == 0 || (east == 0 && west == 0 && peds == 0))
mtx.lock();
cout << name << " entering construction" << endl;
while(peds>0 || west>0 || east>0)
cE.wait(mtx);
east++;
mtx.unlock();
sleep(100/speed);
cout << name << " exiting construction" << endl;
mtx.lock();
east--;
cE.notify_one();
cW.notify_all();
ped.notify_all();
mtx.unlock();
}
}
}
void sleep(int secs){
this_thread::sleep_for(chrono::milliseconds(rand()%secs*1000));
}
Your problem is here:
for (int i=0; i < e; i++) eastCars.push_back(thread(carEast, crossers[i].get_time(), crossers[i].get_name(), crossers[i].get_speed())); //creating threads
for (int i=0; i < p; i++) pedestrians.push_back(thread(pedestrian, crossers[i].get_time(), crossers[i].get_name(), crossers[i].get_speed()));
for (int i=0; i < w; i++) westCars.push_back(thread(carWest, crossers[i].get_time(), crossers[i].get_name(), crossers[i].get_speed()));
In your small data file, you've got 2 east cars, 1 west car, and one pedestrian. So e will be 2, and p and w will be 1. crosser[0] is an east car
Now, look at those push_back loops. You're adding crossers[0] to all lists! Thus your first (and only) westCar is really an east car. But your carWest refuses to do any work except on west cars, so it does no work.
You probably want to keep completely separate lists, rather than putting everyone into a single crossers list. Either that or you can loop once over your crossers list, and examine the name to see what list/thread it goes in.