Add melds method to class Hand; added find_sets and find_runs functions
This commit is contained in:
parent
b4e659e9e0
commit
e179d71d41
@ -1,10 +1,12 @@
|
|||||||
import random
|
import random
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
|
||||||
|
RANK_ORDER = {str(n): n for n in range(2, 11)}
|
||||||
|
RANK_ORDER.update({"A": 1, "J": 11, "Q": 12, "K": 13})
|
||||||
class Card:
|
class Card:
|
||||||
suits = ['♠', '♥', '♦', '♣']
|
suits = ['♠', '♥', '♦', '♣']
|
||||||
ranks = list(range(1, 11)) + ['J', 'Q', 'K']
|
ranks = list(range(1, 11)) + ['J', 'Q', 'K']
|
||||||
RANK_ORDER = {str(n): n for n in range(2, 11)}
|
|
||||||
RANK_ORDER.update({"A": 1, "J": 11, "Q": 12, "K": 13})
|
|
||||||
|
|
||||||
def __init__(self, rank, suit):
|
def __init__(self, rank, suit):
|
||||||
self.rank = rank
|
self.rank = rank
|
||||||
@ -49,6 +51,9 @@ class Hand:
|
|||||||
|
|
||||||
def remove(self, card):
|
def remove(self, card):
|
||||||
self.cards.remove(card)
|
self.cards.remove(card)
|
||||||
|
|
||||||
|
def melds(self):
|
||||||
|
return find_sets(self.cards) + find_runs(self.cards)
|
||||||
|
|
||||||
def deadwood_points(self):
|
def deadwood_points(self):
|
||||||
return sum(c.value for c in self.cards) # placeholder
|
return sum(c.value for c in self.cards) # placeholder
|
||||||
@ -94,7 +99,41 @@ class Game:
|
|||||||
for p in self.players:
|
for p in self.players:
|
||||||
print(p.name, p.hand)
|
print(p.name, p.hand)
|
||||||
|
|
||||||
|
|
||||||
|
# Function to detect sets
|
||||||
|
def find_sets(cards):
|
||||||
|
groups = defaultdict(list)
|
||||||
|
for c in cards:
|
||||||
|
groups[c.rank].append(c)
|
||||||
|
return [group for group in groups.values() if len(group) >= 3]
|
||||||
|
|
||||||
|
|
||||||
|
# Function to detect runs
|
||||||
|
def find_runs(cards):
|
||||||
|
runs = []
|
||||||
|
# group by suit
|
||||||
|
suits = defaultdict(list)
|
||||||
|
for c in cards:
|
||||||
|
suits[c.suit].append(c)
|
||||||
|
|
||||||
|
for suit, suited_cards in suits.items():
|
||||||
|
# sort by rank order
|
||||||
|
sorted_cards = sorted(suited_cards, key=lambda c: RANK_ORDER[str(c.rank)])
|
||||||
|
# scan for consecutive sequences
|
||||||
|
temp = [sorted_cards[0]]
|
||||||
|
for i in range(1, len(sorted_cards)):
|
||||||
|
prev = RANK_ORDER[str(sorted_cards[i-1].rank)]
|
||||||
|
curr = RANK_ORDER[str(sorted_cards[i].rank)]
|
||||||
|
if curr == prev + 1:
|
||||||
|
temp.append(sorted_cards[i])
|
||||||
|
else:
|
||||||
|
if len(temp) >= 3:
|
||||||
|
runs.append(temp)
|
||||||
|
temp = [sorted_cards[i]]
|
||||||
|
if len(temp) >= 3:
|
||||||
|
runs.append(temp)
|
||||||
|
return runs
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Loading…
Reference in New Issue
Block a user