• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
kaktusas2598

Problems with vector.push_back()

18 posts in this topic

Hello everybody, Yesterday I started to program Black Jack game in console and I have problems with vectpr.push_back(), I use it to add cards from deck to players hand, for what I use CPlayer::PDraw(CDeck d) function, here it is:

void PDraw( CDeck d)
	{	
		cards.push_back(d.getDeck()[cardCounter]);//error, deck deletes somehow after doing one command
		cardCounter++;
	}

The problem is, when I use puch back(), my deck what I pass into function somehow is changed and becomes empty, I think it has to do something with my Copy and Assignment constructors of CDeck class, here is my CDeck class:

//Class representing Deck of Cards
class CDeck
{
public:
	CDeck(){
		pDeck= new SCard[CARD_NUMBER];
		for(int i = 0; i < CARD_NUMBER; i ++)
		{
			//Assign ID to card and its suit and value
			pDeck[i].id = i;
			identifyCard(&pDeck[i]);			
		}
	}
	~CDeck(){
		delete[] pDeck;
	}
	CDeck(const CDeck &d) { operator=(d); }//error here?
	const CDeck &operator=(const CDeck &d) {//still mistake
		for(int i = 0; i < CARD_NUMBER; i++)
		{
			pDeck[i].id = d.pDeck[i].id;
			pDeck[i].type = d.pDeck[i].type;
			pDeck[i].num = d.pDeck[i].num;
			pDeck[i].val = d.pDeck[i].val;
		}
    return d;
	}
	void shuffleDeck()
	{
		//Shuffles Deck, but maybe more suitable with vector and rand()
		std::random_shuffle(pDeck, pDeck + 52);		
	}
	void identifyCard(SCard* c)
	{
		c->type = suits[c->id/13];
		c->val = value[c->id%13];
		c->num = nums[c->id%13];
	}

	SCard* getDeck(){return pDeck;}
private:
	SCard* pDeck;
};

Here is SCard structure:

//Structure representing one card
typedef struct
{
	//Card ID convertible to its value and suit
	int id;
	//Card Value from Sce to King
	string val;
	//Card suit, Hearts etc.
	string type;
	//Cars numerical value with ace being 11 
	int num;
}SCard;

ANd lastly, my CPlayer class:
 

//Class representing main Player
class CPlayer
{
public:
	CPlayer()
	{
		bet = 0;
		balance = START_MONEY;
		counter = 0;
		//party begins
		isPlaying = true;
		//first move is banks
		isActive = false;
	}
	//Player actions funcs
	void PStay()
	{
		isActive = false;
	}
	void PDraw( CDeck d)
	{	
		cards.push_back(d.getDeck()[cardCounter]);//error, deck deletes somehow after doing one command
		cardCounter++;
	}
	void PDouble(CDeck d)
	{
		PDraw(d);
		bet*=2;
	}
	void PMove(CDeck d)
	{
		int choise;
		cout << "Choose move what you like: \n1.Stay.\n2.Draw\n3.Double.\n";
		cin >> choise;
		if(choise == 1) PStay();
		if(choise == 2) PDraw(d);
		if(choise == 3) PDouble(d);
	}
	void PInfo()
	{
		cout << "Balance: " << balance << endl;
		cout << "Bet: " << bet << endl;
		cout << "Cards in your hand:" << endl;
		vector<SCard>::iterator iter;
		for(iter = cards.begin(); iter != cards.end(); ++iter)
		{
			cout << (*iter).val << " of " << (*iter).type << endl;
		}
		cout << "Value: " << PSum() << endl;; 
	}
	void PBet()
	{
		bool isBetMade = false;
		while(!isBetMade)
		{
			cout << "Enter the bet between 10 to "<< balance << ": ";
			cin >> bet;
			if(bet < 10 || bet > balance)
				cout << "\nYou can't bet this sum. Type Again\n";			
			else
				isBetMade = true;
		}
		balance -= bet;
	}
	int PSum()
	{
		int numOfAces = 0; //nuimber of aces in hand 
		vector<SCard>::iterator iter;
		for(iter = cards.begin(); iter != cards.end(); ++iter)
		{
			if((*iter).val == "Ace") numOfAces++;
			counter += (*iter).num;			
			
		}
		if(counter > BLACK_JACK)
		{
			for(iter = cards.begin(); iter != cards.end(); ++iter)
			{
				if((*iter).val == "Ace") 
				counter -= 10;// +1 and -11
				if(counter <= BLACK_JACK)
					break;
			
			}
		}
		return counter;
	}
	
	bool isPlaying;//player currently playing

	bool isActive; // is players move
private:
	int balance;
	int bet;
	//stores current points that player has
	int counter;	
	//stores current cards in hand
	vector<SCard> cards;
};

I regard every possible answer to this problem. When I run program and step to line where I push card into my vector representing cards in player hands it throws unhandled exception (Unhandled exception at 0x779615de in Black Jack.exe: 0xC0000005: Access violation writing location 0x76d833aa.). To be more precise it comes to constructor of CDeck and then breaks.

2

Share this post


Link to post
Share on other sites

[tt]void PDraw(CDeck d)[/tt] makes a copy of the deck because you are passing by value rather than by reference.

 

void PDraw(CDeck &d) passing by reference

Edited by hikrea
1

Share this post


Link to post
Share on other sites
If you decide not to fix your copy constructor you should consider disabling it. For example, declaring it private and removing the definition or, if you have access to a C++11 compiler, declaring it as = delete.
2

Share this post


Link to post
Share on other sites

Thank you, I removed my copy constructor and passed CDeck as reference. Now it works and im nearly finished my game smile.png

Edited by kaktusas2598
0

Share this post


Link to post
Share on other sites
What exactly do you mean by "removing"? Removed as per SiCrane's suggestions or just removed it from your code?

If you do not supply one explicitly the compiler will generate one which might have similar problems depending on the situation.
0

Share this post


Link to post
Share on other sites

What exactly do you mean by "removing"? Removed as per SiCrane's suggestions or just removed it from your code?

If you do not supply one explicitly the compiler will generate one which might have similar problems depending on the situation.

I just removed it from my code and compiled generated constructors works just fine for me. One more question. Do anybody know how use random_shuffle() which I am using to shuffle my deck to shuffle deck diferrently every time, similar like using srand() with rand(). Cause now it shuffles the deck same way every time I run the game, so I think I need some way to seed some random number based by time every time I use random_shuffle(). Thank you.

0

Share this post


Link to post
Share on other sites

What exactly do you mean by "removing"? Removed as per SiCrane's suggestions or just removed it from your code?

If you do not supply one explicitly the compiler will generate one which might have similar problems depending on the situation.

I just removed it from my code and compiled generated constructors works just fine for me.

But as BitMaster said, the compiler generated copy constructor is as incorrect as the copy constructor you originally had. It doesn't work. Your class simply isn't set up for handling the ownership of the pointer, and neither the compiler generated copy constructor nor your original copy constructor is doing the right job. And by the way, this applies to the copy assignment operator as well.

 

The point is to completely disable copying by making the copy constructor and assignment operators private to ensure that you cannot copy the objects. Or, implement proper copy operators to ensure that the ownership of the pointer is handled correctly.

 

One more question. Do anybody know how use random_shuffle() which I am using to shuffle my deck to shuffle deck diferrently every time, similar like using srand() with rand(). Cause now it shuffles the deck same way every time I run the game, so I think I need some way to seed some random number based by time every time I use random_shuffle(). Thank you.

Seed the random number generator with something that is not pre-defined, such as time.

srand(time(NULL));
0

Share this post


Link to post
Share on other sites

kaktusas2598, on 28 Mar 2013 - 13:09, said:

One more question. Do anybody know how use random_shuffle() which I am using to shuffle my deck to shuffle deck diferrently every time, similar like using srand() with rand(). Cause now it shuffles the deck same way every time I run the game, so I think I need some way to seed some random number based by time every time I use random_shuffle(). Thank you.

Seed the random number generator with something that is not pre-defined, such as time.

srand(time(NULL));

 

But I am using random_shuffle(). not rand(), does srand() also works with random_shuffle()? :o

0

Share this post


Link to post
Share on other sites

kaktusas2598, on 28 Mar 2013 - 13:09, said:

One more question. Do anybody know how use random_shuffle() which I am using to shuffle my deck to shuffle deck diferrently every time, similar like using srand() with rand(). Cause now it shuffles the deck same way every time I run the game, so I think I need some way to seed some random number based by time every time I use random_shuffle(). Thank you.

Seed the random number generator with something that is not pre-defined, such as time.

srand(time(NULL));

 

But I am using random_shuffle(). not rand(), does srand() also works with random_shuffle()? ohmy.png

Sorry, I was thinking randomness and seeding and wasn't exactly thinking about what I was actually answering. The random generator used by the two-parameter variant of std::random_shuffle is in fact implementation defined, but probably uses rand. If it does, then srand will seed std::random_shuffle.

 

However, you may want to use the variant with the third parameter instead, which lets you specify the random number generator yourself. I believe you can pass rand as the third parameter to make sure that it does, in fact, use rand for random numbers.

0

Share this post


Link to post
Share on other sites
rand() isn't a valid function for the third parameter of std::random_shuffle(). If you pass it a function, the function has to take one argument n, and return a value from 0 to n - 1. rand() doesn't take any arguments.
2

Share this post


Link to post
Share on other sites

I have read on internet, that random_shuffle really was inplemented using rand(), so srand() works! Thank you, fellow developers, for all your help! smile.png

Edited by kaktusas2598
0

Share this post


Link to post
Share on other sites
It would be more accurate to say "is usually implemented using rand()". The C++ standard doesn't require standard library implementations to use rand() under the hood for the two argument version of the random_shuffle() function. I would be cautious about trusting an internet source that said this was definitely the case (unless it was referring to your particular compiler/standard library implementation).
0

Share this post


Link to post
Share on other sites
I just checked a late draft of the C++11 standard, and SiCrane is correct. This is unfortunate, and it leaves us with two options: Either avoid using the two-argument version of random_shuffle (since the standard doesn't give you any tools to seed the source of randomness) or live our lives ignoring this oddity in the standard, and trusting that compiler writers are sensible people. If a compiler doesn't use rand as the source of randomness, I will happily stop using that compiler.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0