杰瑞科技汇

Python加密轮盘如何实现?

Of course! A "crypto wheel" in Python is a fantastic project for learning about data structures, user interaction, and probability. It simulates the classic "Wheel of Fortune" game, but instead of "Bankrupt" or "Lose a Turn," the segments contain various cryptocurrencies.

Python加密轮盘如何实现?-图1
(图片来源网络,侵删)

Let's build this step-by-step, starting with a simple command-line version and then moving to a more visual one using a popular library.


Part 1: The Simple Command-Line Wheel

This version is great for beginners. It uses a list to represent the wheel segments and random.choice to "spin" it.

The Code

import random
import time
# --- 1. Define the Wheel Segments ---
# We'll use a list of tuples. Each tuple contains (name, value).
# The value could be a prize, a multiplier, or a special action.
crypto_wheel = [
    ("Bitcoin (BTC)", "$100"),
    ("Ethereum (ETH)", "$50"),
    ("Cardano (ADA)", "x2 Multiplier"),
    ("Solana (SOL)", "$75"),
    ("Dogecoin (DOGE)", "$25"),
    ("Ripple (XRP)", "x3 Multiplier"),
    ("Polkadot (DOT)", "$150"),
    ("Avalanche (AVAX)", "x2 Multiplier"),
    ("Chainlink (LINK)", "$200"),
    ("Polygon (MATIC)", "$10"),
    ("Litecoin (LTC)", "x5 Multiplier"),
    ("BANKRUPT", "0")
]
# --- 2. The Spinning Logic ---
def spin_wheel():
    """
    Simulates spinning the wheel and returns the selected segment.
    """
    print("\n--- Spinning the wheel... ---")
    time.sleep(1) # Add a little suspense
    # Use random.choice to pick one item from our list
    result = random.choice(crypto_wheel)
    # Unpack the tuple for easier access
    crypto_name, prize = result
    print(f"The wheel is spinning...")
    time.sleep(1)
    print(f"...and it lands on...")
    time.sleep(0.5)
    print(f"*** {crypto_name}! ***")
    time.sleep(0.5)
    print(f"You win: {prize}!")
    return result
# --- 3. Main Game Loop ---
def main():
    """Main function to run the crypto wheel game."""
    print("Welcome to the Python Crypto Wheel!")
    print("=====================================")
    while True:
        # Ask the user if they want to spin
        user_input = input("\nPress Enter to spin the wheel (or type 'quit' to exit): ").lower()
        if user_input == 'quit':
            print("Thanks for playing! Goodbye!")
            break
        elif user_input == '':
            spin_wheel()
        else:
            print("Invalid input. Press Enter to spin.")
# This line ensures the main() function is called only when the script is executed directly
if __name__ == "__main__":
    main()

How to Run It

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

Part 2: The Visual GUI Wheel with Pygame

For a more impressive and realistic wheel, we can use the Pygame library. This will draw the wheel, animate the spin, and show a pointer.

Step 1: Install Pygame

If you don't have it installed, open your terminal or command prompt and run:

Python加密轮盘如何实现?-图2
(图片来源网络,侵删)
pip install pygame

Step 2: The Visual Wheel Code

This code is more complex but much more rewarding. It draws the wheel, calculates segment angles, animates the spin, and detects where it stops.

import pygame
import sys
import math
import random
# --- Constants ---
WIDTH, HEIGHT = 800, 800
CENTER = (WIDTH // 2, HEIGHT // 2)
RADIUS = 300
FPS = 60
# --- Colors ---
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GOLD = (218, 165, 32)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
BLUE = (0, 0, 200)
COLORS = [RED, GREEN, BLUE, (255, 165, 0), (128, 0, 128), (0, 255, 255), (255, 192, 203)]
# --- Wheel Data ---
# Each item is a tuple: (name, value, color)
crypto_segments = [
    ("Bitcoin (BTC)", "$100", COLORS[0]),
    ("Ethereum (ETH)", "$50", COLORS[1]),
    ("Cardano (ADA)", "x2 Multiplier", COLORS[2]),
    ("Solana (SOL)", "$75", COLORS[3]),
    ("Dogecoin (DOGE)", "$25", COLORS[4]),
    ("Ripple (XRP)", "x3 Multiplier", COLORS[5]),
    ("Polkadot (DOT)", "$150", COLORS[6]),
    ("Avalanche (AVAX)", "x2 Multiplier", COLORS[0]),
    ("Chainlink (LINK)", "$200", COLORS[1]),
    ("Polygon (MATIC)", "$10", COLORS[2]),
    ("Litecoin (LTC)", "x5 Multiplier", COLORS[3]),
    ("BANKRUPT", "0", RED)
]
class Wheel:
    def __init__(self, segments, center, radius):
        self.segments = segments
        self.center = center
        self.radius = radius
        self.angle = 0  # Current rotation angle
        self.spinning = False
        self.spin_speed = 0
        self.font = pygame.font.SysFont('Arial', 24, bold=True)
        self.small_font = pygame.font.SysFont('Arial', 16)
    def draw(self, screen):
        # Draw each segment
        num_segments = len(self.segments)
        angle_per_segment = (2 * math.pi) / num_segments
        for i, (name, value, color) in enumerate(self.segments):
            start_angle = i * angle_per_segment + self.angle
            end_angle = (i + 1) * angle_per_segment + self.angle
            # Draw the segment (a polygon)
            points = [self.center]
            for a in range(int(math.degrees(start_angle)), int(math.degrees(end_angle)) + 1):
                x = self.center[0] + self.radius * math.cos(math.radians(a))
                y = self.center[1] + self.radius * math.sin(math.radians(a))
                points.append((x, y))
            pygame.draw.polygon(screen, color, points)
            pygame.draw.polygon(screen, BLACK, points, 3) # Draw border
            # Draw text
            text_angle = start_angle + angle_per_segment / 2
            text_radius = self.radius * 0.65
            text_x = self.center[0] + text_radius * math.cos(text_angle)
            text_y = self.center[1] + text_radius * math.sin(text_angle)
            # Create a surface for the text to allow for rotation
            text_surface = self.small_font.render(name, True, WHITE)
            text_rect = text_surface.get_rect(center=(text_x, text_y))
            # Rotate text to be readable
            angle_deg = math.degrees(text_angle) - 90
            rotated_text = pygame.transform.rotate(text_surface, -angle_deg)
            rotated_rect = rotated_text.get_rect(center=text_rect.center)
            screen.blit(rotated_text, rotated_rect)
        # Draw the center circle
        pygame.draw.circle(screen, BLACK, self.center, 30)
        pygame.draw.circle(screen, GOLD, self.center, 25)
    def spin(self):
        if not self.spinning:
            self.spinning = True
            # Random spin speed and duration
            self.spin_speed = random.uniform(15, 25) # Radians per second
            # Calculate how long to spin (e.g., 3-6 full rotations)
            spin_duration = random.uniform(3, 6) * 2 * math.pi
            self.target_angle = self.angle + spin_duration
    def update(self, dt):
        if self.spinning:
            self.angle += self.spin_speed * dt
            # Slow down the spin over time (friction)
            self.spin_speed *= 0.985
            # Stop spinning when speed is very low
            if self.spin_speed < 0.1:
                self.spinning = False
                self.spin_speed = 0
                # Normalize angle to be between 0 and 2*pi
                self.angle = self.angle % (2 * math.pi)
                return self.get_winning_segment()
        return None
    def get_winning_segment(self):
        # The pointer is at the top (angle -pi/2).
        # The wheel's rotation is 'self.angle'.
        # The effective angle of the first segment is -self.angle.
        # We need to find which segment the top pointer is pointing to.
        # Normalize the angle to be positive
        normalized_angle = (2 * math.pi - (self.angle % (2 * math.pi))) % (2 * math.pi)
        num_segments = len(self.segments)
        angle_per_segment = (2 * math.pi) / num_segments
        # Calculate the segment index
        segment_index = int(normalized_angle / angle_per_segment)
        return self.segments[segment_index]
def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Python Crypto Wheel")
    clock = pygame.time.Clock()
    wheel = Wheel(crypto_segments, CENTER, RADIUS)
    result_text = ""
    show_result = False
    while True:
        dt = clock.tick(FPS) / 1000.0  # Delta time in seconds
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and not wheel.spinning:
                    wheel.spin()
                    show_result = False # Hide previous result
            if event.type == pygame.MOUSEBUTTONDOWN and not wheel.spinning:
                wheel.spin()
                show_result = False # Hide previous result
        # Update wheel physics
        winning_segment = wheel.update(dt)
        if winning_segment and not wheel.spinning and not show_result:
            result_text = f"You won: {winning_segment[1]} ({winning_segment[0]})"
            show_result = True
        # Drawing
        screen.fill(WHITE)
        wheel.draw(screen)
        # Draw pointer
        pygame.draw.polygon(screen, BLACK, [
            (CENTER[0], CENTER[1] - RADIUS - 20),
            (CENTER[0] - 15, CENTER[1] - RADIUS + 10),
            (CENTER[0] + 15, CENTER[1] - RADIUS + 10)
        ])
        # Draw result text
        if show_result:
            result_surface = wheel.font.render(result_text, True, BLACK)
            result_rect = result_surface.get_rect(center=(WIDTH // 2, HEIGHT - 50))
            pygame.draw.rect(screen, WHITE, result_rect.inflate(20, 10))
            pygame.draw.rect(screen, BLACK, result_rect.inflate(20, 10), 2)
            screen.blit(result_surface, result_rect)
        # Draw instructions
        inst_surface = wheel.small_font.render("Press SPACE or Click to Spin", True, BLACK)
        inst_rect = inst_surface.get_rect(center=(WIDTH // 2, 30))
        screen.blit(inst_surface, inst_rect)
        pygame.display.flip()
if __name__ == "__main__":
    main()

How to Run It

  1. Make sure you have pygame installed (pip install pygame).
  2. Save the code as visual_crypto_wheel.py.
  3. Run it from your terminal: python visual_crypto_wheel.py
  4. Press the Spacebar or Click the mouse to spin the wheel!

Next Steps and Improvements

This is a great starting point. Here’s how you could make it even better:

  1. Sound Effects: Add sounds for the spinning, a "click" when it stops, and a victory fanfare using pygame.mixer.
  2. Player Management: Keep track of a player's total winnings. Add "Bankrupt" and "Lose a Turn" segments that affect the player's score.
  3. Better Graphics: Load actual crypto logos from image files and draw them onto the wheel segments instead of just text.
  4. Different Modes: Create a "bonus round" where only high-value segments are on the wheel.
  5. A More Realistic Physics Model: Instead of just slowing down, you could model acceleration and deceleration for a more natural feel.
分享:
扫描分享到社交APP
上一篇
下一篇