Compare commits

..

10 Commits

5 changed files with 257 additions and 31 deletions

15
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}

Binary file not shown.

111
poker.py
View File

@ -11,20 +11,38 @@ Deck = List[Card]
player1: Hand
player2: Hand
deck: Deck
new_card: Card
def create_deck():
deck: Deck = [(rank, suit) for suit in SUITS for rank in RANKS]
return deck
def create_deck() -> Deck:
Deck = [(rank, suit) for suit in SUITS for rank in RANKS]
return Deck
def deal_card(deck):
return deck.pop()
def deal_card(deck) -> Card:
pull_card = deck.pop(0)
print("DEBUG - Dealt card:", pull_card)
return pull_card
def deal_hand(deck, num=5):
def deal_hand(deck, num=5) -> Hand:
hand = random.sample(deck, num)
for card in hand:
deck.remove(card)
return hand
def pop_list(lst: List, index: int) -> Tuple:
"""Removes and returns the element at the specified index from the list."""
if index < 0:
raise IndexError("Index out of range")
element = lst[index]
lst.remove(element)
return element
def card_in_hand(card: Card, hand: Hand) -> bool:
rank, suit = card
for r, s in hand:
if r.strip().upper() == rank.strip().upper() and s.strip().capitalize() == suit.strip().capitalize():
return True
return False
def hand_rank(hand):
ranks = sorted([RANK_VALUES[card[0]] for card in hand], reverse=True)
suits = [card[1] for card in hand]
@ -54,34 +72,48 @@ def hand_rank(hand):
def show_hand(hand):
return '\n '.join([f"{rank} of {suit}" for rank, suit in hand])
def replace_card_from_hand(hand, card, new_card) -> bool:
if card in hand:
hand.remove(card)
hand.append(new_card)
def replace_card_from_hand(hand: Hand, card: Card, new_card: Card) -> bool:
for i, existing_card in enumerate(hand):
if existing_card[0].strip().upper() == card[0].strip().upper() and \
existing_card[1].strip().capitalize() == card[1].strip().capitalize():
hand[i] = new_card
return True
return False
def handle_player_input(hand):
user_input = input("Player, enter a card to pull from your hand (e.g., 'A of Spades', or 'none'): ").strip()
if 'none' in user_input.lower():
print("No card pulled.")
def handle_player_input(hand: Hand, deck: Deck) -> None:
user_input = input("Enter a card to pull from your hand (e.g., A of Spades): ").strip()
print("DEBUG - Current hand:", hand)
# Basic format check
if ' of ' not in user_input:
print("Invalid input format. Please use Rank of Suit.")
return
try:
rank, suit = user_input.split(' of ')
card_to_replace = (rank.strip().upper(), suit.strip().capitalize())
new_card = deal_card(deck) # Example new card from the deck
rank, suit = user_input.split(' of ', 1)
rank = rank.strip().upper()
suit = suit.strip().capitalize()
card = (rank, suit)
print("DEBUG - Attempting to remove:", card)
if not card_in_hand(card, hand):
print("DEBUG - Normalized input:", card)
print("DEBUG - Hand contents:", hand)
print(f"Card '{rank} of {suit}' not found in your hand.")
return
if not deck:
print("No more cards left in the deck to draw.")
return
new_card = deal_card(deck)
success = replace_card_from_hand(hand, card, new_card)
success = replace_card_from_hand(hand, card_to_replace, new_card)
print(success)
if success:
print(f"Player 1 pulled {rank} of {suit} from their hand.")
print(f"Player 1 received new card: {new_card[0]} of {new_card[1]}")
print(f"Replaced {rank} of {suit} with {new_card[0]} of {new_card[1]}.")
else:
print("Card not found in Player 1's hand.")
except ValueError:
print("Invalid input format. Please use 'Rank of Suit'.")
print("Card replacement failed unexpectedly.")
except Exception as e:
print(f"Unexpected error: {e}")
def display_initial_hands(player1: Hand, player2: Hand):
print("\nPlayer's hands:")
@ -90,8 +122,8 @@ def display_initial_hands(player1: Hand, player2: Hand):
print("Player 2\n", show_hand(player2))
print()
def display_hands(player1, player2):
print("\nAfter pulling cards:")
def display_hands(player1: Hand, player2: Hand):
print("\nPlayer's current hands:")
print("Player 1's hand:\n", show_hand(player1))
print()
print("Player 2's hand:\n", show_hand(player2))
@ -100,11 +132,32 @@ def display_hands(player1, player2):
def main():
deck = create_deck()
random.shuffle(deck)
random.shuffle(deck)
player1 = deal_hand(deck)
player2 = deal_hand(deck)
display_initial_hands(player1, player2)
handle_player_input(player1)
handle_player_input(player2)
print("Player 1's turn to pull a card.")
p1_num = int(input("How many cards do you want to pull? (0-3): "))
if p1_num < 0 or p1_num > 3:
print("Invalid number of cards. Please choose between 0 and 3.")
return
elif p1_num != 0:
for _ in range(p1_num):
handle_player_input(player1, deck)
else:
print("Player 1 chose not to pull any cards.")
display_hands(player1, player2)
print("Player 2's turn to pull a card.")
p2_num = int(input("How many cards do you want to pull? (0-3): "))
if p2_num < 0 or p2_num > 3:
print("Invalid number of cards. Please choose between 0 and 3.")
return
elif p2_num != 0:
for _ in range(p2_num):
handle_player_input(player2, deck)
else:
print("Player 2 chose not to pull any cards.")
display_hands(player1, player2)
# Evaluate hands and determine winner

146
poker_class_version.py Normal file
View File

@ -0,0 +1,146 @@
import random
from typing import List, Tuple
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)}
class Card:
def __init__(self, rank: str, suit: str):
self.rank = rank.strip().upper()
self.suit = suit.strip().capitalize()
def __repr__(self):
return f"{self.rank} of {self.suit}"
def __eq__(self, other):
return isinstance(other, Card) and self.rank == other.rank and self.suit == other.suit
class Deck:
def __init__(self):
self.cards: List[Card] = [Card(rank, suit) for suit in SUITS for rank in RANKS]
random.shuffle(self.cards)
def deal_card(self) -> Card:
return self.cards.pop(0)
def deal_hand(self, num: int = 5) -> List[Card]:
hand = self.cards[:num]
del self.cards[:num]
return hand
class Player:
def __init__(self, name: str, deck: Deck):
self.name = name
self.hand: List[Card] = deck.deal_hand()
def show_hand(self):
return '\n '.join(str(card) for card in self.hand)
def replace_card(self, old_card: Card, new_card: Card) -> bool:
for i, card in enumerate(self.hand):
if card == old_card:
self.hand[i] = new_card
return True
return False
def hand_rank(self) -> Tuple[int, List[int]]:
ranks = sorted([RANK_VALUES[card.rank] for card in self.hand], reverse=True)
suits = [card.suit for card in self.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))
# Handle Ace-low straight
if ranks == [14, 5, 4, 3, 2]:
is_straight = True
ranks = [5, 4, 3, 2, 1]
if is_flush and ranks == [14, 13, 12, 11, 10]:
return (9, ranks) # Royal Flush
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
class Game:
def __init__(self):
self.deck = Deck()
self.player1 = Player("Player 1", self.deck)
self.player2 = Player("Player 2", self.deck)
def prompt_card_replacement(self, player: Player):
while True:
try:
num = int(input(f"{player.name}, how many cards do you want to pull? (03): "))
if 0 <= num <= 3:
break
else:
print("Invalid number. Please choose between 0 and 3.")
except ValueError:
print("Invalid input. Please enter a number between 0 and 3.")
replacements_done = 0
while replacements_done < num:
print("\nYour current hand:\n", player.show_hand())
user_input = input("Enter a card to replace (e.g., A of Spades): ").strip()
if ' of ' not in user_input:
print("Invalid format. Use 'Rank of Suit'.")
continue
rank, suit = user_input.split(' of ', 1)
old_card = Card(rank, suit)
if old_card not in player.hand:
print(f"{old_card} not found in your hand. Please try again.")
continue
new_card = self.deck.deal_card()
if player.replace_card(old_card, new_card):
print(f"Replaced {old_card} with {new_card}")
replacements_done += 1
else:
print("Replacement failed unexpectedly.")
def play(self):
print("Initial hands:")
print("Player 1:\n", self.player1.show_hand())
print("Player 2:\n", self.player2.show_hand())
self.prompt_card_replacement(self.player1)
self.prompt_card_replacement(self.player2)
rank1 = self.player1.hand_rank()
rank2 = self.player2.hand_rank()
print("\nFinal hands:")
print("Player 1:\n", self.player1.show_hand())
print("Player 2:\n", self.player2.show_hand())
if rank1 > rank2:
print("Player 1 wins!", rank1)
elif rank2 > rank1:
print("Player 2 wins!", rank2)
else:
print("It's a tie!")
if __name__ == "__main__":
Game().play()

12
pop_list.py Normal file
View File

@ -0,0 +1,12 @@
from typing import List, Tuple
Card = Tuple[str, str] # ('Rank', 'Suit')
Hand = List[Card]
def pop_list(lst: List, index: int) -> Tuple:
"""Removes and returns the element at the specified index from the list."""
if index < 0 or index >= len(lst):
raise IndexError("Index out of range")
element = lst[index]
lst.remove(element)
return element