Trying coding 5 card poker

Tell us what’s happening:

I’m trying to do a Python’s poker program, but I’m having an issue with changing cards(probably due to suits and suits_name). My idea was prining the cards with suits symbol, but changing them by typing suits name(as 2 of hearts, 5 of clubs…). There’s a way to give cards the suits value (hearts) but print them with symbol only?

And one more question: I’m a beginner with programming and I’m trying to coding this by myself. Do you think it’s an acceptable code? (It’s obviously not finished)

Your code so far

import random, time


suits = ["♥️", "♦️", "♣️", "♠"]
hearts, diamonds, clubs, spades = suits
suits_name = (hearts, diamonds, clubs, spades)
value = (10, 11)
A = value[0]
J = value[1]
Q = value[1]
K = value[1]
number = [A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K]




def start():
    play = input("You wanna play? ")
    if play.lower() in ("yes", "sure", "yeah"):
        unique_cards = set()
        while len(unique_cards) < 5:
            unique_cards.add(f"{random.choice(number)}{random.choice(suits_name)}")
        cards = list(unique_cards)
        print("Your cards are:", ", ".join(cards) )
        time.sleep(4)
        while True:
            change_cards = input("Want to change cards? ")
            if change_cards.lower() == "yes":
                quantity = input("Which cards? ")
                if quantity.lower() == "none":
                    print("chepalle")
                    break
                elif quantity.lower() in cards:
                    cards.remove(quantity.lower())
                    new_cards = [f"{random.choice(number)}{random.choice(suits_name)}" for _ in range(len(quantity.split(',')))]
                    cards.extend(new_cards)
                    print("Your new cards are: ", ", ".join(cards))
                    break
                elif quantity.lower() == "all":
                    all_choice = [f"{random.choice(number)}{random.choice(suits_name)}" for _ in range(5)]
                    print("Your new cards are: ", ", ".join(all_choice))
                    break
                else:
                    print("Invalid cards selected")
            elif change_cards.lower() == "no":    
                break
        # CONTROLLARE CARTE CON IPOTETICO AVVERSARIO/AVVERSARI
        print("ngul")
    else:
        exit()
    

start()

Cool project :+1:

I would keep the suit names as strings in the code, and just use the symbols when printing the output for the user to see. I would keep the suits list as:

suits = ["Hearts", "Diamonds"...etc]

internally in the code. You could have a dictionary mapping those to symbols

suit_dict = {"Hearts": "♥️", "Diamonds": "♦️" ... etc}

and only use that when you print. Maybe cards is a collection of small lists

[[5,"Hearts"],[Q,"Diamonds"], ... etc]

and when you print them something like

print(cards[0][0], "of", suit_dict[cards[0][1]])

in a loop so it prints the value, and then looks up the suitable symbol in the dictionary. This way you can look up if the user wants to change “5 of hearts” you can check it against your list:

[[5,"Hearts"],[Q,"Diamonds"], ... etc]

Something like that, I hope I made sense.

Basically: Keep the suit to symbol mapping in a dictionary and use it when you print the cards. Keep text for everything else to easily parse user input.

1 Like

I tried that, but it says str object is not callable. Can you please help me? I would assign multiple values to the cards (suits and suits names) so the terminal prints the symbols but i can change cards typing their values in name, but I don’t know if it’s possible.
Anyway thank you

Can you show me the code that generated this error?

I’ve already deleted it, because I’ve copied this code on a new file and made some little changes, but this evening or tomorrow I’ll try another time and if it shows the same error, I’ll reply to you

If what I said above makes sense, you can try implementing it.

I’m happy to help with any questions or errors.

I’ve tried different solutions, but nothing…
Tried with your idea of dict, reassigning values, but nothing. Tried also this:

suits = ["♥️", "♦️", "♣️", "♠"]
suits_name = hearts, diamonds, clubs, spades = suits
hearts="♥️"
diamonds="♦️"
clubs="♣️"
spades="♠"

also tried that

suits_name = hearts, diamonds, clubs, spades = suits = ["♥️", "♦️", "♣️", "♠"]

I don’t know if these attempts are stupid or not, but this code still doesn’t work and I don’t know how to proceed, I want to code the checking hands part but firstly want to finish this.

Can you share your code with the attempt using a dictionary? I really think that’s the way to go here. This makes it easy to map back and forth between the symbols and the words.

You could even use two lists:

suits = ["♥️", "♦️", "♣️", "♠"]
suits_name = ["hearts", "diamonds", "clubs", "spades"]

If the user types “3 of spades” to switch you lookup “spades” in the suits_name list and then lookup the same index in the suits list.

I could also see the user typing in the number of the card. For example:

Your cards are: 2♠, 5♣️, 11♥️, 11♦️, 11♣️
Want to change cards? yes
Which cards? 1,3

To refer to 2♠ and 11♥️ then you can just remove those in the cards. Easier for the player to type too

In the end, I’ve modified a little bit using classes, but I’m still having issues with how changing cards.

    import random, time
    from random import shuffle

    from enum import Enum

    class CardSuits(Enum):
        Hearts = "Hearts"
        Diamonds = "Diamonds"
        Clubs = "Clubs"
        Spades = "Spades"

    class CardValues(Enum):
        Two = 2
        Three = 3
        Four = 4
        Five = 5
        Six = 6
        Seven = 7
        Eight = 8
        Nine = 9
        Ten = 10
        Jack = "J"
        Queen = "Q"
        King = "K"
        Ace = "A"


    class Card:

        _symbols = {"Hearts": "♥️", "Diamonds": "♦️", "Clubs": "♣️", "Spades": "♠"}

        def __init__(self, suit: CardSuits, value: CardValues) -> None:
            self.suit = suit
            self.value = value

        def __str__(self) -> str:
            return f"{self.value.value}{self._symbols[self.suit.name]}"

        def __repr__(self) -> str:
            return f"{self.value.value}{self._symbols[self.suit.name]}"


    def start():
        play = input("You wanna play? ")
        if play.lower() in ("yes", "sure", "yeah"):
            all_cards = [Card(suits, value) for suits in CardSuits for value in CardValues]
            shuffle(all_cards)
            unique_cards = set()
            while len(unique_cards) < 5:
                unique_cards.add(random.choice(all_cards))
            cards = list(unique_cards)
            print("Your cards are:", ", ".join(str(card) for card in cards))
            #time.sleep(4)
            while True:
                change_cards = input("Want to change cards? ")
                if change_cards.lower() == "yes":
                    quantity = input("Which cards? ")

                    card_input_index = first, second, third, fourth, fifth 
                    first, second, third, fourth, fifth = (1, 2, 3, 4, 5) 
                    first = cards[0]
                    second = cards[1]
                    third = cards[2]
                    fourth = cards[3]
                    fifth = cards[4]
                    

                    if quantity.lower() == "none":
                        break

                    elif quantity.lower() in card_input_index:
                        cards.remove(card_input_index)
                        while len(cards) < 5:
                        cards.add(random.choice(all_cards))
                        print("Your cards are:", ", ".join(str(card) for card in cards))
                        break
                    
                    
                    elif quantity.lower() == "all":
                        all_cards = [Card(suits, value) for suits in CardSuits for value in CardValues]
                        unique_cards = set()
                        while len(unique_cards) < 5:
                            unique_cards.add(random.choice(all_cards))
                        cards = list(unique_cards)
                        print("Your new cards are:", ", ".join(str(card) for card in cards))
                        break                
                    else:
                        print("Invalid cards selected")
                elif change_cards.lower() == "no":    
                    break     

            #CHECKING PHASE
                


            #SCORE DASHBOARD?
            
            
            while True:        
                continue_playing = input("You want to keep playing?")
                if continue_playing.lower() == "yes":
                    wanna_shuffle = input("Wanna shuffle the deck?")
                    if wanna_shuffle.lower() == "yes":
                        shuffle(all_cards)
                        print("Deck shuffled")
                        break
                    elif continue_playing.lower() == "no":
                        break
                    else:
                        continue
                elif continue_playing.lower() == "no":
                    exit()    
            start()   
            
            
        else:
            exit()
        

    start()

So now I’m trying to understand how change cards by an index input (1st, 4th / second or even 1, 4, 5…) instead of write every possible change.
I’ve tried with that card_input_index, but the terminal gives me this error:

UnboundLocalError: cannot access local variable ‘first’ where it is not associated with a value

So now I’ll search about this error and try to fix it

No, frankly this is not the way to use classes.

Use dictionary or list for these, or a set.

A class is to define a type of thing that you want to instantiate multiple instances of. Maybe you could define a deck of cards that has 52 cards and you can instantiate multiple decks and keep track of which cards have been dealt that way?

I see how you are using Enum/Class here:
https://docs.python.org/3/howto/enum.html

That’s fine but it does not solve your problem. I’ve explained as best I can above. I think you are over-complicating it.

If the user types “1” to change the first card, you just need to access cards[0], or cards[n - 1].

If you want the user to type “first” to change the first card, you just need to look it up in a dictionary, or use a simple if statement. Keep it simple.

n = input("What cards do you want to change?")

change(cards[n-1])

or

if n == "first":
    change(cards[0])

There’s only 5 cards so it will work. Or you look it up in a dictionary mapping:

dictionary =	{
  "first": 0,
  "second": 1,
  "third": 2
}

change(cards[dictionary[input]])

https://www.w3schools.com/python/python_dictionaries.asp