Jump to content
  • Advertisement
Sign in to follow this  
DrPepperCorn

Programming a deck of cards

This topic is 3712 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I posted a while back looking for scenarios i could make up teaching 11-16 programming and ive thought about the concept of programming a deck of cards. All im after is some thoughts, as many different methods as you can if possible, im not looking for a full solution as i want to get concepts over first. This will be an end task problem which will cover classes, inheritance and types. So what im looking at is A program that randomly selects cards and can be used for a game of blackjack (ignore any betting and concentrate on making a good card and deck class) Some of the things i would like them to consider are: Card values - ints (or possibly an enum) Card suits - enum an array this be a vector or fixed array and some method of keeping track of what cards have been drawn from the deck(Class) i have an idea of how i would do it but im looking to drag some different methods so i can select the easiest to get across to some 11 year olds. Most of this will be given to them and they add little bits for the kids but the 16 byear olds may be given a little more to do. With the ability of the group i beleive they can get most of this done so far we have been using c++ to create a welcome USER program and log some dtails about a person and a pythagoras and percentage calculator. in these lessons we have covered data types, functions, if statements and a switch statement. Most of this os going quite well but as expected for some people its a bit heavy going for them but they arent giving up and i wont let them down. Anyone care to suggest some methods for the card game above? Many thanks, i am documenting all of this so if gamedev would like a set of beginner - moderate starter programming resources i will gladly han d them over with teacher to student plans and activities. there has been quite a lot of work done already on this and its looking really good for a beginner programmer.

Share this post


Link to post
Share on other sites
Advertisement
DrPepperCorn,

One possible solution would be using a stack for your deck of cars. One thing they would have to consider is populating the stack at the beginning with the cards in a random order. One nice thing is using the deck "stack" of cars after its created would be fairly easy with pop's ect.

Another option would be using an array to hold the deck of the cards. Each method is possible to use. I was trying to put myself in the mindset in that classroom and was trying to think what stuff I might have had learned by that point! Good luck with your lessons!

Share this post


Link to post
Share on other sites
Well if the deck of cards needs to be shuffled then using a vector of card classes and swapping elements randomly would allow you to perform a shuffle. Of course if you didn't need to shuffle the cards then a stack would work well for just drawing cards off the top ;) .

The card class could contain the value of the card and the suite of the card in integer format (just makes it easier to work with later then say using strings). You could use enumeration also for making it easy to say compare the current card to see if it is an Ace or not. Also if you wanted you could overwrite the output operator and print the value and suite of the card to the screen.

If I were making something like this then I would have a Deck class with my STL vector of Card classes. My Deck class would have my shuffle method, and a method for drawing a card from the vector. If you really wanted to get fancy then you could define a method in the deck class that returns a deck based on how many cards you wanted to draw from the current deck.

like Deck* myHand=myDeck->DrawCards(STARTING_CARDS);

Where as a single card could be: Card* curCard=myDeck->DrawCard();

Using a Deck class would support the idea of using an Abstract Data Type (ADT) where the underlying data structure is not important and we just focus on what methods we expose to the user (IE the methods for shuffling and drawing cards)

Good luck :) .

Share this post


Link to post
Share on other sites
I wrote a poker console project a few years back. The idea was to determine the probablility of winning a hand of Texas Hold 'Em against a number of opponents given a fixed initial hand of two cards and disregarding bluffing (basically I wanted to improve my real-life game and I thought it was an interesting project) I created a card collection class that had methods to shuffle, sort cards by suit or value, deal or receive a card to or from another collection (in which case ownership of the individual card objects would be transferred.) That way the full deck can use the same collection object as a single hand.

I forget now what internal structure I used for it's collection (probably something silly - I've learned a bit since then!) Mostly I recall running into some logical difficulties in determining winning hands efficiently. Aces counting high or low depending on the circumstance is one particular gotcha.

Share this post


Link to post
Share on other sites
Good resposes, all appreciated. Trying to avoid at every turn pointers as the examples ive used so far are very trivial its hard to sort of show the advatages of pointers and of course explaining that they point to memory. Im trying to give real tangable examples, not something they have to see as a programmer would. they can get their head around initialisation: "we make a variable and we have to state what this is, int myNumber = 10;" they can see that and get their head around it, telling them that 10 is really 0014f9b9 . . and this variable points to its address . . . hmmm

at the moment id sooner them be able to visualise the code . .(make a couple of sloppy errors . .dont worry ive already drummed into their heads NEVER to use a goto) and bebable to comment it and do a post mortem on the code they have written or added.

this gives me a chance to pick up errors and misconceptions and develop better ways of understanding it. So far ive been looking at them to see a card as a datatype and creating a class like this

class cCard
{

private: //see lesson 8: private, protected and public for this keyword

int nCard; // a class variable which we will need to asssign a card
string rgCardValues[]; //Something like {"2", "Three" ... "J", "Queen"}
string rgCardSuit[]; // Something like { "D", "Spades", "Hts", "CL"}

//Use what you feel is best. I would use a format like "AC", "5D", "KD" etc

public: //see lesson 8: private, protected and public for this keyword
cCard(); //constructor

//TASK //////////////////////////////////////////////////////////////////////
//Add destructor below and in comments explain what this is.
//(view lesson 7c for contruction and destruction of classes and why we do it)
/////////////////////////////////////////////////////////////////////////////

string getSuit() // a (class) function to return the suit
string getValue() // a (class) function to return the value of the card

};

thanks for the replys so far, its all good. this is really a great community

Share this post


Link to post
Share on other sites
My card object had an enum for the suit and an int for the value. I initially defined a collection of all 52 cards just by basically iterating over them and populating a 'deck' which could then be passed around to individual card hands or the cards on the table (that was another initial difficulty with my project - I don't know if you know the rules of Hold 'Em, but basically some cards are shared between everyone's hands, so it's not just a case of dealing everyone individual cards, some need to be in all hands.)

What are the string arrays you are using? I'd steer clear of using strings for your internal card/hand data, it's easier to write further code (hand scoring etc.) based on numeric types i.e. ints. If you need to write card details to console, or use a string representation for any other purpose, you could write a cCard::ToString() method that returns a human-readable representation.

Reading your original post, I see this is intended as a tutorial for 11 year olds. In that case (not meaning to patronise 11 year olds here!) I'd advise sticking to the most basic representation you can. If they can grasp the program flow required to implement an enum for suits, an int for value, and include those in a class, then I'd say they're getting along pretty well compared to what my school taught me at that age!

Share this post


Link to post
Share on other sites
indeed (last poster) ive taken a lot from the accelerated c++ book and the way they launch into it rather than go the learn c++ in 21 days/c++ for idiots approach. At the moment even the kids who are having difficulty get this string thing and a large part of the scenario is designing putting these elements into an array and using ( myarray; ) to sort them. Here i can introduce them to fixed and variable arrays. In many ways ive taken it too far and it is a little advanced, one of the kids is really good at this as his dad is a php professional developer and is coming at me with templates (very good kid only 13) so i have to kep the pressure on him . . may have to start giving hima primer in direct x so we can actually see some cards.

Thanks for the replys this is really good and like i said if all this needs to be compiled as a resource i will do as so far we have 90% understanding and development rate with the 11yr olds and almost 100% 13+, statistically what im doing is working and they are getting some programs running and they can see the effort programmers have to put in to get mario to jump, hit a coin get a score and generally do something what looks really easy.

Thanks again guys

Share this post


Link to post
Share on other sites
well what I did is an array.

cards[312];

why 312? because 6 decks of 52.

Then I initialized it all to 1. from there I just randomly selected a index.

card_chosen=rand()%312;

and checked to make sure its value was 1. if not i checked again. While not really a shuffle it did the trick.

Share this post


Link to post
Share on other sites
To shuffle a deck of cards, you can use std::random_shuffle. Example with integer numbers:

#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

const int n_cards = 52;

int main()
{
// seed random number generator once
srand(time(0));

std::vector<int> deck;
deck.reserve(n_cards);

// fill deck
for (int i = 0; i < n_cards; ++i)
deck.push_back(i);

// shuffle deck
std::random_shuffle(deck.begin(), deck.end());

// output
std::copy(deck.begin(), deck.end(), std::ostream_iterator<int>(std::cout, " "));
}

Share this post


Link to post
Share on other sites
A simple implementation, in C++, would be:

namespace cards
{

// The cards

struct card
{
enum suit_type { Clubs, Hearts, Diamonds, Spades};

const suit_type suit;
const unsigned value;

card(suit_type suit, unsigned value) : suit(suit), value(value)
{ assert (value > 0 && value < 15); }
};

bool operator == (const card& c1, const card &c2)
{ return c1.suit == c2.suit && c1.value == c2.value; }

bool operator != (const card &c1, const card &c2)
{ return ! (c1 == c2); }

bool operator < (const card &c1, const card &c2)
{ return c1.suit < c2.suit || c1.suit == c2.suit && c1.value < c2.value); }

// The decks

typedef std::vector<card> deck;

inline deck fresh_deck()
{
deck d;

d.reserve(52);
for (int val = 1; val <= 14; ++val)
{
d.push_back(card(Clubs, val));
d.push_back(card(Hearts, val));
d.push_back(card(Diamonds, val));
d.push_back(card(Spades, val));
}
}

inline void shuffle(deck &d)
{
std::random_shuffle(d.begin(), d.end());
}

inline void deal(deck &d, std::vector<deck> &hands, unsigned cards)
{
unsigned total = hands.size() * cards;
assert (total <= d.size());

for (int i = 0; i < total; ++i)
{
hands[i % hands.size()].push_back(d.back());
d.pop_back();
}
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!