Created
March 5, 2009 13:23
-
-
Save ramalho/74349 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
''' | |
Uma carta tem atributos valor e naipe:: | |
>>> c = Carta('A','ouros') | |
>>> c | |
<A de ouros> | |
Dado um baralho... :: | |
>>> b = Baralho() | |
>>> for c in b: print c # doctest: +ELLIPSIS | |
<A de copas> | |
<2 de copas> | |
<3 de copas> | |
... | |
<Q de paus> | |
<K de paus> | |
>>> b[-1] | |
<K de paus> | |
... o método pop serve para tirar a última :: | |
>>> b.pop() | |
<K de paus> | |
>>> b[-1] | |
<Q de paus> | |
>>> len(b) | |
51 | |
O pop também permite tirar uma carta específica:: | |
>>> b.pop(2) | |
<3 de copas> | |
>>> len(b) | |
50 | |
E o método tira_uma sorteia e tira uma carta qualquer:: | |
>>> b.tira_uma() # doctest: +ELLIPSIS | |
<... | |
>>> len(b) | |
49 | |
>>> manga = b.tira_uma() | |
>>> len(b) | |
48 | |
>>> manga in b | |
False | |
''' | |
from random import randrange | |
class Carta(object): | |
def __init__(self, valor, naipe): | |
self.valor = valor | |
self.naipe = naipe | |
def __repr__(self): | |
return '<%s de %s>' % (self.valor, self.naipe) | |
class Baralho(object): | |
naipes = 'copas ouros espadas paus'.split() | |
valores = 'A 2 3 4 5 6 7 8 9 10 J Q K'.split() | |
def __init__(self): | |
self.cartas = [ | |
Carta(v, n) for n in self.naipes for v in self.valores | |
] | |
def __len__(self): | |
return len(self.cartas) | |
def __getitem__(self, pos): | |
return self.cartas[pos] | |
def __setitem__(self, pos, item): | |
self.cartas[pos] = item | |
def pop(self, index=-1): | |
return self.cartas.pop(index) | |
def tira_uma(self): | |
return self.pop(randrange(0,len(self.cartas))) | |
if __name__=='__main__': | |
import doctest | |
print doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment