I'm trying to create a little ascii game where I can run around kill enemies etc. However I'm new to C++ and I would like to do something if the players location is at a certain point.
Below is a simpler version of the code and a picture of the problem:
#include <iostream>
using namespace std;
struct Game
{
bool bGameOver = false;
int iWidth = 20;
int iHeight = 40;
void Draw() {
if (player.x == 5)
{
cout << "Hello"
}
}
};
struct Player
{
bool bGameOver = false;
int x = 0;
int y = 0;
};
void Setup()
{
}
int main()
{
Game game;
Player player;
while (!game.bGameOver)
{
Setup();
}
}
Picture of the error
The variable player is local in function main, so it's not visible where you tried to use it in Game::Draw.
One solution could be to make player a global variable. You'll need to switch the order of the structs:
struct Player
{
bool bGameOver = false;
int x = 0;
int y = 0;
};
Player player;
struct Game
{
bool bGameOver = false;
int iWidth = 20;
int iHeight = 40;
void Draw() {
if (player.x == 5)
{
cout << "Hello"
}
}
};
But I'd prefer to instead model things so a Game "has a" Player. So make Player a member of the Game:
struct Player
{
bool bGameOver = false;
int x = 0;
int y = 0;
};
struct Game
{
Player player;
bool bGameOver = false;
int iWidth = 20;
int iHeight = 40;
void Draw() {
if (player.x == 5)
{
cout << "Hello"
}
}
};
(Aside: You probably don't want two different values called bGameOver, since keeping them in sync would be extra work. It sounds more like a game property than a player property to me.)
Related
I am working on a google chrome dinosaur chrome clone using an SDL template and I have an issue where the character is not stopping once he hits the floor. My code logic is supposed to work like this, I have a bool called "onFloor" that tells the program when the player and ground come into contact with each other. When onFloor = false the player keeps on falling and when onFloor = true the player stops falling and stays in place. My issue is that when I try to do the reverse of my current falling or gravity code.
These are the parts of my code that I think are the problem
Player.h
#pragma once
#include "GameObject.h"
#include "common.h"
#include "draw.h"
class Player :
public GameObject
{
public:
void start();
void update();
void draw();
//X Setter
void setX(int x) {
this->side = x;
}
//X Getter
int getX() {
return side;
}
//Y Setter
void setY(int y) {
this->fall = y;
}
//Y Getter
int getY() {
return fall;
}
//Height Setter
void setHeight(int h) {
height = h;
}
//Height Getter
int getHeight() {
return height;
}
//Width Setter
void setWidth(int w) {
width = w;
}
//Width Getter
int getWidth() {
return width;
}
//OnFloor Setter
void setOnFloor(bool onFloor) {
onFloor = true;
}
//OnFloor Getter
bool getOnFloor() {
return onFloor;
}
private:
SDL_Texture* texture;
int side;
int fall;
int height;
int width;
int speed;
bool onFloor;
};
GameScene.cpp
#include "GameScene.h"
GameScene::GameScene()
{
// Register and add game objects on constructor
player = new Player();
this->addGameObject(player);
floor = new Floor();
this->addGameObject(floor);
}
GameScene::~GameScene()
{
delete player;
}
void GameScene::start()
{
Scene::start();
// Initialize any scene logic here
}
void GameScene::draw()
{
Scene::draw();
}
void GameScene::update()
{
Scene::update();
floorCollision();
//This is where Gravity strength is located
if (player->getOnFloor() == false) {
player->setY(player->getY() + 2);
}
else {
player->setY(0);
}
}
void GameScene::floorCollision()
{
//Checks for collisions between player and floor
for (int i = 0; i < objects.size(); i++)
{
//Cast to floor
Floor* floor = dynamic_cast<Floor*>(objects[i]);
//Check if the floor was casted
if (floor != NULL)
{
int collision = checkCollision(
player->getX(), player->getY(), player->getWidth(), player->getHeight(),
floor->getX(), floor->getY(), floor->getWidth(), floor->getHeight()
);
if (collision == 1)
{
std::cout << "!" << std::endl;
player->getOnFloor() == true;
break;
}
}
}
}
at first I thought that just changing the false to true would work so I just put this part of the code
player->getOnFloor() == false
into my collision logic but instead of false I make it true once he hits the ground to stop him from falling
void GameScene::floorCollision()
{
//Checks for collisions between player and floor
for (int i = 0; i < objects.size(); i++)
{
//Cast to floor
Floor* floor = dynamic_cast<Floor*>(objects[i]);
//Check if the floor was casted
if (floor != NULL)
{
int collision = checkCollision(
player->getX(), player->getY(), player->getWidth(), player->getHeight(),
floor->getX(), floor->getY(), floor->getWidth(), floor->getHeight()
);
if (collision == 1)
{
std::cout << "!" << std::endl;
//This is what is supposed to make the player stop falling
player->setOnFloor(player->getOnFloor() == true);
break;
}
}
}
}
but the player just falls through the floor
EDIT:
Okay I think I fixed it and the player stops falling when he hits the ground by changing my onFloor setter in my player.h to this
//OnFloor Setter
void setOnFloor(bool) {
onFloor = true;
}
and my GameScene collision logic to this
if (collision == 1)
{
std::cout << "!" << std::endl;
player->setOnFloor(true);
break;
}
New problem now though is that when onFloor = true the player just sticks to the top of the screen with no way to move down or up anymore.
I'm not sure whether this is the only issue but it's one which could be responsible for OPs reported problem:
//OnFloor Setter
void setOnFloor(bool onFloor) {
onFloor = true;
}
The argument onFloor shadows the member variable Player::onFloor.
(This is legal in C++ as the function starts a local scope.)
Thus, true is assigned to the argument onFloor (which is pointless as it's a value parameter and lost after return from function) while the member variable Player::onFloor is not modified at all.
Nevertheless, though the member variable is shadowed by an argument , it's still accessible — either by this->onFloor or by Player::onFloor.
So, a possible fix is:
//OnFloor Setter
void setOnFloor(bool onFloor) {
this->onFloor = onFloor;
}
or
//OnFloor Setter
void setOnFloor() {
onFloor = true;
}
So in my program, I'm using polymorphism, which could also explain some of the issues that I'm having.
This is my pure abstract class:
class Event {
public:
Event();
~Event();
virtual int returnType();
};
Then I have a room class that sets events to a particular room:
class Room {
private:
Event * e;
bool player = false;
bool bEvent = false;
public:
Room();
~Room();
Event * getEvent();
void setEvent(Event *);
bool getPlayer();
void setPlayer(bool);
bool getBoolEvent();
void setBoolEvent(bool);
};
And here are my function definitions:
Event * Room::getEvent() {
return e;
}
void Room::setEvent(Event * n) {
e = n;
}
bool Room::getPlayer() {
return player;
}
void Room::setPlayer(bool p) {
player = p;
}
bool Room::getBoolEvent() {
return bEvent;
}
void Room::setBoolEvent(bool b) {
bEvent = b;
}
Here is my bats class which is a derived class from event: The functions are the same, so here are the function definitions:
int Bats::returnType() {
return 1;
}
So in my program, I am using a 2d vector of Rooms, and then assigning events to these rooms via polymorphism. The problem is that I don't think the changes are persisting, at least with the polymorphism, even when passing by reference.
Here is the function where I am setting the bat event to a certain room in the 2d vector:
vector<vector<Room>> Game::setEvents(vector<vector<Room>> &grid) {
Bats b1;
Event * eb1 = &b1;
//Set player
int r1 = rand()%gridSize;
int r2 = rand()%gridSize;
grid[r1][r2].setPlayer(true);
//Set bats
grid[0][0].setBoolEvent(true);
grid[0][0].setEvent(eb1);
cout << "Function example: " << grid[0][0].getEvent()->returnType() << endl;
return grid;
}
As an output I get Function example: 1;
However, when we move into the main (in this case Game::play()) function, these changes don't hold.
void Game::play() {
srand(time(NULL));
//Create vector
vector<vector<Room>> grid;
//Fill vector
fillGrid(grid);
//Set player and events
grid = setEvents(grid);
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
if (grid[i][j].getBoolEvent() == true) {
cout << i << " " << j << endl;
cout << grid[i][j].getEvent()->returnType() << endl;
}
}
}
}
As an output I get 0 0 and then a seg fault.
Although the boolEvent is still true, for some reason I get a segmentation fault when trying to call returnType(), even though it worked in the setEvents() function. What am I doing wrong with polymorphism?
I'm trying to create a Monopoly game in C++ and I've been messing with object-oriented-programming, the problem happens with the classes "Game" and "Player", I would like to know how to use "Game"'s functions inside "Player" and "Player"'s functions inside "Game", but I've been getting a compiler error saying that the class is not defined.
Switching class positions won't work (obviously) but I tried anyways.
Code (reduced and minimized to the Game and Player classes):
namespace Monopoly {
typedef enum { normal, train, company, incometax, luxurytax, start, chancecard, chestcard, jail } type;
class Game {
private:
bool running = false;
int turn = 1;
int currentPlayerID;
int startingMoney = 1000;
std::vector<Player> players;
public:
// Functions
void createPlayer() {
++currentPlayerID;
Player newPlayer(currentPlayerID, startingMoney);
players.push_back(newPlayer);
++currentPlayerID;
}
void createPlayers(int playerAmount) {
for (int i = 0; i <= playerAmount; ++i) {
createPlayer();
}
}
Player getPlayer(int index) {
Player p = players[index];
return p;
}
};
class Player {
private:
int playerID;
int money;
std::vector<int> propertiesOwned;
void addProperty(int id) {
this->propertiesOwned.push_back(id);
}
public:
// Constructor
Player(int pID, int sMoney) {
this->playerID = pID;
this->money = sMoney;
}
// Functions
Player payMoney(int payAmount, unsigned int destinationID, Game engine) {
this->money -= payAmount;
if (destinationID > 0) {
// Checks if you're paying to a player or bank
bool playerFound = false;
for (int i = 0; i <= engine.getPlayerAmount(); ++i) {
if (engine.getPlayer(i).getID() == destinationID) {
playerFound = true;
break;
}
}
if (playerFound) {
// Player was found
engine.getPlayer(destinationID).giveMoney(payAmount);
return;
}
else {
std::cout << "\nERROR: Invalid player ID at function payMoney\n";
return;
}
}
else {
// You're paying to the bank
}
return;
}
void buyProperty(int id, int price, Game engine) {
payMoney(price, 0, engine);
addProperty(id);
}
void giveMoney(int payMoney) {
this->money += payMoney;
}
// Returns
inline int getMoney() { return this->money; }
inline int getID() { return this->playerID; }
inline auto getProperties(int index) {
auto p = propertiesOwned[index];
return p;
}
inline int getPropertyAmount() {
int amount = std::size(propertiesOwned);
return amount;
}
};
}
I expected the classes to run the other classes function normally, but it seens like that in C++, classes are defined in certain order, and you can only access classes (in a class) declared before the class you're using, feedback and alternatives that fix this would help
You are correct that in C++ declaration order matters, and that is the cause of your errors, however there are a few other issues with the code.
Firstly, you should swap the order that Game and Player are defined. This will make it easier, as Player relies on Game fewer times than Game relies on Player.
Next, add a forward declaration for Game before the definition of Player:
class Game;
This tells the compiler that a class named Game exists and allows you to use it in scenarios where it doesn't need to know the contents (i.e. definition) of the class.
Next, make payMoney and buyProperty accept their engine parameter by reference instead of by value by changing the parameter specifier to Game &engine. This is important for two reasons. First, passing by value can only be done if you have already defined the type, which we have not (we've only declared it). Second, passing by value creates a copy of the object, which in this case means a completely new vector of completely new Player objects, and the changes will not synchronize back to the old object. See here for a better explanation of references.
Next, you need to extract the definition of payMoney to after the definition of Game. The reason is that while the parameter list of payMoney no longer relies on the definition of Game, the code in the function body does (because it calls functions on the engine object). See the end for what this looks like.
This fixes all the problems with declaration/definition order. You also should make payMoney return void as its return value is never provided and never used, pick a consistent type for IDs (either int or unsigned int, not a mix), and add the getPlayerAmount to Game.
Here's what the final code could look like:
namespace Monopoly {
typedef enum { normal, train, company, incometax, luxurytax, start, chancecard, chestcard, jail } type;
class Game;
class Player {
private:
int playerID;
int money;
std::vector<int> propertiesOwned;
void addProperty(int id) {
this->propertiesOwned.push_back(id);
}
public:
// Constructor
Player(int pID, int sMoney) {
this->playerID = pID;
this->money = sMoney;
}
// Functions
void payMoney(int payAmount, int destinationID, Game &engine);
void buyProperty(int id, int price, Game &engine) {
payMoney(price, 0, engine);
addProperty(id);
}
void giveMoney(int payMoney) {
this->money += payMoney;
}
// Returns
inline int getMoney() { return this->money; }
inline int getID() { return this->playerID; }
inline auto getProperties(int index) {
auto p = propertiesOwned[index];
return p;
}
inline int getPropertyAmount() {
int amount = std::size(propertiesOwned);
return amount;
}
};
class Game {
private:
bool running = false;
int turn = 1;
int currentPlayerID;
int startingMoney = 1000;
std::vector<Player> players;
public:
// Functions
void createPlayer() {
++currentPlayerID;
Player newPlayer(currentPlayerID, startingMoney);
players.push_back(newPlayer);
++currentPlayerID;
}
void createPlayers(int playerAmount) {
for (int i = 0; i <= playerAmount; ++i) {
createPlayer();
}
}
Player getPlayer(int index) {
Player p = players[index];
return p;
}
int getPlayerAmount() {
int amount = players.size();
return amount;
}
};
void Player::payMoney(int payAmount, int destinationID, Game &engine) {
this->money -= payAmount;
if (destinationID > 0) {
// Checks if you're paying to a player or bank
bool playerFound = false;
for (int i = 0; i <= engine.getPlayerAmount(); ++i) {
if (engine.getPlayer(i).getID() == destinationID) {
playerFound = true;
break;
}
}
if (playerFound) {
// Player was found
engine.getPlayer(destinationID).giveMoney(payAmount);
return;
}
else {
std::cout << "\nERROR: Invalid player ID at function payMoney\n";
return;
}
}
else {
// You're paying to the bank
}
return;
}
}
Side note: it's technically better C++ to use size_t instead of int for variables storing the size of vectors, as that is what the size functions return (and it's an unsigned integer type whereas int is signed), but that's not especially important.
I am a beginner in threading with C++. Tried to create a thread t1 inside the class, but I want it not to be initialized. For this I did:
In the class variable, thread *t1 as if were to declare the class variable without initializing it.
Then from the constructor, I did:
t1 = new Thread(functionName);
But, there's some error that I didn't get. I previously had simple working experience with threading in Java.
Will this strategy cause an interlocking problem, assuming the solution exists to the way I want to implement it. (if I want to access the same variable without modifying it). Code goes like this:
class game:protected gameObjects
{
thread *t1;
///-------------------- Variables-------------------///
char keyPressed = NULL;
/// structure for holding player information.
struct player
{
int x, y0, y1,color;
};
player player1, player2;
/// for ball
int ballX, ballY, ballColor, ballBorderColor;
///--------------------------------------------------///
void initializeData()
{
ballX = 42;
ballY = 130;
player1.color = LIGHTCYAN;
player1.x = 30;
player1.y0 = 100;
player1.y1 = 200;
player2.color = LIGHTMAGENTA;
player2.x = 600;
player2.y0 = 100;
player2.y1 = 200;
/// Basic setUp For Game and Game Screen
ballBorderColor = RED;
ballColor = GREEN;
}
void updateScoreBoard()
{
/// whole score board border.
drawRect(20,10,620,50,RED);
/// left score board
drawRect(21,11,321,49,CYAN);
setfillstyle(SOLID_FILL,CYAN);
floodfill(30,40,CYAN);
setbkcolor(CYAN);
setcolor(LIGHTGREEN);
outtextxy(35,20,"Score:0");
///right score board.
drawRect(323,11,619,49,LIGHTMAGENTA);
setfillstyle(SOLID_FILL,LIGHTMAGENTA);
floodfill(330,40,LIGHTMAGENTA);
setbkcolor(LIGHTMAGENTA);
setcolor(LIGHTGREEN);
outtextxy(350,20,"Score:1");
}
void ballPosition()
{
setfillstyle(SOLID_FILL,ballColor);
drawCircle(ballX,ballY,10,ballBorderColor); ///ball for game
floodfill(ballX,ballY,ballBorderColor);
}
void playerBatPosition()
{
drawLine(player1.x,player1.y0,player1.x,player1.y1,player1.color);
drawLine(player2.x,player2.y0,player2.x,player2.y1,player2.color);
}
void setBackground()
{
setfillstyle(SOLID_FILL,background);
drawRect(0,0,getmaxx(),getmaxy(),RED);
floodfill(getmaxx()/2,getmaxy()/2,RED);
drawRect(20,60,620,470,WHITE); ///white line.
}
void updateScreenActivity()
{
playerBatPosition();
}
void startPlaying()
{
do
{
keyPressed = _getch();
if(keyPressed == 'w')
{
if(player1.y0 > 60)
{
drawLine(player1.x,player1.y0,player1.x,player1.y1,background);
player1.y0-=5;
player1.y1-=5;
}
}
else if(keyPressed == 's')
{
if(player1.y1 < 470)
{
drawLine(player1.x,player1.y0,player1.x,player1.y1,background);
player1.y0+=5;
player1.y1+=5;
}
}
if(keyPressed == 't')
{
if(player2.y0 > 60)
{
drawLine(player2.x,player2.y0,player2.x,player2.y1,background);
player2.y0-=5;
player2.y1-=5;
}
}
else if(keyPressed == 'g')
{
if(player2.y1 < 470)
{
drawLine(player2.x,player2.y0,player2.x,player2.y1,background);
player2.y0+=5;
player2.y1+=5;
}
}
updateScreenActivity();
}
while(keyPressed != 'q');
}
///-------------------Threading call --------------///
void startBallMovement(){
cout<<"Hello world"<<endl;
}
///-----------------------------------------------///
public:
game()
{
cleardevice();
initializeData();
setBackground();
updateScoreBoard();
playerBatPosition();
ballPosition();
startPlaying();
t1 = new thread(startBallMovement);
}
};
What I want to do is create a movement of a circle in different paths from the thread. I might sometimes need to access the variables from the thread to simulate the movement in different directions as per the user's strategy.
Error:
Your class implementation looks a bit lousy. But try something like this.
class game
{
private: thread* t;
public:
game()
{
t = new thread([this]() {startBallMovement();} );
}
~game()
{
if(t != nullptr)
{
t->join();
delete t;
}
}
void startBallMovement()
{
}
};
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);