Решение на Тесте карти от Теодор Драганов

Обратно към всички решения

Към профила на Теодор Драганов

Резултати

  • 9 точки от тестове
  • 0 бонус точки
  • 9 точки общо
  • 14 успешни тест(а)
  • 2 неуспешни тест(а)

Код

from collections import OrderedDict
CARDS_RANKS = [('K', 'King'),
('Q', 'Queen'),
('J', 'Jack'),
('10', 'Ten'),
('9', 'Nine'),
('8', 'Eight'),
('7', 'Seven'),
('6', 'Six'),
('5', 'Five'),
('4', 'Four'),
('3', 'Three'),
('2', 'Two'),
('A', 'Ace')]
CARDS_SUITS = [('Diamonds', 'red'),
('Clubs', 'black'),
('Hearts', 'red'),
('Spades', 'black')]
class Rank:
_symbol = ''
def __eq__(self, other):
return self._symbol == other._symbol
def __str__(self):
return self.__class__.__name__
class Suit:
_color = ''
def __eq__(self, other):
return (self._color == other._color) and \
(self.__class__.__name__ == other.__class__.__name__)
def __str__(self):
return self.__class__.__name__
RANKS = OrderedDict()
for rank_symbol, rank in CARDS_RANKS:
RANKS[rank] = type(rank, (Rank,), dict(_symbol=rank_symbol))
SUITS = OrderedDict()
for suit, suit_color in CARDS_SUITS:
SUITS[suit] = type(suit, (Suit,), dict(_color=suit_color))
class Card:
def __init__(self, rank, suit):
object.__setattr__(self, 'rank', rank())
object.__setattr__(self, 'suit', suit())
def __eq__(self, other):
return (self.rank == other.rank) and \
(self.suit == other.suit)
def __str__(self):
return '{} of {}'.format(self.rank.__class__.__name__,
self.suit.__class__.__name__)
def __setattr__(self, *args):
raise AttributeError("can't set attribute")
#def __del__(self, *args):
# raise AttributeError("can't delete attribute")
def __repr__(self):
return '<{}>'.format(str(self))
class CardCollection:
def __init__(self, collection=[]):
self.cards = list(collection)
def __iter__(self):
return iter(self.cards)
def __len__(self):
return len(self.cards)
def __getitem__(self, key):
return self.cards[key]
def add(self, card):
self.cards.append(card)
def draw(self, index):
return self.cards.pop(index)
def draw_from_top(self):
return self.cards.pop()
def draw_from_bottom(self):
return self.cards.pop(0)
def top_card(self):
return self.cards[-1]
def bottom_card(self):
return self.cards[0]
def index(self, card):
return self.cards.index(card)
def __repr__(self):
return str(self.cards)
def StandardDeck():
return CardCollection([Card(rank, suit)
for suit in SUITS.values()
for rank in RANKS.values()])
def BeloteDeck():
BELOTE_DECK_RANKS = CARDS_RANKS[:]
BELOTE_DECK_RANKS[7:-1] = []
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for suit in SUITS.values()
for rank_symbol in BELOTE_DECK_RANKS[5:]])
def SixtySixDeck():
SIXTYSIX_DECK_RANKS = CARDS_RANKS[:]
SIXTYSIX_DECK_RANKS[7:-1] = []
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for suit in SUITS.values()
for rank_symbol in SIXTYSIX_DECK_RANKS[7:]])

Лог от изпълнението

F.....F.........
======================================================================
FAIL: test_belote_deck (test.CardCollectionTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140407-19315-o4wl3v/test.py", line 175, in test_belote_deck
    self.assertEqual(BELOTE_DECK, cards)
AssertionError: Lists differ: ['King of Diamonds', 'Queen of... != ['Eight of Diamonds', 'Seven o...

First differing element 0:
King of Diamonds
Eight of Diamonds

First list contains 20 additional elements.
First extra element 12:
Nine of Clubs

Diff is 718 characters long. Set self.maxDiff to None to see it.

======================================================================
FAIL: test_sixtysix_deck (test.CardCollectionTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140407-19315-o4wl3v/test.py", line 179, in test_sixtysix_deck
    self.assertEqual(SIXTY_SIX_DECK, cards)
AssertionError: Lists differ: ['King of Diamonds', 'Queen of... != ['Ace of Diamonds', 'Ace of Cl...

First differing element 0:
King of Diamonds
Ace of Diamonds

First list contains 20 additional elements.
First extra element 4:
Nine of Diamonds

+ ['Ace of Diamonds', 'Ace of Clubs', 'Ace of Hearts', 'Ace of Spades']
- ['King of Diamonds',
-  'Queen of Diamonds',
-  'Jack of Diamonds',
-  'Ten of Diamonds',
-  'Nine of Diamonds',
-  'Ace of Diamonds',
-  'King of Clubs',
-  'Queen of Clubs',
-  'Jack of Clubs',
-  'Ten of Clubs',
-  'Nine of Clubs',
-  'Ace of Clubs',
-  'King of Hearts',
-  'Queen of Hearts',
-  'Jack of Hearts',
-  'Ten of Hearts',
-  'Nine of Hearts',
-  'Ace of Hearts',
-  'King of Spades',
-  'Queen of Spades',
-  'Jack of Spades',
-  'Ten of Spades',
-  'Nine of Spades',
-  'Ace of Spades']

----------------------------------------------------------------------
Ran 16 tests in 0.029s

FAILED (failures=2)

История (8 версии и 1 коментар)

Теодор обнови решението на 20.03.2014 18:56 (преди над 10 години)

+"""
+Мисля че открих начин да си дефинирам различните класове по не brute force начин, но не знам колко е правилен и дали изобщо е удачно да го правя.А и като цяло не сработва и искам да питам защо?
+"""
+CARDS_RANKS = ['King', 'Six', 'Jack', 'Five', 'Queen', 'Ten', 'Ace', 'Three',
+ 'Eight', 'Four', 'Two', 'Seven', 'Nine']
+
+CARDS_SUITS = ['Diamonds', 'Hearts', 'Spades', 'Clubs']
+
+
+class Rank:
+ def __init__(self, symbol):
+ self.symbol = symbol
+
+
+class Suit:
+ def __init__(self, color):
+ self.color = color
+
+RANKS = {}
+for rank in CARDS_RANKS:
+ class_definition = "{} = Rank".format(rank)
+ exec(class_definition, RANKS)
+
+#Python ми се 'кара',че Rank не е дефинирано.Защо?

Теодор обнови решението на 20.03.2014 19:14 (преди над 10 години)

-"""
-Мисля че открих начин да си дефинирам различните класове по не brute force начин, но не знам колко е правилен и дали изобщо е удачно да го правя.А и като цяло не сработва и искам да питам защо?
+#Решението не е това,което се очаква, но все пак ми е чудно защо не намира Rank?
-"""
-CARDS_RANKS = ['King', 'Six', 'Jack', 'Five', 'Queen', 'Ten', 'Ace', 'Three',
- 'Eight', 'Four', 'Two', 'Seven', 'Nine']
-
-CARDS_SUITS = ['Diamonds', 'Hearts', 'Spades', 'Clubs']
-
-
-class Rank:
- def __init__(self, symbol):
- self.symbol = symbol
-
-
-class Suit:
- def __init__(self, color):
- self.color = color
-
-RANKS = {}
-for rank in CARDS_RANKS:
- class_definition = "{} = Rank".format(rank)
- exec(class_definition, RANKS)
-
-#Python ми се 'кара',че Rank не е дефинирано.Защо?

Струва ми се, че това което искаш е да генерираш динамично питонски код като низ и да го изпълниш. Тази функционалност съществува и е много лоша идея -- нарича се Eval. Има една програмистка поговорка, която гласи "Eval is Evil".

Начин по който да си дефинираш много класове без да ги пишеш изрично с ключовата дума class е използвайки функцията type.

Теодор обнови решението на 21.03.2014 21:46 (преди над 10 години)

-#Решението не е това,което се очаква, но все пак ми е чудно защо не намира Rank?
+CARDS_RANKS = [('2', 'Two'),
+ ('3', 'Three'),
+ ('4', 'Four'),
+ ('5', 'Five'),
+ ('6', 'Six'),
+ ('7', 'Seven'),
+ ('8', 'Eight'),
+ ('9', 'Nine'),
+ ('10', 'Ten'),
+ ('J', 'Jack'),
+ ('Q', 'Queen'),
+ ('K', 'King'),
+ ('A', 'Ace')]
+
+
+CARDS_SUITS = [('Diamonds', 'red'),
+ ('Hearts', 'red'),
+ ('Spades', 'black'),
+ ('Clubs', 'black')]
+
+
+# вид на картата
+class Rank:
+ _symbol = ''
+
+ def __eq__(self, other):
+ return self._symbol == other._symbol
+
+ def __str__(self):
+ return self.__class__.__name__S
+
+
+# боя на картата
+class Suit:
+ _color = ''
+
+ def __eq__(self, other):
+ return (self._color == other._color) and \
+ (self.__class__.__name__ == other.__class__.__name__)
+
+ def __str__(self):
+ return self.__class__.__name__
+
+
+RANKS = {}
+for rank_symbol, rank in CARDS_RANKS:
+ RANKS[rank] = type(rank, (Rank,), dict(_symbol = rank_symbol))
+
+
+SUITS = {}
+for suit, suit_color in CARDS_SUITS:
+ SUITS[suit] = type(suit, (Suit,), dict(_color = suit_color))
+
+
+# Клас който представлява една карта за игра
+class Card:
+ def __init__(self, rank, suit):
+ object.__setattr__(self, 'rank', rank())
+ object.__setattr__(self, 'suit', suit())
+
+ def __eq__(self, other):
+ return (self.rank == other.rank) and \
+ (self.suit == other.suit)
+
+ def __str__(self):
+ return (self.rank.__class__.__name__ + ' of ' +
+ self.suit.__class__.__name__)
+
+ def __repr__(self):
+ return '<{} of {}>'.format(self.rank.__class__.__name__,
+ self.suit.__class__.__name__)
+
+ def __setattr__(self, *args):
+ raise AttributeError("can't set attribute")
+
+
+# Представлява колекция (тесте) от карти
+class CardCollection:
+ def __init__(self, collection):
+ self.cards = list(collection)
+
+ def __iter__(self):
+ return iter(self.cards)
+
+ def __len__(self):
+ return len(self.cards)
+
+ def __getitem__(self, key):
+ return self.cards[key]
+
+ def add(self, card):
+ self.cards.append(card)
+
+ def draw(self, index):
+ return self.cards.pop(index)
+
+ def draw_from_top(self):
+ return self.cards.pop()
+
+ def draw_from_bottom(self):
+ return self.cards.pop(0)
+
+ def top_card(self):
+ return self.cards[-1]
+
+ def bottom_card(self):
+ return self.cards[0]
+
+ def index(self, card):
+ return self.cards.index(card)
+
+
+def StandardDeck():
+ return CardCollection([Card(rank, suit)
+ for rank in RANKS.values()
+ for suit in SUITS.values()])
+
+
+def BeloteDeck():
+ return CardCollection([Card(RANKS[rank_symbol[1]], suit)
+ for rank_symbol in CARDS_RANKS[5:]
+ for suit in SUITS.values()])
+
+
+def SixtySixDeck():
+ return CardCollection([Card(RANKS[rank_symbol[1]], suit)
+ for rank_symbol in CARDS_RANKS[7:]
+ for suit in SUITS.values()])

Теодор обнови решението на 21.03.2014 23:22 (преди над 10 години)

CARDS_RANKS = [('2', 'Two'),
('3', 'Three'),
('4', 'Four'),
('5', 'Five'),
('6', 'Six'),
('7', 'Seven'),
('8', 'Eight'),
('9', 'Nine'),
('10', 'Ten'),
('J', 'Jack'),
('Q', 'Queen'),
('K', 'King'),
('A', 'Ace')]
CARDS_SUITS = [('Diamonds', 'red'),
('Hearts', 'red'),
('Spades', 'black'),
('Clubs', 'black')]
# вид на картата
class Rank:
_symbol = ''
def __eq__(self, other):
return self._symbol == other._symbol
def __str__(self):
return self.__class__.__name__S
# боя на картата
class Suit:
_color = ''
def __eq__(self, other):
return (self._color == other._color) and \
(self.__class__.__name__ == other.__class__.__name__)
def __str__(self):
return self.__class__.__name__
RANKS = {}
for rank_symbol, rank in CARDS_RANKS:
RANKS[rank] = type(rank, (Rank,), dict(_symbol = rank_symbol))
SUITS = {}
for suit, suit_color in CARDS_SUITS:
SUITS[suit] = type(suit, (Suit,), dict(_color = suit_color))
# Клас който представлява една карта за игра
class Card:
def __init__(self, rank, suit):
object.__setattr__(self, 'rank', rank())
object.__setattr__(self, 'suit', suit())
def __eq__(self, other):
return (self.rank == other.rank) and \
(self.suit == other.suit)
def __str__(self):
return (self.rank.__class__.__name__ + ' of ' +
self.suit.__class__.__name__)
def __repr__(self):
return '<{} of {}>'.format(self.rank.__class__.__name__,
self.suit.__class__.__name__)
def __setattr__(self, *args):
raise AttributeError("can't set attribute")
# Представлява колекция (тесте) от карти
class CardCollection:
- def __init__(self, collection):
+ def __init__(self, collection=[]):
self.cards = list(collection)
def __iter__(self):
return iter(self.cards)
def __len__(self):
return len(self.cards)
def __getitem__(self, key):
return self.cards[key]
def add(self, card):
self.cards.append(card)
def draw(self, index):
return self.cards.pop(index)
def draw_from_top(self):
return self.cards.pop()
def draw_from_bottom(self):
return self.cards.pop(0)
def top_card(self):
return self.cards[-1]
def bottom_card(self):
return self.cards[0]
def index(self, card):
return self.cards.index(card)
def StandardDeck():
return CardCollection([Card(rank, suit)
for rank in RANKS.values()
for suit in SUITS.values()])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for rank_symbol in CARDS_RANKS[5:]
for suit in SUITS.values()])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for rank_symbol in CARDS_RANKS[7:]
for suit in SUITS.values()])

Теодор обнови решението на 23.03.2014 18:09 (преди над 10 години)

CARDS_RANKS = [('2', 'Two'),
('3', 'Three'),
('4', 'Four'),
('5', 'Five'),
('6', 'Six'),
('7', 'Seven'),
('8', 'Eight'),
('9', 'Nine'),
('10', 'Ten'),
('J', 'Jack'),
('Q', 'Queen'),
('K', 'King'),
('A', 'Ace')]
CARDS_SUITS = [('Diamonds', 'red'),
('Hearts', 'red'),
('Spades', 'black'),
('Clubs', 'black')]
# вид на картата
class Rank:
_symbol = ''
def __eq__(self, other):
return self._symbol == other._symbol
def __str__(self):
- return self.__class__.__name__S
+ return self.__class__.__name__
# боя на картата
class Suit:
_color = ''
def __eq__(self, other):
return (self._color == other._color) and \
(self.__class__.__name__ == other.__class__.__name__)
def __str__(self):
return self.__class__.__name__
RANKS = {}
for rank_symbol, rank in CARDS_RANKS:
RANKS[rank] = type(rank, (Rank,), dict(_symbol = rank_symbol))
SUITS = {}
for suit, suit_color in CARDS_SUITS:
SUITS[suit] = type(suit, (Suit,), dict(_color = suit_color))
# Клас който представлява една карта за игра
class Card:
def __init__(self, rank, suit):
object.__setattr__(self, 'rank', rank())
object.__setattr__(self, 'suit', suit())
def __eq__(self, other):
return (self.rank == other.rank) and \
(self.suit == other.suit)
def __str__(self):
return (self.rank.__class__.__name__ + ' of ' +
self.suit.__class__.__name__)
def __repr__(self):
return '<{} of {}>'.format(self.rank.__class__.__name__,
self.suit.__class__.__name__)
def __setattr__(self, *args):
raise AttributeError("can't set attribute")
# Представлява колекция (тесте) от карти
class CardCollection:
def __init__(self, collection=[]):
self.cards = list(collection)
def __iter__(self):
return iter(self.cards)
def __len__(self):
return len(self.cards)
def __getitem__(self, key):
return self.cards[key]
def add(self, card):
self.cards.append(card)
def draw(self, index):
return self.cards.pop(index)
def draw_from_top(self):
return self.cards.pop()
def draw_from_bottom(self):
return self.cards.pop(0)
def top_card(self):
return self.cards[-1]
def bottom_card(self):
return self.cards[0]
def index(self, card):
return self.cards.index(card)
def StandardDeck():
return CardCollection([Card(rank, suit)
for rank in RANKS.values()
for suit in SUITS.values()])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for rank_symbol in CARDS_RANKS[5:]
for suit in SUITS.values()])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for rank_symbol in CARDS_RANKS[7:]
for suit in SUITS.values()])

Теодор обнови решението на 25.03.2014 03:16 (преди над 10 години)

CARDS_RANKS = [('2', 'Two'),
('3', 'Three'),
('4', 'Four'),
('5', 'Five'),
('6', 'Six'),
('7', 'Seven'),
('8', 'Eight'),
('9', 'Nine'),
('10', 'Ten'),
('J', 'Jack'),
('Q', 'Queen'),
('K', 'King'),
('A', 'Ace')]
CARDS_SUITS = [('Diamonds', 'red'),
('Hearts', 'red'),
('Spades', 'black'),
('Clubs', 'black')]
-# вид на картата
class Rank:
_symbol = ''
def __eq__(self, other):
return self._symbol == other._symbol
def __str__(self):
return self.__class__.__name__
-# боя на картата
class Suit:
_color = ''
def __eq__(self, other):
return (self._color == other._color) and \
(self.__class__.__name__ == other.__class__.__name__)
def __str__(self):
return self.__class__.__name__
RANKS = {}
for rank_symbol, rank in CARDS_RANKS:
RANKS[rank] = type(rank, (Rank,), dict(_symbol = rank_symbol))
SUITS = {}
for suit, suit_color in CARDS_SUITS:
SUITS[suit] = type(suit, (Suit,), dict(_color = suit_color))
-# Клас който представлява една карта за игра
class Card:
def __init__(self, rank, suit):
object.__setattr__(self, 'rank', rank())
object.__setattr__(self, 'suit', suit())
def __eq__(self, other):
return (self.rank == other.rank) and \
(self.suit == other.suit)
def __str__(self):
- return (self.rank.__class__.__name__ + ' of ' +
- self.suit.__class__.__name__)
+ return '{} of {}'.format(self.rank.__class__.__name__,
+ self.suit.__class__.__name__)
- def __repr__(self):
- return '<{} of {}>'.format(self.rank.__class__.__name__,
- self.suit.__class__.__name__)
-
def __setattr__(self, *args):
raise AttributeError("can't set attribute")
-# Представлява колекция (тесте) от карти
class CardCollection:
def __init__(self, collection=[]):
self.cards = list(collection)
def __iter__(self):
return iter(self.cards)
def __len__(self):
return len(self.cards)
def __getitem__(self, key):
return self.cards[key]
def add(self, card):
self.cards.append(card)
def draw(self, index):
return self.cards.pop(index)
def draw_from_top(self):
return self.cards.pop()
def draw_from_bottom(self):
return self.cards.pop(0)
def top_card(self):
return self.cards[-1]
def bottom_card(self):
return self.cards[0]
def index(self, card):
return self.cards.index(card)
def StandardDeck():
return CardCollection([Card(rank, suit)
for rank in RANKS.values()
for suit in SUITS.values()])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for rank_symbol in CARDS_RANKS[5:]
for suit in SUITS.values()])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for rank_symbol in CARDS_RANKS[7:]
for suit in SUITS.values()])

Теодор обнови решението на 25.03.2014 19:38 (преди над 10 години)

-CARDS_RANKS = [('2', 'Two'),
- ('3', 'Three'),
- ('4', 'Four'),
- ('5', 'Five'),
- ('6', 'Six'),
- ('7', 'Seven'),
- ('8', 'Eight'),
- ('9', 'Nine'),
- ('10', 'Ten'),
- ('J', 'Jack'),
+from collections import OrderedDict
+
+CARDS_RANKS = [('K', 'King'),
('Q', 'Queen'),
- ('K', 'King'),
+ ('J', 'Jack'),
+ ('10', 'Ten'),
+ ('9', 'Nine'),
+ ('8', 'Eight'),
+ ('7', 'Seven'),
+ ('6', 'Six'),
+ ('5', 'Five'),
+ ('4', 'Four'),
+ ('3', 'Three'),
+ ('2', 'Two'),
('A', 'Ace')]
CARDS_SUITS = [('Diamonds', 'red'),
+ ('Clubs', 'black'),
('Hearts', 'red'),
- ('Spades', 'black'),
- ('Clubs', 'black')]
+ ('Spades', 'black')]
class Rank:
_symbol = ''
def __eq__(self, other):
return self._symbol == other._symbol
def __str__(self):
return self.__class__.__name__
class Suit:
_color = ''
def __eq__(self, other):
return (self._color == other._color) and \
(self.__class__.__name__ == other.__class__.__name__)
def __str__(self):
return self.__class__.__name__
-RANKS = {}
+RANKS = OrderedDict()
for rank_symbol, rank in CARDS_RANKS:
- RANKS[rank] = type(rank, (Rank,), dict(_symbol = rank_symbol))
+ RANKS[rank] = type(rank, (Rank,), dict(_symbol=rank_symbol))
-SUITS = {}
+SUITS = OrderedDict()
for suit, suit_color in CARDS_SUITS:
- SUITS[suit] = type(suit, (Suit,), dict(_color = suit_color))
+ SUITS[suit] = type(suit, (Suit,), dict(_color=suit_color))
class Card:
def __init__(self, rank, suit):
object.__setattr__(self, 'rank', rank())
object.__setattr__(self, 'suit', suit())
def __eq__(self, other):
return (self.rank == other.rank) and \
(self.suit == other.suit)
def __str__(self):
return '{} of {}'.format(self.rank.__class__.__name__,
self.suit.__class__.__name__)
def __setattr__(self, *args):
raise AttributeError("can't set attribute")
+ #def __del__(self, *args):
+ # raise AttributeError("can't delete attribute")
+ def __repr__(self):
+ return '<{}>'.format(str(self))
+
+
class CardCollection:
def __init__(self, collection=[]):
self.cards = list(collection)
def __iter__(self):
return iter(self.cards)
def __len__(self):
return len(self.cards)
def __getitem__(self, key):
return self.cards[key]
def add(self, card):
self.cards.append(card)
def draw(self, index):
return self.cards.pop(index)
def draw_from_top(self):
return self.cards.pop()
def draw_from_bottom(self):
return self.cards.pop(0)
def top_card(self):
return self.cards[-1]
def bottom_card(self):
return self.cards[0]
def index(self, card):
return self.cards.index(card)
+ def __repr__(self):
+ return str(self.cards)
+
def StandardDeck():
return CardCollection([Card(rank, suit)
- for rank in RANKS.values()
- for suit in SUITS.values()])
+ for suit in SUITS.values()
+ for rank in RANKS.values()])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
- for rank_symbol in CARDS_RANKS[5:]
- for suit in SUITS.values()])
+ for suit in SUITS.values()
+ for rank_symbol in CARDS_RANKS[5:]])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
- for rank_symbol in CARDS_RANKS[7:]
- for suit in SUITS.values()])
+ for suit in SUITS.values()
+ for rank_symbol in CARDS_RANKS[7:]])

Теодор обнови решението на 26.03.2014 14:55 (преди над 10 години)

from collections import OrderedDict
CARDS_RANKS = [('K', 'King'),
('Q', 'Queen'),
('J', 'Jack'),
('10', 'Ten'),
('9', 'Nine'),
('8', 'Eight'),
('7', 'Seven'),
('6', 'Six'),
('5', 'Five'),
('4', 'Four'),
('3', 'Three'),
('2', 'Two'),
('A', 'Ace')]
CARDS_SUITS = [('Diamonds', 'red'),
('Clubs', 'black'),
('Hearts', 'red'),
('Spades', 'black')]
class Rank:
_symbol = ''
def __eq__(self, other):
return self._symbol == other._symbol
def __str__(self):
return self.__class__.__name__
class Suit:
_color = ''
def __eq__(self, other):
return (self._color == other._color) and \
(self.__class__.__name__ == other.__class__.__name__)
def __str__(self):
return self.__class__.__name__
RANKS = OrderedDict()
for rank_symbol, rank in CARDS_RANKS:
RANKS[rank] = type(rank, (Rank,), dict(_symbol=rank_symbol))
SUITS = OrderedDict()
for suit, suit_color in CARDS_SUITS:
SUITS[suit] = type(suit, (Suit,), dict(_color=suit_color))
class Card:
def __init__(self, rank, suit):
object.__setattr__(self, 'rank', rank())
object.__setattr__(self, 'suit', suit())
def __eq__(self, other):
return (self.rank == other.rank) and \
(self.suit == other.suit)
def __str__(self):
return '{} of {}'.format(self.rank.__class__.__name__,
self.suit.__class__.__name__)
def __setattr__(self, *args):
raise AttributeError("can't set attribute")
#def __del__(self, *args):
# raise AttributeError("can't delete attribute")
def __repr__(self):
return '<{}>'.format(str(self))
class CardCollection:
def __init__(self, collection=[]):
self.cards = list(collection)
def __iter__(self):
return iter(self.cards)
def __len__(self):
return len(self.cards)
def __getitem__(self, key):
return self.cards[key]
def add(self, card):
self.cards.append(card)
def draw(self, index):
return self.cards.pop(index)
def draw_from_top(self):
return self.cards.pop()
def draw_from_bottom(self):
return self.cards.pop(0)
def top_card(self):
return self.cards[-1]
def bottom_card(self):
return self.cards[0]
def index(self, card):
return self.cards.index(card)
def __repr__(self):
return str(self.cards)
def StandardDeck():
return CardCollection([Card(rank, suit)
for suit in SUITS.values()
for rank in RANKS.values()])
def BeloteDeck():
+ BELOTE_DECK_RANKS = CARDS_RANKS[:]
+ BELOTE_DECK_RANKS[7:-1] = []
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for suit in SUITS.values()
- for rank_symbol in CARDS_RANKS[5:]])
+ for rank_symbol in BELOTE_DECK_RANKS[5:]])
def SixtySixDeck():
+ SIXTYSIX_DECK_RANKS = CARDS_RANKS[:]
+ SIXTYSIX_DECK_RANKS[7:-1] = []
return CardCollection([Card(RANKS[rank_symbol[1]], suit)
for suit in SUITS.values()
- for rank_symbol in CARDS_RANKS[7:]])
+ for rank_symbol in SIXTYSIX_DECK_RANKS[7:]])