Class Not Declared in Scope - c++

Getting a "throttle not declared in this scope" error when I attempt to compile the main.cpp. I am very new to c++, so bear with me. I have the #include "throttle.h" in the headers for both cpp files, so I am not sure why when i try to create a throttle object is is not declared...
main.cpp file:
#include <stdio.h>
#include "throttle.h"
using namespace std;
int main(int argc, char **argv)
{
throttle throt1(5, 0);
throttle throt2(4, 0);
return 0;
}
throttle.h file:
#ifndef MAIN_SAVITCH_THROTTLE
#define MAIN_SAVITCH_THROTTLE
namespace main_savitch_2A
{
class throttle
{
public:
// CONSTRUCTORS
//throttle( );
//throttle(int size);
throttle(int size = 1, int start = 0); //by adding this default
//constructor the other two
//are not needed
// MODIFICATION MEMBER FUNCTIONS
void shut_off( ) { position = 0; }
void shift(int amount);
// CONSTANT MEMBER FUNCTIONS
double flow( ) const
{
return position / double(top_position);
}
bool is_on( ) const
{
return (position > 0);
}
int get_top_position()const;
int get_position()const;
friend bool operator <(const throttle& throt1, const throttle& throt2);
//postcondtion: returns true if flow of throt1 < flow of throt2.
//return false if flow of throt1 > flow of throt2
private:
int top_position;
int position;
};
}
#endif
throttle.cpp file :
#include <cassert> // Provides assert
#include "throttle.h" // Provides the throttle class definition
using namespace std; // Allows all Standard Library items to be used
namespace main_savitch_2A
{
//throttle::throttle( )
//{ // A simple on-off throttle
//top_position = 1;
//position = 0;
//}
//throttle::throttle(int size)
// Library facilities used: cassert
//{
//assert(size > 0);
//top_position = size;
//position = 0;
//}
throttle::throttle(int size, int start)
{
assert(size > 0);
assert(start = 0);
top_position = size;
position = start;
}
void throttle::shift(int amount)
{
position += amount;
if (position < 0)
position = 0;
else if (position > top_position)
position = top_position;
}
bool operator <(const throttle& throt1, const throttle& throt2)
{
return(throt1.flow() < throt2.flow());
}
int throttle::get_top_position()const
{
return top_position;
}
int throttle::get_position()const
{
return position;
}
}

In your main, it should be main_savitch_2A::throttle throt1(5, 0);.
The same for throt2.
See namespaces for further details.

Related

Error invalid new-expression of abstract class type FancyPlayer cpp

i have this code at main.cpp :
#include <iostream>
#include <limits>
#include <conio.h>
#include "Ghost/SmartGhost/SmartGhost.h"
#include "Player/Player.h"
#include "PlayerInfo/PlayerInfo.h"
#include "GameBoard/GameBoard.h"
#include "ManualPlayer/ManualPlayer.h"
#include <vector>
using namespace std;
class Position {
public:
int x;
int y;
Position();
Position(int xo,int yo) {x=xo; y=yo;} };
class FancyPlayer : public Player
{
private: vector<Position> visited; //vector of visited nodes int size[2]; //width and height of maze Position start; vector <Position> path; //last visited node(backtrack) public:
void init(int width,int height,int x,int y) {
size[0]=width;
size[1]=height;
start.x=x; //starting position
start.y=y; visited.push_back(Position(start.x,start.y)); path.push_back(Position(start.x,start.y)); }
bool isValid(char ** ViewAround,int x,int y) {
return (ViewAround[x][y]!='#' && ViewAround[x][y]!='*'); }
bool isvisited(int x,int y){
bool f=false;
for(int i=0;i<visited.size();i++) {
if (visited[i].x==x && visited[i].y==y)
f=true;
} return f; }
int getMove(char** ViewAround) {
if (isValid(ViewAround,1,2) && !isvisited(start.x-1,start.y))
{
visited.push_back(Position(start.x-1,start.y));
path.push_back(Position(start.x-1,start.y));
start.x--;
return 0; }
else if (isValid(ViewAround,3,2) && !isvisited(start.x+1,start.y))
{
visited.push_back(Position(start.x+1,start.y));
path.push_back(Position(start.x+1,start.y));
start.x++;
return 1; } else if (isValid(ViewAround,2,3) && !isvisited(start.x,start.y+1))
{
visited.push_back(Position(start.x,start.y+1));
path.push_back(Position(start.x,start.y+1));
start.y++;
return 2; } else if (isValid(ViewAround,2,1) && !isvisited(start.x,start.y-1))
{
visited.push_back(Position(start.x,start.y-1));
path.push_back(Position(start.x,start.y-1));
start.y--;
return 3; } else
{
if (path[path.size()-1].x<start.x){
path.pop_back();
start.x++;
return 1;
}
if (path[path.size()-1].x>start.x){
path.pop_back();
start.x--;
return 0;
}
if (path[path.size()-1].y<start.y){
path.pop_back();
start.y++;
return 2; }
if (path[path.size()-1].y>start.y){
path.pop_back();
start.y--;
return 3;
}
}
}
std::string getName() { return std::string("mplampla"); }
std::string getId() { return std::string("cs141065"); }
};
int main() {
std::vector<ObjectInfo *> PlayersVector; //vector with players engaged
PlayersVector.push_back(new PlayerInfo(*new FancyPlayer(), 'A')); //Erase the comments to play with keyboard
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'B')); //Fool Standby player
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'C')); //Fool Standby player
PlayersVector.push_back(new PlayerInfo(*new StupidPlayer(), 'D')); //Fool Standby player
GameBoard *MainGameObject; //Main Game Object
InfoBoard *ptrToInfoBoard = new InfoBoard();
for (int j = 0; j < PlayersVector.size(); ++j) {
ptrToInfoBoard->addPlayer(*static_cast<PlayerInfo *>(PlayersVector[j]));
}
std::ostringstream he;
std::vector<std::string>*ptr = GameBoard::getMapFileNames(DEVCPP_PATH);
for (unsigned int i = 0; i < ptr->size(); ++i) {
he<<DEVCPP_PATH<<ptr->operator[](i);
for (int j = 0; j < EATCH_MAP_PLAY_TIMES; ++j) {
MainGameObject=new GameBoard(true,he.str().c_str(),PlayersVector,EXETASI_MODE,ptrToInfoBoard);
MainGameObject->StartGame();
delete(MainGameObject);
getchar();
}
he.str("");
}
while(1); }
Player.h code :
#ifndef GHOST_PLAYER_H
#define GHOST_PLAYER_H
#include <iostream>
#include <windows.h>
class Player{
private:
public:
Player(){}
virtual std::string getName()=0 ;
virtual std::string getId()=0 ;
virtual int getMove(const char **ViewAround)=0;
virtual void init(int width,int height,int CurrentX,int CurrentY )=0;
};
#endif //GHOST_PLAYER_H
When i am putting at main the
*new FancyPlayer(), 'A')) i am getting an error that telling "[Error] invalid new-expression of abstract class type 'FancyPlayer'" , if i put this line in comment the code works properly...
the stupidplayer code :
StupidPlayer.h :
#ifndef GHOST_STUPIDPLAYER_H
#define GHOST_STUPIDPLAYER_H
#include "../Player/Player.h"
#include "../Move.h"
class StupidPlayer: public Player {
int getMove(const char **ViewAround);
void init(int width,int height,int x,int y);
std::string getName();
std::string getId();
};
#endif //GHOST_STUPIDPLAYER_H
StupidPlayer.cpp :
#include <cstdlib>
#include "StupidPlayer.h"
#include <fstream>
int StupidPlayer::getMove(const char **ViewAround) {
std::ofstream he("inner.txt");
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
he<<ViewAround[i][j];
}
he<<'\n';
}
return STAND;
}
void StupidPlayer::init(int width, int height, int x, int y) {
}
std::string StupidPlayer::getName() {
return std::string("StupidPlayer");
}
std::string StupidPlayer::getId() {
return std::string("cs161119");
}
i cant see any difference between stupidplayer and fancy... what can i do... in order to make fancy works properly... it may be a problem that have 2 classes in use for fancy?

Function does not take 1 arguments when passing this into it

I'm trying to pass an instance of this (the instance in question being the GameEngine class) into my PlayerBrain.run method which takes a GameEngine * const argument corresponding to what this is. I'm curious as to what would cause such an error to be thrown in this case, especially when there are no alternative function definitions for run() or anything like that. PlayerBrain is its own class, not descending from anything. So there's no alternative definitions to run that might cause problems. Here's the relevant code:
All public methods in PlayerBrain.h
#pragma once
#include "GameEngine.h"
#include "Species.h"
#include "Neuron.h"
#include "Genome.h"
#include "GenePool.h"
#include "Gene.h"
#include <sys/stat.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;
class PlayerBrain {
private:
int popSize;
int stalenessThreshold;
int timeoutConstant;
int currentTimeout;
int maxNodes;
int farthestDistance;
bool buttons[6]; // JASON - shoot, left, right, up, down, jump in that order
GenePool p;
bool fileExists(string filename);
bool fitnessAlreadyMeasured();
void nextGenome();
void evaluateCurrent(Genome * g);
void evaluateNetwork(vector<Neuron*> * network, vector<int> inputs);
void loadPool(string filename);
double sigmoid(double sum);
vector<int> getInputs();
Genome templateGenome();
void pressAKey();
void unPressAKey();
vector<INPUT *> oldbuttons;
public:
PlayerBrain();
void intialize();
void run(GameEngine const *);
void close();
};
The actual implementation in its .cpp
void PlayerBrain::run(GameEngine const * g) {
Genome * current = p.getCurrentGenome();
int xPos = 0;
int bossLives = 0;
double fitness;
double timeoutBonus;
unPressAKey();
if ((p.getCurrentFrame() % 5) == 0)
evaluateCurrent(current);
pressAKey();
xPos = g->getXPosAckVar();
bossLives = g->getBossLivesAckVar();
if (xPos > farthestDistance) { farthestDistance = xPos; currentTimeout = timeoutConstant; }
currentTimeout--;
timeoutBonus = p.getCurrentFrame() / 4;
if ((currentTimeout + timeoutBonus) <= 0) {
fitness = (farthestDistance - (p.getCurrentFrame() / 2)) + 2000 * bossLives;
if (fitness == 0) { fitness = -1; }
current->setFitness(fitness);
if (fitness > p.getMaxFitness()) { p.setMaxFitness(fitness); }
p.setCurrentSpecies(0);
p.setCurrentGenome(0);
while (fitnessAlreadyMeasured()) { nextGenome(); }
}
p.setCurrentFrame(p.getCurrentFrame() + 1);
}
The function call in GameEngine.cpp`
while (true)
{
......//irrelevant stuff
if (tickTimeNow > tickTimeTrigger)
{
if (dTimeTrigger > m_PaintTimeTrigger)
{
....
brain->run(this);
....
}
else Sleep(1);
}
else WaitMessage();
}
}
The error I get is as follows:
Error C2660 'PlayerBrain::run': function does not take 1 arguments

How to initialize a constant in a class? [duplicate]

This question already has answers here:
How to initialize const member variable in a class?
(11 answers)
Closed 7 years ago.
So I've looked around and nothing I found has helped me so far.
I have the following header file for my class.
#ifndef CONGERA2_H
#define CONGERA2_H
typedef float Element300;
class Stack300
{
public:
Stack300 ();
Stack300 (const int);
Stack300 (Stack300 &old);
~Stack300();
void push300(const Element300);
Element300 pop300();
void viewTB300();
void viewBT300();
private:
const int MAX_STACK;
Element300 * stackArray;
int top;
};
#endif
And I'm trying to initialize MAX_STACK. If I set it equal to something I get a warning, which would normally be fine but I must transfer this code to Linux afterwards and I can't do that because it says that MAX_STACK is undefined in my three constructors. I've also tried defining it in my class functions file in the first constructor but then I get an error saying that MAX_STACK is not defined in the constructor.
Here is the constructors for my class functions if they are needed.
#include <iostream>
#include "congera2.h"
using namespace std;
Stack300::Stack300 (): MAX_STACK(10)
{
stackArray = new float[3];
for (int i = 0; i < 3; i++)
{
stackArray[i] = '\0';
}
top = -1;
return;
}
Stack300::Stack300 (const int size) : MAX_STACK (10)
{
stackArray = new float[MAX_STACK];
for (int i = 0; i < MAX_STACK; i++)
{
stackArray[i] = '\0';
}
top = -1;
return;
}
Stack300::Stack300 (Stack300 &old) : MAX_STACK (10)
{
top = old.top;
int i = 0;
while (top != old.top)
{
stackArray[i] = old.stackArray[i];
i = i + 1;
top = i;
}
}
Error:
class A
{
public:
const int x=8; // error (c++98/03)
};
Fix 1
class A
{
public:
const int x;
A() : x(8) // ok
{ }
};
Fix 2
class A
{
public:
const static int x;
};
const int A::x=8; // ok

What's RND / seed in c++?

I'm trying to play with some code..keep getting an compile error RND not declared in scope I found a part of the code that defined it if it ran on linux and if defined it on windows thus ignoring Mac users(no biggie, I would ignore them too!). I removed that part of the code and defined it using the linux settings(since I figured my Mac is more closer to linux than windows), but then I get the same error but for seed. The odd thing is those seed errors are at the same spot at the RND error was. So my question is what the heck is RND/Seed? My searches found them specific to VB but not sure if its useful since I'm using C++.
Here's an offensive code snipped(viewers discretion is advised):
mi = (int)(round(RND*(dimc-1)));
Any tips/suggestions would be great. I'm just starting to learn about c++ so I maybe missing something very simple.
Here's the entire code(stole it from here http://cg.iit.bme.hu/~zsolnai/gfx/genetic/ ):
// a fast genetic algorithm for the 0-1 knapsack problem
// by karoly zsolnai - keeroy#cs.bme.hu
// test case: 1000 items, 50 knapsack size
//
// compilation by: g++ genetic.cpp -O3 -ffast-math -fopenmp
#include <math.h>
#include <time.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include <limits.h>
#define RND ((double)rand_r(&seed)/RAND_MAX) // reentrant uniform rnd
using namespace std;
struct chromo {
chromo(int dimc) { items = new bool[dimc]; }
~chromo() { items = NULL; }
void mutate(const int dimc, const int count) {
int mi;
for(int i=0;i<count;i++) {
mi = (int)(round(RND*(dimc-1)));
items[mi] = !items[mi];
}
}
bool* items;
int f;
};
int fitness(bool*& x, const int dimc, const vector<int>& v, const vector<int>& w, const int limit) {
int fit = 0, wsum = 0;
for(int i=0;i<dimc;i++) {
wsum += x[i]*w[i];
fit += x[i]*v[i];
}
if(wsum>limit) fit -= 7*(wsum-limit); // penalty for invalid solutions
return fit;
}
void crossover1p(const chromo& c1, const chromo& c2, const chromo& c3, const int dimc, const int cp) {
for(int i=0;i<dimc;i++) {
if(i<cp) { c3.items[i] = c1.items[i]; }
else { c3.items[i] = c2.items[i]; }
}
}
void crossover1p_b(const chromo &c1, const chromo &c2, const chromo &c3, int dimc, int cp) {
for(int i=0;i<dimc;i++) {
if(i>=cp) { c3.items[i] = c1.items[i]; }
else { c3.items[i] = c2.items[i]; }
}
}
void crossoverrand(const chromo &c1, const chromo &c2, const chromo &c3, const int dimc) {
for(int i=0;i<dimc;i++) {
if(round(RND)) { c3.items[i] = c1.items[i]; }
else { c3.items[i] = c2.items[i]; }
}
}
void crossoverarit(const chromo &c1, const chromo &c2, const chromo &c3, int dimc) {
for(int i=0;i<dimc;i++) {
c3.items[i] = (c1.items[i]^c2.items[i]);
}
}
bool cfit(const chromo &c1,const chromo &c2) { return c1.f > c2.f; }
bool cmpfun(const std::pair<int,double> &r1, const std::pair<int,double> &r2) { return r1.second > r2.second; }
int coin(const double crp) { // a cointoss
if(RND<crp) return 1; // crossover
else return 0; // mutation
}
// initializes the chromosomes with the results of a greedy algorithm
void initpopg(bool**& c, const std::vector<int> &w, const std::vector<int> &v, const int dimw, const int limit, const int pop) {
std::vector<std::pair<int,double> > rvals(dimw);
std::vector<int> index(dimw,0);
for(int i=0;i<dimw;i++) {
rvals.push_back(std::pair<int,double>(std::make_pair(i,(double)v[i]/(double)w[i])));
}
std::sort(rvals.begin(),rvals.end(),cmpfun);
int currentw = 0, k;
for(int i=0;i<dimw;i++) {
k = rvals[i].first;
if(currentw + w[k] <= limit) { // greedy fill
currentw += w[k];
index[k] = 1;
}
}
for(int i=0;i<pop;i++) {
for(int j=0;j<dimw;j++) {
c[i][j] = index[j];
}
}
}
int main() {
printf("\n");
srand(time(NULL));
vector<int> w, v; // items weights and values
int info=0;
FILE *f = fopen("1000_weights.txt","r");
FILE *f2 = fopen("1000_values.txt","r");
while(!feof(f) || !feof(f2) ) {
fscanf(f," %d ",&info);
w.push_back(info);
info=0;
fscanf(f2," %d ",&info);
v.push_back(info);
} // omitted fclose(f1) and fclose(f2) on purpose
const int limit = 50; // knapsack weight limit
const int pop = 250; // chromosome population size
const int gens = INT_MAX; // maximum number of generations
const int disc = (int)(ceil(pop*0.8)); // chromosomes discarded via elitism
const int dimw = w.size();
int best = 0, ind = 0, ind2 = 0; // a few helpers for the main()
int parc = 0; // parent index for crossover
double avg = 0, crp = 0.35; // crossover probability
vector<chromo> ch(pop,chromo(dimw));
bool **c = new bool*[pop];
for(int i=0;i<pop;i++) c[i] = new bool[dimw];
clock_t start = clock();
printf("Initializing population with a greedy algorithm...");
initpopg(c,w,v,dimw,limit,pop);
printf("done!");
for(int i=0;i<pop;i++) {
ch[i].items = c[i];
ch[i].f = fitness(ch[i].items, dimw ,v, w, limit);
}
printf("\n\n");
for(int p=0;p<gens;p++) {
std::sort(ch.begin(), ch.end(), cfit);
#pragma omp parallel for shared(ch)
for(int i=0;i<pop;i++) {
if(i>pop-disc) { // elitism - only processes the discarded chromosomes
if(coin(crp)==1) { // crossover section
ind = parc+round(10*RND); // choosing parents for crossover
ind2 = parc+1+round(10*RND);
// choose a crossover strategy here
crossover1p(ch[ind%pop],ch[ind2%pop],ch[i],dimw,round(RND*(dimw-1)));
// crossoverrand(ch[ind],ch[ind2],ch[i],dimw);
// crossoverarit(ch[0],ch[1],ch[i],dimw);
ch[i].f = fitness(ch[i].items, dimw ,v, w, limit);
parc += 1;
}
else { // mutation section
ch[i].mutate(dimw,1);
ch[i].f = fitness(ch[i].items, dimw ,v, w, limit);
}
}
avg += ch[i].f;
if(ch[i].f>best) best=ch[i].f;
}
parc = 0;
if(p%5==0) {
printf("\n#%d\t",p);
printf("best fitness: %d \t",best);
printf("avg fitness: %f",avg/pop);
if(best == 675) goto end; // psst...don't tell anyone
}
best = avg = 0;
}
end:
printf("\n\n");
clock_t end = clock();
double t = (double)(end-start)/CLOCKS_PER_SEC;
printf("\nCompletion time: %fs.\n",t);
return 0;
}
The problem is you've inexpertly cut apart the code you've got:
#if defined(__linux) || defined(__linux__)
unsigned int seed = time(NULL);
#define RND ((double)rand_r(&seed)/RAND_MAX) // reentrant uniform rnd
#endif
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#define RND ((double)rand()/RAND_MAX) // uniform rnd
#endif
This defines the seed variable based on the current time for Linux systems; perhaps the Windows systems do not need a seed?
In any event, if you include both lines from the if defined (__linux) ... branch, instead of only one line, it should work without trouble on your OS X system.

C++ object member integer has ridiculous value (WTF)

This is for a poker game and I have class PokerTable defined in PokerTable.h
#include <iostream>
using namespace std;
class PokerTable
{
private:
int numPlayers;
int numPlaying;
int dealerPos;
int bigBlind;
int potSize;
int betSize;
bool flop;
bool turn;
bool river;
public:
//constructors
PokerTable();
PokerTable(int,int,int,int,int,bool,bool,bool);
//getters
int getNumPlayers(){return numPlayers;};
int getDealerPos(){return dealerPos;};
int getBigBlind(){return bigBlind;};
int getNumPlaying(){return numPlaying;};
int getPotSize(){return potSize;};
int getBetSize(){return betSize;};
bool getFlop(){return flop;};
bool getTurn(){return turn;};
bool getRiver(){return river;};
//void buttonShow(int);
//setters
void setBetSize(int inBetSize){betSize = inBetSize;};
void setBigBlind(int inBigBlind){bigBlind = inBigBlind;};
void setNumPlaying(int inNumPlaying){numPlaying = inNumPlaying;};
void setPotSize(int inPotSize){potSize = inPotSize;};
void setFlop(bool inFlop){flop = inFlop;};
void setTurn(bool inTurn){turn = inTurn;};
void setRiver(bool inRiver){river = inRiver;};
void setNumPlayers(int inPlayers){numPlayers = inPlayers;};
void setDealerPos(int inDealerPos){dealerPos = inDealerPos;};
};
PokerTable::PokerTable()
{
numPlayers = 9;
numPlaying = 9;
dealerPos = 1;
bigBlind = 20;
flop = false;
turn = false;
river = false;
}
PokerTable::PokerTable(int playerNum, int playingCount, int posDealer, int blindBig,int inPotSize, bool inFlop,bool inTurn,bool inRiver)
{
numPlayers = playerNum;
numPlaying = playingCount;
dealerPos = posDealer;
potSize = inPotSize;
bigBlind = blindBig;
flop = inFlop;
turn = inTurn;
river = inRiver;
}
In my watch list pokerTable.numPlayers has a random value up to 4 million before I even execute this next line of code.
PokerTable aPokerTable(9,9,1,20,30,false,false,false);
and afterwards here is pokerTable in my watch list:
- aPokerTable { numPlayers=2990892 numPlaying=9 dealerPos=9 ...} PokerTable
betSize 30 int
bigBlind 1 int
dealerPos 9 int
flop false bool
numPlayers 2990892 int
numPlaying 9 int
potSize 20 int
river false bool
turn false bool
Can anyone tell me why all the values are not what I declared them to be??!?!!
And how I can fix this?
This is Form1.h
#pragma once
#include "PokerTable.h"
#include "Card.h"
#include <time.h>
#include "PokerPlayer.h"
#include <fstream>
#include <string>
#include <sstream>
//global variables
//TODO make players start from 0
int firstPlayer;
int deck[52];
int nextCard=0;
PokerTable aPokerTable(9,9,1,20,30,false,false,false);
PokerPlayer players[9]; //however many players
ofstream gameLog;
/*
void setTable()
{
aPokerTable.setNumPlayers(9);
aPokerTable.setNumPlaying(9);
aPokerTable.setDealerPos(1);
aPokerTable.setBigBlind(20);
aPokerTable.setPotSize(30);
aPokerTable.setBetSize(20);
aPokerTable.setFlop(false);
aPokerTable.setTurn(false);
aPokerTable.setRiver(false);
}
*/
string convertInt(int number) //convert to string
{
stringstream ss;//create a stringstream
ss << number;//add number to the stream
return ss.str();//return a string with the contents of the stream
}
void createPlayers()
{
// aPokerTable.setNumPlayers(9);
for(int x=0;x<=(aPokerTable.getNumPlayers()-1);x++)
{
players[x] = *(new PokerPlayer(1000,(aPokerTable.getDealerPos())+1,false,0,1));//1000 chips, position i+1, not folded
}
}
void playRound()
{
int action;
for(int playerTurn = firstPlayer; playerTurn <= aPokerTable.getNumPlayers()+firstPlayer; playerTurn++)
{
if(players[playerTurn].getFold() == false)
{
if(aPokerTable.getNumPlaying() == 1)
{
players[playerTurn].setChipStack(players[playerTurn].getChipStack() + aPokerTable.getPotSize()); //player wins pot
}
else //there is more than one person playing
{
action = players[playerTurn].action(); //0 is check/fold, value is call/bet/raise,
if(action > aPokerTable.getBetSize())
{
aPokerTable.setBetSize(action);
aPokerTable.setPotSize(aPokerTable.getPotSize() + action);
playerTurn = playerTurn - aPokerTable.getNumPlayers();
}
else if (action == aPokerTable.getBetSize()) //call
{
aPokerTable.setPotSize(aPokerTable.getPotSize() + action);
}
else //action < aPokerTable.betSize
{
players[playerTurn].setFold(true);
aPokerTable.setNumPlaying(aPokerTable.getNumPlaying()-1); //removes player from playing tally
}
}
}
}
}
void randomDeck()
{
int random_integer;
int tempCard;
//srand((unsigned)time(0));
for(int j=0;j<=51;j++)
{
deck[j] = j;
}
for(int i=51; i>=1; i--)
{
random_integer = rand()%(i); //a random number between 0 and i
tempCard = deck[i];
deck[i] = deck[random_integer]; //put the random card from unshuffled deck into slot i of the deck
deck[random_integer] = tempCard; //put whatever was at slot i into the random slot
}
}
void dealCards()
{
for(int j=1;j<=aPokerTable.getNumPlayers();j++)
{
players[j].setCard1(deck[nextCard]);
nextCard++;
players[j].setCard2(deck[nextCard]);
nextCard++;
}
}
void playPreFlop()
{
aPokerTable.setBetSize(aPokerTable.getBigBlind());
aPokerTable.setFlop(false); //it is before the flop
aPokerTable.setTurn(false);
aPokerTable.setRiver(false);
randomDeck(); //shuffle cards
dealCards();
firstPlayer = (aPokerTable.getDealerPos() + 3)%(aPokerTable.getNumPlayers()); // first player is left of blinds between 0 and numplayers
playRound();
}
void playFlop()
{
aPokerTable.setFlop(true);
firstPlayer = (aPokerTable.getDealerPos())%aPokerTable.getNumPlayers(); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
}
void playTurn()
{
aPokerTable.setTurn(true);
firstPlayer = (aPokerTable.getDealerPos())%aPokerTable.getNumPlayers(); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
}
void playRiver()
{
aPokerTable.setRiver(true);
firstPlayer = (aPokerTable.getDealerPos())%(aPokerTable.getNumPlayers()); // first player is left of dealer between 0 and numplayers
aPokerTable.setBetSize(0);
playRound();
if(aPokerTable.getNumPlaying() >=2)
{
//showDown();
}
}
/*
void showDown()
{
}
*/
This is pokerPlayer.h
using namespace std;
class PokerPlayer
{
private:
int chipStack,position;
bool fold;
int card1,card2;
public:
//constructors
PokerPlayer();
PokerPlayer(int,int,bool,int,int);
//getters
int getChipStack() {return chipStack;}
int getPosition() {return position;}
int getCard1(){return card1;}
int getCard2(){return card2;}
bool getFold(){return fold;}
//setters
void setChipStack(int inChips){chipStack = inChips;}
void setPosition(int inPos){position = inPos;}
void setCard1(int inCard1){card1 = inCard1;}
void setCard2(int inCard2){card2 = inCard2;}
void setFold(bool inFold){fold = inFold;}
int action();
};
PokerPlayer::PokerPlayer()
{
chipStack = 1000;
position = 0;
fold=false;
card1 = 0;
card2 = 1;
}
PokerPlayer::PokerPlayer(int inChipStack,int inPos, bool inFold, int inCard1, int inCard2)
{
chipStack = inChipStack;
position = inPos;
fold = inFold;
card1 = inCard1;
card2 = inCard2;
}
int PokerPlayer::action()
{
return 0;
}
aPokerTable { numPlayers=2990892 numPlaying=9 dealerPos=9 ...}
Note that dealerPos got assigned the value 9, that's wrong as well. If you look closely, you'll see that everything is shifted by 4 bytes.
Two possible reasons. The debugger could have picked the wrong address for aPokerTable, the actual address minus 4. That's unlikely. Or there's a mismatch between the definition of the PokerTable class as seen by pokertable.cpp and the other .cpp files that #include the pokertable.h include file. Where pokertable.cpp saw an extra member before the numPlayers member. Maybe you edited the header and deleted that member but ended up not recompiling pokertable.cpp for some mysterious reason. Build + Rebuild to fix. Do panic a bit if this actually works.
It's because in C++ before the constructor is called, variable uses the value that it already contains in its memory location that is a "random" value
I cannot reconstruct it because i dont have the full code. However, a random value near 4 million sounds like a pointer. When you store or retrieve a member variable maybe you did not de-reference the pointer. Please post the rest of the code so we can check if that's the case.
players[x] = *(new PokerPlayer(...));
That is a memory leak. What you probably want is:
players[x] = PokerPlayer(1000,(aPokerTable.getDealerPos())+1,false,0,1);