Python Forum
how to compare two cards games?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to compare two cards games?
#1
COMPARING CARD GAMES

The cards have a value of (1-13) and a suit (a, b, c, d).
so that the deck of cards consists of 52 cards.

1) first of all i created the deck:

def card():
    
    value = [1,2,3,4,5,6,7,8,9,10,11,12,13]
    suit = ["a", "b", "c", "d"]
    
    deck= []
    
    for i in value:
        for j in suit:
            deck.append
    return deck

card()
2) then I would compare the cards by accessing the deck
so ..



def card():
    
    value = [1,2,3,4,5,6,7,8,9,10,11,12,13]
    suit = ["a", "b", "c", "d"]
    
    deck= []
    
    for i in value:
        for j in suit:
            deck.append
    return deck

card()

x = card 



def compare_cards(card1,card2,trump):
  
    if card1 [1] == trump: # [1] second value should be the suite
        if card2 [1] == trump:
            if card1 [0] > card1 [0]:
                print (2)

    elif card1 [1] == trump:
        if card2 [1] != trump:
            print (2)
                
                
    elif card1 [1] != trump:
        if card2 [1] == trump:
            print (0)
            
    #........
        

compare_cards(card1,card2,trump)
i feel lost Sad because i cannot make any progress from this point


notation
COMPARING CARD GAMES

i) For this purpose, a function should be created that compares 2 playing cards.

ii) It should be returned whether the first card is the same size (1), smaller (0) or larger (2) than the 2nd card.

a) The function takes three arguments (1st card, 2nd card, trump suit).

b) The coded ratio (0: smaller; 1: equal; 2 larger) of the cards should be returned as the return.

* A trump card: is a card that is bigger than the others. .
Reply
#2
If you print things out as you go, you will be able to see where things are going wrong before it all gets too messy.
To start off with, yourcard ()function is not doing what you think it is. What you want is to put a value (which is an integer element of a list) and a suit (which is a string element of another list) together to represent a card and then add that card to your deck. If you print the deck from your function you will see that this is not what is happening. Try it like this:
def cards():
     
    values= [1,2,3,4,5,6,7,8,9,10,11,12,13]
    suits= ["a", "b", "c", "d"]
     
    deck= []
     
    for i in values:
        for j in suits:
            deck.append (str(i)+j)
    return deck
 
deck = cards()
print (deck) 
Reply
#3
thanks @BashBedlam for the advise, I forgot the append () argument .
But what about the second part (comparing) i still struggle with
Reply
#4
My advice is still the same. Print everything as you go. One thing that you're going to find out is thatcard1 [0]is the same for an ace, a ten, a jack, a queen and a king so you'll need to go about splitting the value from the suite incompare_cards ()a little differently. Keep at it, I know you can do it!
Reply
#5
Just a small point if you are into card games.
Why call the suits a,b,c,d ?
Maybe d for diamonds, h for hearts ...
Easier.

Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#6
Why use strings at all, when Python has enumerations: https://docs.python.org/3/library/enum.html? If you're going to use strings, make your code readable with full words..
Reply
#7
(Nov-25-2021, 06:23 PM)ndc85430 Wrote: Why use strings at all
@ndc85430 One reason for using strings is to be able to userandom.shuffleto shuffle the deck. Using a shuffled list of strings is a very convenient way to imitate a physical deck of cards. A good reason to use abbreviations for the suits is that they will always be the same length which makes it easy to trim them off the end when you want just the value. Of course this is only one way of doing it Wink
from random import shuffle

def cards () :
	values= [1,2,3,4,5,6,7,8,9,10,11,12,13]
	suits= ["H", "C", "D", "S"]
	new_deck= []
	  
	for value in values:
		for suit in suits:
			new_deck.append (str(value)+suit)
	return new_deck

the_deck = cards ()
shuffle (the_deck)
first_card = the_deck [0]

print (f'The suit of the first card is {first_card [-1]}')
print (f'The value of the first card is {int (first_card [:-1])}')
Reply
#8
I think cards should be objects instead of strings. A card has a suit and a rank (value). You can encode this information into a string and decode it each time you want to know the suite or rank, but I think it makes much more sense to keep the information separate and only encode() it when you want to display a string representing the card.

I would make a Card class, but if you aren't ready for classes you could make cards a tuple or a dictionary. Here I use a tuple(rank, suit) to represent a card (a named tuple would be a nice choice too).
import random

def new_deck():
    """Return a new deck of cards"""
    return [(rank, suit) for rank in range(1,14) for suit in ('Clubs', 'Diamonds', 'Hearts', 'Spades')]

def name(card):
    """Return the name of the card"""
    ranks = ['', 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
    return f"{ranks[rank(card)]} of {suit(card)}"

def suit(card):
    """Return the suit of the card"""
    return card[1]

def rank(card):
    """Return the rank of the card"""
    return card[0]

def value(card, trump=None):
    """Return the value of the card.  Any trump card is worth more than any other card."""
    if card[1] == trump:
        return card[0] + 13
    return card[0]

deck = new_deck()
random.shuffle(deck)
print (f"The top card is {name(deck[0])}")
print (f"The suit of the top card is {suit(deck[0])}")
print (f"The rank of the top card is {rank(deck[0])}")
print (f"The value of the top card is {value(deck[0], 'Spades')}")
Output:
The top card is 7 of Spades The suit of the top card is Spades The rank of the top card is 7 The value of the top card is 20
If any trump card is worth more than any non-trump card, an easy way to represent this is add 13 to the value of a trump card.

If you want to make aces high instead of low, just change the rank names in the names() function and modify the rank range in the new_deck() function.
def new_deck():
    """Return a new deck of cards"""
    return [(rank, suit) for rank in range(2, 15) for suit in ('Clubs', 'Diamonds', 'Hearts', 'Spades')]

def name(card):
    """Return the name of the card"""
    ranks = ['', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
    return f"{ranks[rank(card)]} of {suit(card)}"
And when you learn about classes you'll understand why they are soooo much better than lists or tuples or dictionaries for doing this kind of programming.
import random

class Card:
    """A playing card"""
    suit_names = ('Clubs', 'Diamonds', 'Hearts', 'Spades')
    rank_names = ('', '', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace')

    def __init__(self, rank, suit):
        self.rank_value = rank
        self.suit = suit

    def __str__(self):
        """Return a pretty string"""
        return f"{self.rank} of {self.suit}"

    @property
    def rank(self):
        """Return my rank as a str"""
        return self.rank_names[self.rank_value]

    def value(self, trump=None):
        """Return numerical value.  Any trump card has higer value than any non-trump card"""
        if self.suit == trump:
            return self.rank_value + 13
        return self.rank_value

    @classmethod
    def deck(cls, shuffle=False):
        """Return a deck of cards.  Set shuffle=True if you want the deck shuffled"""
        cards = [Card(rank, suit) for rank in range(2, 15) for suit in cls.suit_names]
        if shuffle:
            random.shuffle(cards)
        return cards

for card in Card.deck(True)[:5]:
    print (f"{card}, suit={card.suit}, rank={card.rank}, value={card.value('Spades')}")
Output:
Ace of Hearts, suit=Hearts, rank=Ace, value=14 5 of Spades, suit=Spades, rank=5, value=18 6 of Spades, suit=Spades, rank=6, value=19 3 of Diamonds, suit=Diamonds, rank=3, value=3 8 of Hearts, suit=Hearts, rank=8, value=8
And now the card comparison function is simple.
def compare(a, b, trump):
    a = a.value(trump)
    b = b.value(trump)
    return 0 if a < b else 1 if a == b else 2
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  sorting a deck of cards (objects in a list) itmustbebunnies 1 7,200 Dec-05-2018, 02:44 AM
Last Post: ichabod801
  Using two functions to shuffle a deck of cards bwe587 7 9,208 Feb-15-2017, 08:15 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020