Compare commits

...

14 Commits

Author SHA1 Message Date
231235ba44 Final Poker Game commit 2025-09-17 11:22:48 -07:00
a30079df3b Add Royal Flush to the hand_rank 2025-09-17 11:20:00 -07:00
6b262097c3 Fixed issue where program asked for 1 more card replacement than the player had requested 2025-09-17 11:06:57 -07:00
4ee362911b Updated prompt_card_replacement function to prompt for another card if the player enters a card which is not in his hand. 2025-09-17 10:55:44 -07:00
4d45d1168e Updated Game() function to repeat user_input if player enter an invalid number of cards to be pulled. 2025-09-17 10:44:59 -07:00
6227c5b3a8 Added ranks to final play output 2025-09-17 10:32:10 -07:00
d4ace5ada1 Initial commit 2025-09-17 10:28:19 -07:00
d86423b3c5 Updated deal_card function to eliminate ValueError exception 2025-09-17 10:21:27 -07:00
eb5927a887 created pop_list function 2025-09-16 10:20:47 -07:00
7e58d59ebe Add functionality to let each player pull up to 3 cards from their hand and replace them with new cards from the deck. 2025-09-16 09:28:10 -07:00
02d551de2a Updated poker.py to fix card replacement and display hands correctly. 2025-09-16 09:16:50 -07:00
4fb57a3ff5 Add card pulling functionality for Player 2 and update hand display 2025-09-15 11:29:04 -07:00
c2d5d799fc Implement card removal functionality and update player 1's hand management 2025-09-15 11:21:40 -07:00
4a36bfdfca Changed product2 instance 2025-09-15 10:28:52 -07:00
6 changed files with 295 additions and 10 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.

128
poker.py
View File

@ -1,18 +1,48 @@
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)}
def create_deck():
return [(rank, suit) for suit in SUITS for rank in RANKS]
Card = Tuple[str, str] # ('Rank', 'Suit')
Hand = List[Card]
Deck = List[Card]
player1: Hand
player2: Hand
deck: Deck
new_card: Card
def deal_hand(deck, num=5):
def create_deck() -> Deck:
Deck = [(rank, suit) for suit in SUITS for rank in RANKS]
return Deck
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) -> 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]
@ -42,14 +72,95 @@ def hand_rank(hand):
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)
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
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 ', 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)
if success:
print(f"Replaced {rank} of {suit} with {new_card[0]} of {new_card[1]}.")
else:
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:")
print("Player 1\n", show_hand(player1))
print()
print("Player 2\n", show_hand(player2))
print()
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))
print()
def main():
deck = create_deck()
random.shuffle(deck)
random.shuffle(deck)
player1 = deal_hand(deck)
player2 = deal_hand(deck)
display_initial_hands(player1, 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
rank1 = hand_rank(player1)
rank2 = hand_rank(player2)
if rank1 > rank2:
@ -62,5 +173,6 @@ def main():
print("It's a tie!")
print("Both players have rank:", rank1)
if __name__ == "__main__":
main()

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

View File

@ -16,10 +16,10 @@ class product:
# Example usage:
product1 = product("Laptop", 1999.99, -1)
product1 = product("Laptop", 1999.99, 1)
print(product1.display_info()) # Output: Item: Laptop, Price: $1999.99
print(product1.calculate_total_price()) # Output: 3999996.0001
product2 = product("Smartphone", 799.99, 3)
product2 = product("Smartphone", 799.99, -3)
print(product2.display_info()) # Output: Item: Smartphone, Price: $799.99
print(product2.calculate_total_price()) # Output: 2399.97