Created
October 26, 2017 14:00
-
-
Save entwanne/f799d01ab6689ae455a9b20ae4dead12 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env python | |
import itertools | |
import random | |
from collections import Counter | |
from enum import IntEnum | |
card_ranks = range(2, 15) | |
card_colors = '♠♥♦♣' | |
cards = list(itertools.product(card_ranks, card_colors)) | |
cards_unicode = [None, None, 0x1f0a2, 0x1f0a3, 0x1f0a4, 0x1f0a5, 0x1f0a6, 0x1f0a7, 0x1f0a8, 0x1f0a9, 0x1f0aa, 0x1f0ab, 0x1f0ad, 0x1f0ae, 0x1f0a1] | |
class Score(IntEnum): | |
NULL = 0 | |
SIMPLE = 1 | |
PAIR = 2 | |
TWO_PAIR = 3 | |
THREE = 4 | |
STRAIGHT = 5 | |
FLUSH = 6 | |
FULL = 7 | |
FOUR = 8 | |
SFLUSH = 9 | |
def format_card(card): | |
rank, color = card | |
return chr(cards_unicode[rank] + 0x10*card_colors.index(color)) | |
def format_hand(hand): | |
return ' '.join(format_card(card) for card in hand) | |
def flushs(hand): | |
if len(set(color for _, color in hand)) == 1: | |
straight, *args = straights(hand) | |
if straight == Score.STRAIGHT: | |
return (Score.SFLUSH, *args) | |
return Score.FLUSH, hand[0][0] | |
return Score.NULL, | |
def straights(hand): | |
ranks = [rank for rank, _ in reversed(hand)] | |
if ranks == list(range(ranks[0], ranks[-1]+1)): | |
return Score.STRAIGHT, ranks[-1] | |
ranks = sorted([1 if rank == 14 else rank for rank, _ in hand]) | |
if ranks == list(range(ranks[0], ranks[-1]+1)): | |
return Score.STRAIGHT, ranks[-1] | |
return Score.NULL, | |
def multiples(hand): | |
count = Counter(rank for rank, _ in hand) | |
commons = sorted(count.most_common(), key=lambda c: (c[1], c[0]), reverse=True) | |
if commons[0][1] == 4: | |
return Score.FOUR, commons[0][0] | |
elif len(commons) == 2: | |
return Score.FULL, commons[0][0], commons[1][0] | |
elif commons[0][1] == 3: | |
return Score.THREE, commons[0][0] | |
elif len(commons) == 3: | |
return Score.TWO_PAIR, commons[0][0], commons[1][0] | |
elif commons[0][1] == 2: | |
return Score.PAIR, commons[0][0] | |
return Score.NULL, | |
def simple(hand): | |
return Score.SIMPLE, hand[0][0] | |
def get_score(hand): | |
return (*max(flushs(hand), straights(hand), multiples(hand), simple(hand)), *(rank for rank, _ in hand)) | |
if __name__ == '__main__': | |
hand = sorted(random.sample(cards, 5), reverse=True) | |
print(format_hand(hand), hand) | |
print(get_score(hand)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment