杰瑞科技汇

Python poker dice 如何实现?

Of course! Here is a complete, well-commented Python implementation of the classic dice game "Poker Dice".

Python poker dice 如何实现?-图1
(图片来源网络,侵删)

This implementation includes:

  1. A Die class to represent a single die.
  2. A PokerDiceGame class to manage the game state, rolls, and scoring.
  3. A command-line interface for a player to interact with the game.
  4. Clear instructions and a user-friendly experience.

The game rules implemented are:

  • The player gets 3 rolls per turn.
  • After each roll, the player can choose to keep some dice and re-roll the others.
  • The game automatically detects the best poker hand from the final 5 dice and calculates the score.

The Code

You can copy and paste this code into a single Python file (e.g., poker_dice.py) and run it.

import random
import collections
# --- Helper Functions ---
def display_dice(dice_values):
    """Displays a list of dice values with ASCII art."""
    die_faces = {
        1: ["┌───────┐", "│       │", "│   ●   │", "│       │", "└───────┘"],
        2: ["┌───────┐", "│  ●    │", "│       │", "│    ●  │", "└───────┘"],
        3: ["┌───────┐", "│  ●    │", "│   ●   │", "│    ●  │", "└───────┘"],
        4: ["┌───────┐", "│  ●  ● │", "│       │", "│  ●  ● │", "└───────┘"],
        5: ["┌───────┐", "│  ●  ● │", "│   ●   │", "│  ●  ● │", "└───────┘"],
        6: ["┌───────┐", "│  ●  ● │", "│  ●  ● │", "│  ●  ● │", "└───────┘"],
    }
    # Transpose the rows of all dice faces to print them side-by-side
    lines = []
    for i in range(5):
        line = ""
        for value in dice_values:
            line += die_faces[value][i] + " "
        lines.append(line)
    print("\n" + "\n".join(lines))
def get_hand_name(hand_counts):
    """Determines the name of the poker hand from a dictionary of value counts."""
    # hand_counts is a dict like {5: 1} for Five of a Kind
    counts = sorted(hand_counts.values(), reverse=True)
    if counts[0] == 5:
        return "Five of a Kind"
    if counts[0] == 4:
        return "Four of a Kind"
    if counts[0] == 3 and counts[1] == 2:
        return "Full House"
    if counts[0] == 3:
        return "Three of a Kind"
    if counts[0] == 2 and counts[1] == 2:
        return "Two Pair"
    if counts[0] == 2:
        return "One Pair"
    return "High Card"
def get_hand_score(hand_counts):
    """Assigns a score to a poker hand."""
    counts = sorted(hand_counts.values(), reverse=True)
    if counts[0] == 5:
        return 1000  # Five of a Kind
    if counts[0] == 4:
        return 750   # Four of a Kind
    if counts[0] == 3 and counts[1] == 2:
        return 500   # Full House
    if counts[0] == 3:
        return 300   # Three of a Kind
    if counts[0] == 2 and counts[1] == 2:
        return 200   # Two Pair
    if counts[0] == 2:
        return 100   # One Pair
    return 0       # High Card
# --- Core Classes ---
class Die:
    """Represents a single six-sided die."""
    def __init__(self):
        self.value = random.randint(1, 6)
        self.is_kept = False
    def roll(self):
        """Rolls the die if it's not being kept."""
        if not self.is_kept:
            self.value = random.randint(1, 6)
    def __repr__(self):
        return f"D{self.value}" if self.is_kept else f"D{self.value}*"
class PokerDiceGame:
    """Manages the game logic for Poker Dice."""
    def __init__(self):
        self.dice = [Die() for _ in range(5)]
        self.rolls_left = 3
    def roll_dice(self):
        """Rolls all dice that are not being kept."""
        if self.rolls_left <= 0:
            print("No rolls left!")
            return
        print(f"\n--- Rolling Dice ({self.rolls_left} rolls left) ---")
        for die in self.dice:
            die.roll()
        self.rolls_left -= 1
        self.display_current_hand()
    def display_current_hand(self):
        """Shows the current state of the dice and the current best hand."""
        dice_values = [die.value for die in self.dice]
        display_dice(dice_values)
        hand_counts = collections.Counter(dice_values)
        hand_name = get_hand_name(hand_counts)
        hand_score = get_hand_score(hand_counts)
        print(f"\nCurrent Hand: {hand_name} (Score: {hand_score})")
    def toggle_keep_die(self, index_str):
        """Toggles the 'kept' status of a die based on user input."""
        try:
            index = int(index_str) - 1  # Convert to 0-based index
            if 0 <= index < 5:
                self.dice[index].is_kept = not self.dice[index].is_kept
                print(f"Die {index + 1} is now {'kept' if self.dice[index].is_kept else 'available to roll'}.")
            else:
                print("Invalid die number. Please choose a number from 1 to 5.")
        except ValueError:
            print("Invalid input. Please enter a number.")
    def end_turn(self):
        """Calculates and displays the final score for the turn."""
        dice_values = [die.value for die in self.dice]
        hand_counts = collections.Counter(dice_values)
        hand_name = get_hand_name(hand_counts)
        hand_score = get_hand_score(hand_counts)
        print("\n" + "="*40)
        print("        TURN OVER")
        print("="*40)
        display_dice(dice_values)
        print(f"\nFinal Hand: {hand_name}")
        print(f"Score for this turn: {hand_score}")
        print("="*40 + "\n")
        return hand_score
    def reset_turn(self):
        """Resets the game for a new turn."""
        self.dice = [Die() for _ in range(5)]
        self.rolls_left = 3
        print("\n--- New Turn Started! ---")
# --- Main Game Loop ---
def main():
    """The main function to run the Poker Dice game."""
    game = PokerDiceGame()
    print("Welcome to Python Poker Dice!")
    print("Try to get the best poker hand with 5 dice.")
    print("You have 3 rolls per turn.")
    print("After a roll, you can keep dice by typing their number (e.g., '1 3 5').")
    print("Type 'r' to roll, 'k' to toggle keep status, or 'e' to end turn.\n")
    while True:
        game.display_current_hand()
        if game.rolls_left == 0:
            # Must end turn if no rolls are left
            game.end_turn()
            game.reset_turn()
            continue
        prompt = f"\nWhat would you like to do? (r)oll, (k)eep, (e)nd turn: "
        action = input(prompt).lower().strip()
        if action == 'r':
            game.roll_dice()
        elif action == 'e':
            game.end_turn()
            game.reset_turn()
        elif action == 'k':
            print("Enter the numbers of the dice you want to toggle (e.g., '1 3' or 'all' to clear keeps):")
            die_input = input("> ").lower().strip()
            if die_input == 'all':
                for die in game.dice:
                    die.is_kept = False
                print("All dice are now available to roll.")
            else:
                try:
                    indices = [s for s in die_input.split()]
                    for idx_str in indices:
                        game.toggle_keep_die(idx_str)
                except Exception as e:
                    print(f"An error occurred: {e}. Please try again.")
        else:
            print("Invalid command. Please use 'r', 'k', or 'e'.")
if __name__ == "__main__":
    main()

How to Run the Game

  1. Save the code above as a Python file (e.g., poker_dice.py).
  2. Open a terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. Run the script using the command: python poker_dice.py

How to Play

The game will guide you through the process. Here's a summary of the controls:

Python poker dice 如何实现?-图2
(图片来源网络,侵删)
  1. Rolling: At the start of your turn or after deciding which dice to keep, type r and press Enter to roll the available dice.
  2. Keeping Dice: After a roll, you can choose to keep some dice to prevent them from being re-rolled.
    • Type k and press Enter.
    • The game will then ask you which dice to toggle. Enter the numbers of the dice you want to keep (e.g., 1 3 5 to keep dice 1, 3, and 5).
    • A die marked with an asterisk (D6*) is available to roll. A die without one (D6) is being kept.
    • You can type all to clear all kept dice and make them all available for the next roll.
  3. Ending the Turn: When you are satisfied with your hand or have no rolls left, type e and press Enter. The game will reveal your final hand, its name (e.g., "Full House"), and its score. A new turn will then automatically begin.

Scoring System

The game scores hands based on their poker value:

  • Five of a Kind: 1000 points
  • Four of a Kind: 750 points
  • Full House: 500 points
  • Three of a Kind: 300 points
  • Two Pair: 200 points
  • One Pair: 100 points
  • High Card: 0 points
Python poker dice 如何实现?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇