One option is to use collections.namedtuples
:
from collections import namedtuple
from itertools import product
Carta = namedtuple('Carta', ['face', 'naipe'])
faces = {'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'}
naipes = {'O', 'P', 'C', 'E'}
baralho = [Carta(face, naipe) for face, naipe in product(faces, naipes)]
print('Seu baralho possui', len(baralho), 'cartas')
# Seu baralho possui 52 cartas
See working at Ideone | Repl.it
To generate all the cards in the deck, I used itertools.product
. So, for each card in the deck you can do, for example:
carta = baralho[0]
print(carta.face, carta.naipe)
Displaying the face and suit of the respective card.
To randomly draw two cards for a player, you can use the random.sample
:
from random import sample
mao = sample(baralho, 2)
print('Mão do jogador:', mao)
# Mão do jogador: [Carta(face='Q', naipe='O'), Carta(face='A', naipe='P')]
See working at Ideone | Repl.it
Given the new information about the deck being stored in a file, the logic does not differ much, only, instead of generating all possible cards, read them from the respective file. Assuming the file is named baralho1.txt
, the definition of the deck would look something like:
from collections import namedtuple
Carta = namedtuple('Carta', ['face', 'naipe'])
baralho = []
with open('baralho1.txt') as ficheiro:
for linha in ficheiro:
carta = linha.strip().split()
baralho.append(Carta(*carta))
See working at Repl.it
Thus, the baralho
object will be a list of Carta
tuples following the values that were stored in the file. For the file excerpt given in the question, the result of print(baralho)
would be:
[
Carta(face='10', naipe='C'),
Carta(face='8', naipe='C'),
Carta(face='A', naipe='P'),
Carta(face='2', naipe='P'),
Carta(face='7', naipe='P'),
Carta(face='4', naipe='C'),
Carta(face='10', naipe='O'),
Carta(face='7', naipe='E'),
Carta(face='9', naipe='E'),
Carta(face='8', naipe='E')
]
You can shuffle the cards using the random.shuffle
function:
random.shuffle(baralho)
And then you could, for example, distribute the card between four players:
jogador_a = baralho[0:2]
jogador_b = baralho[2:4]
jogador_c = baralho[4:6]
jogador_d = baralho[6:8]
See working at Repl.it
Getting each one with 2 different cards. Obviously the process of distributing the cards can be modified according to your need and even the way to represent the player if there are other requirements to be satisfied.