python/poker.py

66 lines
2.1 KiB
Python

import random
SUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
RANK_VALUES = {rank: i for i, rank in enumerate(RANKS, 2)}
def create_deck():
return [(rank, suit) for suit in SUITS for rank in RANKS]
def deal_hand(deck, num=5):
hand = random.sample(deck, num)
for card in hand:
deck.remove(card)
return hand
def hand_rank(hand):
ranks = sorted([RANK_VALUES[card[0]] for card in hand], reverse=True)
suits = [card[1] for card in hand]
rank_counts = {r: ranks.count(r) for r in ranks}
is_flush = len(set(suits)) == 1
is_straight = all(ranks[i] - 1 == ranks[i+1] for i in range(len(ranks)-1))
counts = sorted(rank_counts.values(), reverse=True)
if is_straight and is_flush:
return (8, ranks) # Straight flush
elif counts[0] == 4:
return (7, ranks) # Four of a kind
elif counts[0] == 3 and counts[1] == 2:
return (6, ranks) # Full house
elif is_flush:
return (5, ranks) # Flush
elif is_straight:
return (4, ranks) # Straight
elif counts[0] == 3:
return (3, ranks) # Three of a kind
elif counts[0] == 2 and counts[1] == 2:
return (2, ranks) # Two pair
elif counts[0] == 2:
return (1, ranks) # One pair
else:
return (0, ranks) # High card
def show_hand(hand):
return '\n '.join([f"{rank} of {suit}" for rank, suit in hand])
def main():
deck = create_deck()
random.shuffle(deck)
player1 = deal_hand(deck)
player2 = deal_hand(deck)
print("Player 1's hand:\n", show_hand(player1))
print()
print("Player 2's hand:\n", show_hand(player2))
rank1 = hand_rank(player1)
rank2 = hand_rank(player2)
if rank1 > rank2:
print("Player 1 wins! with rank:", rank1)
print("Player 2 loses with rank:", rank2)
elif rank2 > rank1:
print("Player 2 wins! with rank:", rank2)
print("Player 1 loses with rank:", rank1)
else:
print("It's a tie!")
print("Both players have rank:", rank1)
if __name__ == "__main__":
main()