Let's create a continuing thread to program Crazy 8's from scratch for learning purposes!

DECK/CARD IDEA'S

My simple starting suggestion:

deck = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC',
        '2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD',
        '2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH',
        '2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS',]

I've started writing a Cribbage game in python here is my deck coding so far it should help this project. The dictionary has the card names as keys and their point values(for cribbage) as the values. My next step with my game was to make a list with the keys from the dictionary so the cards can be shuffled. This leave the dictionary alone but uses the key name for easy reference to the card point values. Then I was thing of making hands a tuple of list( 'hands(hand0[], hand1[], ...) for each player. With this structure, How would I go about sorting each hand in ascending value ie
hand should sort as...
or
I've been looking at sort(key=something) or the cmp=something; however, nothing makes sense to me.
Well, here is my code for the card deck. I will repost my code when I add the other functions for the deck[] and hands(hand0[], hand1[], ...).

#!/usr/bin/python
# -*- coding: utf-8 -*-

class CribDeck:
    from random import shuffle
    deck = {}

    def makeDeck(self):
        s = " "
        for char in "23456789TJQKA":
            for suit in "SHCD": #♠♥♣♦
                if char.isdigit():
                    self.deck[char+s+suit] = int(char)
                elif char == "A":
                    self.deck[char+s+suit] = 1
                else:
                    self.deck[char+s+suit] = 10

    #def makeDeck
    def getDeck(self):
        d = self.deck
        return d
    #def getDeck
    def printDeck(self):
        print self.deck
    #def printDeck

PS
If ppl are interested, we could start a new tread similar to this for cribbage.

Looking to move a little slower for beginner's sake (i.e., explaining every new class, object, list, variable, introduced). As far as other ways to program the deck/cards, I forsee having an added value(s) to cards beside rank & suit for playing purposes (i.e. 8's are wild). Perhaps I am wrong but let's continue discussing the deck/cards and their relationship to the game.

BTW I'm working with python 2.7

One way to make a deck,that is ok to understand.
@askrabal remember that import statement shall never be inside a class or function.
Import statement shall alway be on top.

rank = 'A23456789TJQK'
suit = 'CDHS'

deck = []
for r in list(rank):
    for s in list(suit):
        card = r + s
        deck.append(card)

print deck

One with list comprehension.

deck = [rank + suit for rank in "A23456789TJQK" for suit in "CDHS"]
print deck

Shuffle deck and deal some card.

>>> from random import shuffle
>>> #Shuffle deck
>>> shuffle(deck)
>>> #Deal out 5 card
>>> [deck.pop() for k in range(5)]
['7S', 'TC', 'TD', '8C', 'QS']

I used values separately and coding function, in object oriented approach it could be __str__ method for printing out concise form of hand.

Perfect! Any idea whether or not we'll need a third value to define playing them?

Could u show that tony?

How about dealing the cards individually?

See my code snippet of poker hands I posted.

Let's create a continuing thread to program Crazy 8's from scratch for learning purposes!

DECK/CARD IDEA'S

My simple starting suggestion:

deck = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC',
        '2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD',
        '2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH',
        '2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS',]

Start by downloading one of the existing packages, like http://duo.tuxfamily.org/lang/en/about and look at the code. If you don't understand something, then post the question and code. I don't think there are many who volunteer their time here, who want to spend it coding a solution for you when many already exist.

commented: good link +1

Trying to develop a style while learning other styles. No one needs to continually post. If someone should stumble upon this with some input, so be it.

Ideas for what needs to be defined for game play, with snippets of an idea??

How would you sort the hand so it would be easy to read?

Perhaps giving a "suit_value" (for playability) and a "rank_value" (for playablity & order) with eights having the highest rank_value, recognizing it as the wild card?! Nah, maybe a suit_value is unnecessary. Could just use suit for playability. Perhaps just "value", who's order is determined by rank.

Hmmm, where can we put the code to build on and link to?

The Beginnings:

import random

# variables
rank = 'A23456789TJQK'
suit = 'CDHS'
deck = []
self = []
p2 = []
p3 = []
p4 = []

for r in list(rank):
    for s in list(suit):
        card = r + s
        deck.append(card)

random.shuffle(deck)

print deck

##Deal out 5 card
#[deck.pop() for k in range(5)]

def deal():
    """this function deals the cards individually to each hand"""
    self.append(deck.pop(0))    #pop(0) grabs the first card/item in list
    p2.append(deck.pop(0))      #pop() would grab last...I believe
    p3.append(deck.pop(0))
    p4.append(deck.pop(0))
    self.append(deck.pop(0))
    p2.append(deck.pop(0))
    p3.append(deck.pop(0))
    p4.append(deck.pop(0))
    self.append(deck.pop(0))
    p2.append(deck.pop(0))
    p3.append(deck.pop(0))
    p4.append(deck.pop(0))
    self.append(deck.pop(0))
    p2.append(deck.pop(0))
    p3.append(deck.pop(0))
    p4.append(deck.pop(0))
    self.append(deck.pop(0))
    p2.append(deck.pop(0))
    p3.append(deck.pop(0))
    p4.append(deck.pop(0))

deal()

print
print 'YOUR HAND'
print self
print
print 'REMAINING CARDS'
print deck

Similar part adapted from my above mentioned poker code is:

import random
from itertools import islice

valuecode={14:'A',13:'K',12:'Q',11:'J'}
for i in range(2,11):
    valuecode[i] = str(i)
    
def dealer(deck):
    while deck:
        yield deck.pop()

def gethands(dealer):
    while dealer:
        cards = sorted(islice(dealer,5))
        if len(cards) == 5:
            yield cards
        else:
            break

def cardcode(value,suit):
    return suit[0].upper()+valuecode[value]

def codedhand(cards):
   return ', '.join(cardcode(*card) for card in cards)

def newdeck():
    ## cards with ace as more high value 14 == 12 + 2
    deck = [(value+2,suit)
              for suit in ('heart','diamonds','spade','club')
              for value in range(13)]
    random.shuffle(deck)
    return deck

if __name__== '__main__':
    deck = newdeck()
    cards_generator = dealer(deck)
    # generate the full five card hands
    for hand in gethands(cards_generator):
        print '\nYour sorted by value hand is %s.' % codedhand(hand)
        print 'Cards in suit order are: %s.' %  codedhand(sorted(hand, key=lambda x: x[1]))
        
    raw_input('Your deck finished. Push Enter to quit.')

Use next(dealer(deck)) to generate only one card.

>>> print deck[-1]
(7, 'club')
>>> print cardcode(*next(dealer(deck)))
C7
>>> print deck[-1]
(5, 'diamonds')

doffing81, theres no need to hardcode the 5 deals.

def deal():
    """this function deals the cards individually to each hand"""
    for i in range(5):
        self.append(deck.pop(0))    #pop(0) grabs the first card/item in list
        p2.append(deck.pop(0))      #pop() would grab last...I believe
        p3.append(deck.pop(0))
        p4.append(deck.pop(0))

Cheers and Happy coding

commented: Perfect +1

Thx beat, exactly what I'm looking for!

We have any idea's for game play code? As far as AI, I'll post a basic strategy to code.

@doffing81 i will give som advice about code design.
This can be very important as code grow,to much code in global space can be a real pain.
when you work with function code is local to that function(you have to call it)
Learn to work with function first,of course class is also an option later.
But is important to get comfortable with function.

So some code to show you what i mean.
Look how this work,and a make some documation(called dok_string)

from random import shuffle

def make_deck():
    '''This function retur a sorted deck'''
    rank = 'A23456789TJQK'
    suit = 'CDHS'
    deck = []
    for r in list(rank):
        for s in list(suit):
            card = r + s
            deck.append(card)
    return deck

def shuffle_deck(deck, number=None):
    '''Shuffle deck and return card number(5) return five card'''
    shuffle(deck)
    return [deck.pop() for k in range(number)]

def foo():
    '''Not finsih yet'''
    pass

def main():
    #Here we put it all together
    #Make a note that no code is in global space,this make it eaiser to add remove code
    #We can just add remove function.
    deck = make_deck()
    five_card = shuffle_deck(deck, 5)
    print 'A test give player five card: %s' % five_card
    #-->A test give player five card: ['AH', '5S', '9H', '2S', '9S']

if __name__ == '__main__':
    main()

Totally understand, thx. Shall I keep the players global? Also, I do not understand how this works -
if __name__ == '__main__':
main()
or the purpose of -
def foo():

if __name__ == '__main__':
     main()

The if separates part which is run when importing the module from the part which is run when file is run directly.

def foo():
   pass

Is place holding code reminding not yet implemented feature. Idea of using functions is that you do not code all functionality at once but implement parts and combine them together in another function. When you start coding first parts, you have not coded yet the last parts.

Ok, how do we play a card and perhaps make a rule to who plays first?

This should be interesting. I have a game that allows you to play cards according to the top card of the pile. What I can't get is an exception for the eights'. The code is horrid and rough. What can I say, first attempt at programming, going step by little knowledgable step. Although I know of classes, I guess I am unclear how to apply them to this game. Perhaps we could dissect and clean this up?!?!

import random

# variables
self = []
p2 = []
p3 = []
p4 = []
z = []
w = []
rank = 'A23456789TJQK'
suit = 'CDHS'
deck = []
pile = []
for r in list(rank):
    for s in list(suit):
        card = r + s
        deck.append(card)

##Deal out 5 card
#[deck.pop() for k in range(5)]

def deal():
    '''deals cards to 4 players'''
    for i in range(5):
        self.append(deck.pop(0))    #pop(0) grabs the first card/item in list
        p2.append(deck.pop(0))      
        p3.append(deck.pop(0))
        p4.append(deck.pop(0))

def accept_card(x):
    '''plays x to pile'''
    if x == self[0]: pile.append(self.pop(0))
    elif x == self[1]: pile.append(self.pop(1))
    elif x == self[2]: pile.append(self.pop(2))
    elif x == self[3]: pile.append(self.pop(3))
    elif x == self[4]: pile.append(self.pop(4))
    elif x == self[5]: pile.append(self.pop(5))
    elif x == self[6]: pile.append(self.pop(6))
    elif x == self[7]: pile.append(self.pop(7))
    elif x == self[8]: pile.append(self.pop(8))
    elif x == self[9]: pile.append(self.pop(9))     # 39 enough for now lol
    elif x == self[10]: pile.append(self.pop(10))   # help me clean this
    elif x == self[11]: pile.append(self.pop(11))
    elif x == self[12]: pile.append(self.pop(12))
    elif x == self[13]: pile.append(self.pop(13))
    elif x == self[14]: pile.append(self.pop(14))
    elif x == self[15]: pile.append(self.pop(15))
    elif x == self[16]: pile.append(self.pop(16))
    elif x == self[17]: pile.append(self.pop(17))
    elif x == self[18]: pile.append(self.pop(18))
    elif x == self[19]: pile.append(self.pop(19))
    elif x == self[20]: pile.append(self.pop(20))
    elif x == self[21]: pile.append(self.pop(21))
    elif x == self[22]: pile.append(self.pop(22))
    elif x == self[23]: pile.append(self.pop(23))
    elif x == self[24]: pile.append(self.pop(24))
    elif x == self[25]: pile.append(self.pop(25))
    elif x == self[26]: pile.append(self.pop(26))
    elif x == self[27]: pile.append(self.pop(27))
    elif x == self[28]: pile.append(self.pop(28))
    elif x == self[29]: pile.append(self.pop(29))
    elif x == self[30]: pile.append(self.pop(30))
    elif x == self[31]: pile.append(self.pop(31))
    elif x == self[32]: pile.append(self.pop(32))
    elif x == self[33]: pile.append(self.pop(33))
    elif x == self[34]: pile.append(self.pop(34))
    elif x == self[35]: pile.append(self.pop(35))
    elif x == self[36]: pile.append(self.pop(36))
    elif x == self[37]: pile.append(self.pop(37))
    elif x == self[38]: pile.append(self.pop(38))
    elif x == self[39]: pile.append(self.pop(39))
    print pile
    print self
    print 'Last card played'
    print pile[-1]
        
def deny_card():
    '''denies unmatching cards and asks to play again'''
    print 'You cannot play that card!'
    play_card()
    
def draw():
    '''draws a card from the deck'''
    self.append(deck.pop(0))

def check_card(x):
    '''Checks to see if the card can be played or to draw'''
    if len(x) != 2:                                     # hit enter to draw
        draw()                                          # otherwise check x
    else:
        check_rank(x)

def check_rank(x):
    '''checks rank elif suit''
    if x[0] == '8':
        y = raw_input('What suit would you like?')
# here is where I've been trying to make an exception/rule for the 8's
        accept_card(x)
    elif x[0] != pile[-1][0]:
        check_suit(x)
    elif x[0] == pile[-1][0]:
        accept_card(x)
        
def check_suit(x):
    '''suit elif deny the card'''
    if x[1] != pile[-1][1]:
        deny_card()
    elif x[1] == pile[-1][1]:
        accept_card(x)

def play_card():
    if len(deck) == 0:
        print 'NO MORE CARDS'                   # rule in case deck runs out
        while len(pile) >= 2:
            deck.append(pile.pop(0))
            random.shuffle(deck)
        print 'pile', pile, 'Cards shuffled!'
    elif len(deck) >= 1:
        print 'YOUR HAND'
        print self
        x = raw_input("What card would you like to play? ")  #x = card to play
        check_card(x)
        if len(self) == 0:                      # determines the end
            print 'GAME OVER - Player 1 WINS!!!'

def start_game():
    pile.append(deck.pop(0))        # takes the starting card from the deck
    print "PILE"
    print pile
    play_card()
    
def game():
    random.shuffle(deck)
    print 'SHUFFLED DECK'
    print deck
    deal()
    start_game()

game()
    
#what should u do if the first card on the pile is an eight?!?!

Guess some of those comments screw up the function. Although I dealt to 4 players I was just playing cards from my hand the whole time to see where I could get before adding players into the mix.

Line 94 is missing third ' Do not use at least the self for variable name, it is very confusing for others who are used to use that name for special purpose in object oriented programming.

I must say that still I have no idea of what the program is supposed to do, except maybe accept_card is doing strange version of pop(self.index(x)) or something like that.

It works if you throw in the last '. Try it out xP. As for self, I figured as much when I started to learn more about objects. Will turn to p1 if I don't re-write this whole thing. Anyway, the proogram starts on it's own. May have to hit enter once. The cards, which probably shouldn't be global, are shuffled, printed just to see that they are, dealt to 4 players, then game starts. A card is taken from the deck and placed on the pile. The player can only play a card from his hand onto the pile if it matches either suit or rank. Otherwise they hit enter, when prompted to play a card, to draw a card. For a start to making a rule/exception for the 8's I have it simply at least recognize that an played 8 has been played and ask what suit would you like, only I can't actually get it to do this. Really this is the only thing I couldn't get it to do, however horrid this really is lol. Should I clean this up, organize it maybe a little, and be more comment specific? Anyway, once all the cards are gone from the player's (self) hand, the game is over! That's what this is

Gonna work on some classes and redo! I will make a player class, card class, and deck class for starters. I'll post for advice.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.