How to deal cards from a deck using dictionary

Asked

Viewed 86 times

2

I have the following dictionary composed of a list of its values:

baralho = { 'Paus':   ['Ás',2,3,4,5,6,7,8,9,10,'Dama','Valete','Reis'] ,
            'Ouros':  ['Ás',2,3,4,5,6,7,8,9,10,'Dama','Valete','Reis'] ,
            'Espadas':['Ás',2,3,4,5,6,7,8,9,10,'Dama','Valete','Reis'] ,
            'Copas':  ['Ás',2,3,4,5,6,7,8,9,10,'Dama','Valete','Reis'] }

I would like to know how to go through these keys and their values sequentially and randomly, drawing 5 cards. Without using Python functions. I don’t know how to index the values for each key.

I tried for a simpler step:

for b in baralho:
   print(b)

The result was only printing the keys, I tried a cont=0 and add to each loop for the index but gave the error: The 'Nonetype' object is not subscriptible.

 for b in baralho:
     print(b)[cont]     
     cont = cont + 1

I searched here on the platform but I did not find something equivalent to this problem, it may be that I have not used any necessary term.

2 answers

3

I cannot say that it is the ideal method, as there are several ways you can understand the cards of a deck.
But a simple way to model cards from a deck is first to model the suits, then to model the values and from these form the cards in the deck.

To model the suits and values of the cards can be used tuples because it is an immutable sequence, once the values are defined there is no reason to change them.

To model a single card also use a tuple because created the letter there is no why change its value.

For the deck use one list because it is a changeable sequence and it is interesting to change the order of the elements as well as add and remove cards.

Example1: Shaping the deck and displaying your cards.

naipes = ('Paus', 'Ouros', 'Espadas', 'Copas')

valores = ('A', 2, 3, 4, 5, 6, 7, 8, 9, 10,'Dama', 'Valete', 'Reis')

baralho = [(v, n) for v in valores for n in naipes]

for carta in baralho:
  print(carta)

Upshot:

('A', 'Paus')
('A', 'Ouros')
('A', 'Espadas')
('A', 'Copas')
(2, 'Paus')
(2, 'Ouros')
(2, 'Espadas')
(2, 'Copas')
(3, 'Paus')
(3, 'Ouros')
(3, 'Espadas')
(3, 'Copas')
(4, 'Paus')
(4, 'Ouros')
(4, 'Espadas')
(4, 'Copas')
(5, 'Paus')
(5, 'Ouros')
(5, 'Espadas')
(5, 'Copas')
(6, 'Paus')
(6, 'Ouros')
(6, 'Espadas')
(6, 'Copas')
(7, 'Paus')
(7, 'Ouros')
(7, 'Espadas')
(7, 'Copas')
(8, 'Paus')
(8, 'Ouros')
(8, 'Espadas')
(8, 'Copas')
(9, 'Paus')
(9, 'Ouros')
(9, 'Espadas')
(9, 'Copas')
(10, 'Paus')
(10, 'Ouros')
(10, 'Espadas')
(10, 'Copas')
('Dama', 'Paus')
('Dama', 'Ouros')
('Dama', 'Espadas')
('Dama', 'Copas')
('Valete', 'Paus')
('Valete', 'Ouros')
('Valete', 'Espadas')
('Valete', 'Copas')
('Reis', 'Paus')
('Reis', 'Ouros')
('Reis', 'Espadas')
('Reis', 'Copas')

To shuffle a sequence can be used the function shuffle() of the native module random.

Exemplo2: Shuffling your cards around.

import random

naipes = ('Paus', 'Ouros', 'Espadas', 'Copas')

valores = ('A', 2, 3, 4, 5, 6, 7, 8, 9, 10,'Dama', 'Valete', 'Reis')

baralho = [(v, n) for v in valores for n in naipes]

random.shuffle(baralho)

for carta in baralho:
  print(carta)

Upshot:

(2, 'Paus')
('Valete', 'Ouros')
(3, 'Ouros')
('Reis', 'Copas')
(5, 'Paus')
('Reis', 'Paus')
(6, 'Ouros')
(9, 'Copas')
(6, 'Espadas')
(4, 'Copas')
(9, 'Espadas')
(2, 'Espadas')
(6, 'Paus')
(9, 'Ouros')
(7, 'Copas')
('Valete', 'Copas')
(3, 'Paus')
('A', 'Espadas')
('A', 'Paus')
(2, 'Copas')
(8, 'Copas')
(10, 'Espadas')
(4, 'Paus')
('A', 'Ouros')
(8, 'Ouros')
(5, 'Ouros')
('Dama', 'Paus')
(7, 'Ouros')
('Valete', 'Espadas')
(9, 'Paus')
(7, 'Paus')
(2, 'Ouros')
(5, 'Copas')
(6, 'Copas')
(10, 'Paus')
('Reis', 'Espadas')
(10, 'Copas')
('Valete', 'Paus')
(4, 'Espadas')
('Dama', 'Espadas')
('Reis', 'Ouros')
(10, 'Ouros')
('Dama', 'Ouros')
(7, 'Espadas')
(3, 'Espadas')
(8, 'Espadas')
(3, 'Copas')
(4, 'Ouros')
('Dama', 'Copas')
(5, 'Espadas')
(8, 'Paus')
('A', 'Copas')

As a test for the model and example of how draw n cards can be created a 21 game where the player only wins if he makes exactly 21 points.

The game starts by clearing the pile of cards of the played and then shuffles the deck.
With the method list pop.() a card is removed from the deck and added to the player’s pile. The value of the card is computed and added to the user’s points.

The points are computed according to this table:

Letter Valor
To 1 If the total of points is greater than 10
To 11 If total points are less than 10
2,3,4,5,6,7,8,9,10 Has as value the face value itself
Lady Worth 12 points
Knave Worth 13 points
King Worth 14 points

If the player leaves the hand with less than 21 points or if he makes more than 21 points he loses.
Win only if you score exactly 21 points.

Example3: Game of 21

import random

naipes = ('Paus', 'Ouros', 'Espadas', 'Copas')

valores = ('A', 2, 3, 4, 5, 6, 7, 8, 9, 10,'Dama', 'Valete', 'Reis')

#Função para lipar a tela.
cls = lambda: print("\033c\033[3J", end='')

#Função para gerar um novo baralho.
def embaralhar():
  b = [(v, n) for v in valores for n in naipes]
  random.shuffle(b)
  return b

#Função para computar o valor da carta.
def calcular(pontos, carta):
  if carta[0] == 'A':
    return 11 if pontos <= 10 else 1
  if carta[0] in ('Dama', 'Valete', 'Reis'):
    return (
      12 if carta[0] == 'Dama' else
      13 if carta[0] == 'Valete' else
      14
    )
  return int(carta[0])

vitorias = 0        #Numeros de vitórias 
derrotas = 0        #Numeros de derrotas 

frase1 = "Bem vindo a jogatina."
frase2 = "Deseja jogar uma partida?(S/N)"
frase3 = "Puxar mais uma carta?(S/N)"
frase4 = "Você venceu."
frase5 = "Você perdeu."
frase6 = "Pressione <Enter> para continuar..."


print(frase1)
while((jogar:= input(frase2).upper()) == "S" ):
  cls()                       #Limpa a tela.
  monte = []                  #Limpa o monte do jogador
  baralho = embaralhar()      #Inicializa um novo baralho, já embaralhado.
  soma = 0                    #Inicializa os pontos do jogador.
  while(True):
    cls()                                      #Limpa a tela.
    monte.append(carta:= baralho.pop())        #Tira uma  carta do baralho e adiciona ao monte
    soma += calcular(soma, carta)              #Calcula o valor da carta e soma aos pontos do jogador.
    #Imprime o placar do jogo
    print(f'Vitorias: {vitorias}\tDerrotas: {derrotas}')
    print(*monte, sep="\n", end="")
    print(f'\ttotal: {soma}')
    #Testa condições de saída da mão. 
    if (soma >= 21) or input(frase3).upper() != "S":      
      break    
  #Testa vitória ou derrota.
  if (soma == 21):
      print(frase4)
      vitorias += 1
  else:
      print(frase5)
      derrotas += 1
  input(frase6)

Test the example on Repl.it

  • Very good his explanation @Augusto, I understood better being explained by parts like you did. I implemented here as adaptations and worked to list the cards, now I will work to randomize the choice of 5 cards, thanks!

  • @Santos, like this. See in the second example that after random.shuffle(baralho) just pick five cards or from the beginning or the end of the list, the result is always random.

  • @Carlosm.Santos I added a third example showing how to draw n cards.

  • Since you already answered... would it be duplicated? https://answall.com/q/261210/5878

  • 1

    @Woss, being honest I believe it is a duplicate. Very good response by the way(I had already voted for it in 2019 I think)

  • @Augusto good night! his reply helped me to understand the logic of the game of deck and went beyond, gave an excellent example of a full game. In the case of the question on this topic, I needed to do the letter distribution using specifically the concept of dictionaries and lists in the way I presented them. I understand that it may seem unnecessary to go this way but the proposal is to know how to deal with the structure in question (dictionary containing a list within it). I am very grateful!

Show 1 more comment

1

To list all cards in sequence:

def lista_cartas(baralho):
lista = []
for naipe in baralho:
    for carta in baralho[naipe]:
        lista.append(carta)
return lista

print(lista_cartas(baralho))

To choose 5 Random Cards:

import random

def escolhe_carta(baralho):
lista_escolhidas = []
naipe = random.choice(list(baralho.keys()))
carta = random.choice(baralho[naipe])
lista_escolhidas.append([naipe, carta])
return lista_escolhidas

for i in range(5):
    for i in escolhe_carta(baralho):
        print(f'Naipe: {i[0]} \nCarta: {i[1]}')
        print('-' * 20)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.