Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

import pygame import sys import time from pygame.locals import * import math…

  1. User

    import pygame import sys import time from pygame.locals import * import math

    Initialisiere Pygame

    pygame.init()

    Fenstergröße

    WIDTH, HEIGHT = 800, 600 WINDOW = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Bombenentwaffnungs-Spiel")

    Farben

    BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (200, 0, 0) GREEN = (0, 200, 0) DARK_RED = (150, 0, 0) DARK_GREEN = (0, 150, 0) GRAY = (50, 50, 50) SEGMENT_ON = (0, 255, 0) SEGMENT_OFF = (20, 20, 20)

    Schriftarten

    FONT = pygame.font.SysFont('Courier', 30) LCD_FONT = pygame.font.SysFont('Courier', 40, bold=True)

    Timer-Einstellungen

    TOTAL_TIME = 180 # Sekunden (3 Minuten)

    Geheimcode (Beispiel: "1234")

    SECRET_CODE = "1234"

    Zahlenfeld-Einstellungen

    NUM_PAD = [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['CLR', '0', 'ENT'] ]

    BUTTON_WIDTH, BUTTON_HEIGHT = 100, 60 BUTTON_PADDING = 20 START_X = (WIDTH - (3 * BUTTON_WIDTH + 2 * BUTTON_PADDING)) // 2 START_Y = HEIGHT - (4 * (BUTTON_HEIGHT + BUTTON_PADDING)) - 50

    Spielstatus

    STATUS_COUNTDOWN = 0 STATUS_EXPLOSION = 1

    Explosion-Einstellungen

    EXPLOSION_DURATION = 2 # Sekunden

    7-Segment-Display Konfiguration

    SEGMENT_LENGTH = 40 SEGMENT_WIDTH = 10 SEGMENTS = { 'A': ((20, 0), (60, 0), (50, 10), (30, 10)), 'B': ((60, 0), (70, 10), (70, 50), (60, 40)), 'C': ((60, 60), (70, 70), (70, 110), (60, 100)), 'D': ((20, 100), (60, 100), (50, 110), (30, 110)), 'E': ((10, 60), (20, 70), (20, 110), (10, 100)), 'F': ((10, 0), (20, 10), (20, 50), (10, 40)), 'G': ((20, 50), (60, 50), (50, 60), (30, 60)), }

    Jede Ziffer definiert, welche Segmente an sind

    DIGITS = { '0': ['A', 'B', 'C', 'D', 'E', 'F'], '1': ['B', 'C'], '2': ['A', 'B', 'G', 'E', 'D'], '3': ['A', 'B', 'G', 'C', 'D'], '4': ['F', 'G', 'B', 'C'], '5': ['A', 'F', 'G', 'C', 'D'], '6': ['A', 'F', 'G', 'C', 'D', 'E'], '7': ['A', 'B', 'C'], '8': ['A', 'B', 'C', 'D', 'E', 'F', 'G'], '9': ['A', 'B', 'C', 'D', 'F', 'G'], ':': [] # Für die Trenner zwischen Minuten und Sekunden }

    def draw_segment(surface, segment, position, color): """Zeichnet ein einzelnes Segment an der gegebenen Position.""" translated = [ (x + position[0], y + position[1]) for (x, y) in segment ] pygame.draw.polygon(surface, color, translated)

    def draw_digit(surface, digit, top_left): """Zeichnet eine einzelne Ziffer im 7-Segment-Stil.""" if digit not in DIGITS: digit = ' ' # Leerer Raum für unbekannte Zeichen

    # Zeichenbereich
    digit_surface = pygame.Surface((80, 120), pygame.SRCALPHA)
    digit_surface.fill(BLACK)
    
    # Zeichne Segmente
    for seg in SEGMENTS:
        if seg in DIGITS[digit]:
            color = SEGMENT_ON
        else:
            color = SEGMENT_OFF
        draw_segment(digit_surface, SEGMENTS[seg], (0, 0), color)
    
    surface.blit(digit_surface, top_left)
    

    def draw_lcd_time(surface, time_str, pos): """Zeichnet die Zeit als 7-Segment-LCD.""" x, y = pos for char in time_str: if char == ':': # Zeichne einen einfachen Punkt als Trenner pygame.draw.circle(surface, SEGMENT_ON, (x + 40, y + 60), 5) x += 20 # Platz zwischen den Zeichen continue draw_digit(surface, char, (x, y)) x += 80 # Abstand zwischen den Ziffern

    def draw_buttons(): """Zeichnet das Zahlenfeld.""" for row_idx, row in enumerate(NUM_PAD): for col_idx, label in enumerate(row): x = START_X + col_idx * (BUTTON_WIDTH + BUTTON_PADDING) y = START_Y + row_idx * (BUTTON_HEIGHT + BUTTON_PADDING) rect = pygame.Rect(x, y, BUTTON_WIDTH, BUTTON_HEIGHT) pygame.draw.rect(WINDOW, GRAY, rect, border_radius=5) # Button-Text if label in ['CLR', 'ENT']: text_color = RED if label == 'CLR' else GREEN else: text_color = WHITE text = FONT.render(label, True, text_color) text_rect = text.get_rect(center=rect.center) WINDOW.blit(text, text_rect) # Eingabefeld input_rect = pygame.Rect(START_X, START_Y - 100, 3 * BUTTON_WIDTH + 2 * BUTTON_PADDING, 60) pygame.draw.rect(WINDOW, GRAY, input_rect, border_radius=5) prompt_text = FONT.render("Code (4):", True, WHITE) WINDOW.blit(prompt_text, (input_rect.x + 10, input_rect.y + 10)) input_text = FONT.render(current_input, True, WHITE) WINDOW.blit(input_text, (input_rect.x + 120, input_rect.y + 10))

    def show_explosion(): """Einfache Explosion-Animation.""" start_time = time.time() while time.time() - start_time < EXPLOSION_DURATION: elapsed = time.time() - start_time WINDOW.fill(BLACK) # Explosion-Kreise vergrößern sich und verblassen alpha = max(255 - int((elapsed / EXPLOSION_DURATION) * 255), 0) explosion_color = (255, alpha, 0) for i in range(1, 6): radius = int(50 + i * 40 + elapsed * 200) if radius > max(WIDTH, HEIGHT): continue temp_surface = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA) pygame.draw.circle(temp_surface, explosion_color, (WIDTH//2, HEIGHT//2), radius) WINDOW.blit(temp_surface, (0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.time.delay(30)

    def reset_game(): global countdown, current_input, status countdown = TOTAL_TIME current_input = "" status = STATUS_COUNTDOWN

    Initialisiere Spielvariablen

    countdown = TOTAL_TIME current_input = "" status = STATUS_COUNTDOWN last_tick = time.time()

    Hauptspiel-Schleife

    while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN and status == STATUS_COUNTDOWN: mouse_x, mouse_y = event.pos # Überprüfe, ob eine der Tasten gedrückt wurde for row_idx, row in enumerate(NUM_PAD): for col_idx, label in enumerate(row): x = START_X + col_idx * (BUTTON_WIDTH + BUTTON_PADDING) y = START_Y + row_idx * (BUTTON_HEIGHT + BUTTON_PADDING) rect = pygame.Rect(x, y, BUTTON_WIDTH, BUTTON_HEIGHT) if rect.collidepoint(mouse_x, mouse_y): if label == 'CLR': current_input = "" elif label == 'ENT': if len(current_input) == 4: if current_input == SECRET_CODE: # Code korrekt print("Code korrekt! Countdown gestoppt.") # Option: Stoppe den Countdown oder setze ein Flag # Hier setzen wir den Countdown auf unendlich countdown = float('inf') else: # Falscher Code show_explosion() reset_game() else: if len(current_input) < 4: current_input += label break

    if status == STATUS_COUNTDOWN:
        # Aktualisiere den Countdown jede Sekunde
        current_time = time.time()
        if current_time - last_tick >= 1:
            countdown -= 1
            last_tick = current_time
            if countdown <= 0:
                # Zeit abgelaufen
                show_explosion()
                reset_game()
        # Zeichne den Bildschirm
        WINDOW.fill(BLACK)
        # Zeichne den Countdown
        minutes = countdown // 60
        seconds = countdown % 60
        time_str = f"{minutes:02}:{seconds:02}"
        draw_lcd_time(WINDOW, time_str, (WIDTH//2 - 160, 50))
        # Zeichne das Zahlenfeld und Eingabefeld
        draw_buttons()
    elif status == STATUS_EXPLOSION:
        show_explosion()
        reset_game()
    
    pygame.display.flip()
    pygame.time.Clock().tick(30)  # 30 FPS
    

    Optimize above code to make an uncluttered, more modern ui without elements overlaying echa other. Dith the (4) and display the missing input numbers as underscores.

  2. Assistant

    Certainly! Let's optimize your Pygame "Bombenentwaffnungs-Spiel" to feature a more modern and uncluttered user interface. We'll address the following enhancements:

    1. Modern UI Design:

      • Simplify Colors: Use a cohesive color scheme with softer tones.
      • Improve Layout: Ensure elements are well-spaced and aligned.
      • Enhance Fonts: Utilize more contemporary fonts for better readability.
    2. Input Display Enhancement:

      • Underscores for Missing Digits: Instead of displaying "Code (4):", we'll show "Code: _ _ _ _" and update the underscores as the user inputs numbers.
    3. Avoid Overlapping Elements:

      • Responsive Design: Adjust positions dynamically to prevent overlapping, especially on different screen sizes.
      • Clear Separation: Ensure buttons and display areas are distinctly separated.

    Here's the optimized code with these improvements:

    import pygame
    import sys
    import time
    from pygame.locals import *
    import math
    
    # Initialize Pygame
    pygame.init()
    
    # Window settings
    WIDTH, HEIGHT = 800, 600
    WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Bombenentwaffnungs-Spiel")
    
    # Colors (modern, cohesive palette)
    BLACK = (18, 18, 18)
    WHITE = (255, 255, 255)
    RED = (230, 57, 70)
    GREEN = (46, 204, 113)
    GRAY = (52, 73, 94)
    DARK_GRAY = (44, 62, 80)
    LIGHT_GRAY = (149, 165, 166)
    SEGMENT_ON = (46, 204, 113)
    SEGMENT_OFF = (108, 122, 137)
    
    # Fonts
    FONT = pygame.font.SysFont('Arial', 24)
    LCD_FONT = pygame.font.SysFont('Digital-7 Mono', 48, bold=True)  # Requires Digital-7 Mono installed
    
    # Timer settings
    TOTAL_TIME = 180  # Seconds (3 minutes)
    
    # Secret code (example: "1234")
    SECRET_CODE = "1234"
    
    # Number pad settings
    NUM_PAD = [
        ['1', '2', '3'],
        ['4', '5', '6'],
        ['7', '8', '9'],
        ['CLR', '0', 'ENT']
    ]
    
    BUTTON_WIDTH, BUTTON_HEIGHT = 80, 60
    BUTTON_PADDING = 15
    NUM_COLS = 3
    NUM_ROWS = 4
    NUM_PAD_WIDTH = NUM_COLS * BUTTON_WIDTH + (NUM_COLS - 1) * BUTTON_PADDING
    NUM_PAD_HEIGHT = NUM_ROWS * BUTTON_HEIGHT + (NUM_ROWS - 1) * BUTTON_PADDING
    START_X = (WIDTH - NUM_PAD_WIDTH) // 2
    START_Y = HEIGHT - NUM_PAD_HEIGHT - 80
    
    # Game statuses
    STATUS_COUNTDOWN = 0
    STATUS_EXPLOSION = 1
    
    # Explosion settings
    EXPLOSION_DURATION = 2  # Seconds
    
    # 7-Segment Display Configuration (Optional: Can be replaced with a modern digital display)
    SEGMENT_LENGTH = 40
    SEGMENT_WIDTH = 10
    SEGMENTS = {
        'A': ((20, 0), (60, 0), (50, 10), (30, 10)),
        'B': ((60, 0), (70, 10), (70, 50), (60, 40)),
        'C': ((60, 60), (70, 70), (70, 110), (60, 100)),
        'D': ((20, 100), (60, 100), (50, 110), (30, 110)),
        'E': ((10, 60), (20, 70), (20, 110), (10, 100)),
        'F': ((10, 0), (20, 10), (20, 50), (10, 40)),
        'G': ((20, 50), (60, 50), (50, 60), (30, 60)),
    }
    
    DIGITS = {
        '0': ['A', 'B', 'C', 'D', 'E', 'F'],
        '1': ['B', 'C'],
        '2': ['A', 'B', 'G', 'E', 'D'],
        '3': ['A', 'B', 'G', 'C', 'D'],
        '4': ['F', 'G', 'B', 'C'],
        '5': ['A', 'F', 'G', 'C', 'D'],
        '6': ['A', 'F', 'G', 'C', 'D', 'E'],
        '7': ['A', 'B', 'C'],
        '8': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
        '9': ['A', 'B', 'C', 'D', 'F', 'G'],
        ':': []
    }
    
    def draw_segment(surface, segment, position, color):
        """Draw a single segment at the given position."""
        translated = [(x + position[0], y + position[1]) for (x, y) in segment]
        pygame.draw.polygon(surface, color, translated)
    
    def draw_digit(surface, digit, top_left):
        """Draw a single digit in 7-segment style."""
        if digit not in DIGITS:
            return  # Skip unknown characters
    
        # Draw segments
        for seg in SEGMENTS:
            if seg in DIGITS[digit]:
                color = SEGMENT_ON
            else:
                color = SEGMENT_OFF
            draw_segment(surface, SEGMENTS[seg], top_left, color)
    
    def draw_lcd_time(surface, time_str, pos):
        """Draw the time as a 7-segment LCD."""
        x, y = pos
        for char in time_str:
            if char == ':':
                # Draw a simple dot as a separator
                pygame.draw.circle(surface, SEGMENT_ON, (x + 40, y + 60), 5)
                x += 30  # Space between characters
                continue
            draw_digit(surface, char, (x, y))
            x += 80  # Space between digits
    
    def draw_buttons():
        """Draw the number pad and input field."""
        # Draw input field background
        input_width = WIDTH - 100
        input_height = 60
        input_x = 50
        input_y = 50
        pygame.draw.rect(WINDOW, DARK_GRAY, (input_x, input_y, input_width, input_height), border_radius=10)
    
        # Input prompt
        prompt_text = FONT.render("Code:", True, WHITE)
        WINDOW.blit(prompt_text, (input_x + 20, input_y + 15))
    
        # Display input with underscores for missing digits
        display_input = ""
        for i in range(4):
            if i < len(current_input):
                display_input += current_input[i] + " "
            else:
                display_input += "_ "
        input_text = FONT.render(display_input.strip(), True, WHITE)
        WINDOW.blit(input_text, (input_x + 100, input_y + 15))
    
        # Draw the number pad buttons
        for row_idx, row in enumerate(NUM_PAD):
            for col_idx, label in enumerate(row):
                x = START_X + col_idx * (BUTTON_WIDTH + BUTTON_PADDING)
                y = START_Y + row_idx * (BUTTON_HEIGHT + BUTTON_PADDING)
                rect = pygame.Rect(x, y, BUTTON_WIDTH, BUTTON_HEIGHT)
                pygame.draw.rect(WINDOW, GRAY, rect, border_radius=10)
    
                # Button label
                if label == 'CLR':
                    text = FONT.render(label, True, RED)
                elif label == 'ENT':
                    text = FONT.render(label, True, GREEN)
                else:
                    text = FONT.render(label, True, BLACK)
                text_rect = text.get_rect(center=rect.center)
                WINDOW.blit(text, text_rect)
    
    def show_explosion():
        """Simple explosion animation."""
        start_time = time.time()
        while time.time() - start_time < EXPLOSION_DURATION:
            elapsed = time.time() - start_time
            WINDOW.fill(BLACK)
            # Explosion circles expanding and fading
            alpha = max(255 - int((elapsed / EXPLOSION_DURATION) * 255), 0)
            explosion_color = (255, alpha, 0)
            for i in range(1, 6):
                radius = int(50 + i * 40 + elapsed * 200)
                if radius > max(WIDTH, HEIGHT):
                    continue
                temp_surface = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
                pygame.draw.circle(temp_surface, explosion_color, (WIDTH//2, HEIGHT//2), radius)
                WINDOW.blit(temp_surface, (0, 0))
            pygame.display.flip()
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
            pygame.time.delay(30)
    
    def reset_game():
        """Reset game variables."""
        global countdown, current_input, status
        countdown = TOTAL_TIME
        current_input = ""
        status = STATUS_COUNTDOWN
    
    # Initialize game variables
    countdown = TOTAL_TIME
    current_input = ""
    status = STATUS_COUNTDOWN
    last_tick = time.time()
    
    # Main game loop
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONDOWN and status == STATUS_COUNTDOWN:
                mouse_x, mouse_y = event.pos
                # Check if a button was pressed
                for row_idx, row in enumerate(NUM_PAD):
                    for col_idx, label in enumerate(row):
                        x = START_X + col_idx * (BUTTON_WIDTH + BUTTON_PADDING)
                        y = START_Y + row_idx * (BUTTON_HEIGHT + BUTTON_PADDING)
                        rect = pygame.Rect(x, y, BUTTON_WIDTH, BUTTON_HEIGHT)
                        if rect.collidepoint(mouse_x, mouse_y):
                            if label == 'CLR':
                                current_input = ""
                            elif label == 'ENT':
                                if len(current_input) == 4:
                                    if current_input == SECRET_CODE:
                                        # Correct code
                                        print("Code korrekt! Countdown gestoppt.")
                                        countdown = float('inf')  # Stop the countdown
                                    else:
                                        # Incorrect code
                                        show_explosion()
                                        reset_game()
                            else:
                                if len(current_input) < 4 and label.isdigit():
                                    current_input += label
                            break
    
        if status == STATUS_COUNTDOWN:
            # Update the countdown every second
            current_time = time.time()
            if current_time - last_tick >= 1:
                if countdown != float('inf'):
                    countdown -= 1
                    last_tick = current_time
                    if countdown <= 0:
                        # Time's up
                        show_explosion()
                        reset_game()
    
            # Draw the screen
            WINDOW.fill(BLACK)
    
            # Draw the countdown timer
            if countdown != float('inf'):
                minutes = int(countdown) // 60
                seconds = int(countdown) % 60
                time_str = f"{minutes:02}:{seconds:02}"
                # Using a more modern font for the timer
                lcd_text = LCD_FONT.render(time_str, True, GREEN)
            else:
                lcd_text = LCD_FONT.render("SAFE", True, GREEN)
            lcd_rect = lcd_text.get_rect(center=(WIDTH//2, HEIGHT//2 - 100))
            WINDOW.blit(lcd_text, lcd_rect)
    
            # Draw buttons and input field
            draw_buttons()
    
        pygame.display.flip()
        pygame.time.Clock().tick(30)  # 30 FPS
    

    Key Improvements Explained:

    1. Modern Color Scheme:

      • Adopted a darker background (BLACK) with vibrant accent colors (RED, GREEN) for buttons and alerts, creating a sleek, modern look.
    2. Enhanced Layout:

      • Input Field: Positioned at the top with clear separation from the timer.
      • Number Pad: Centrally aligned with sufficient spacing to prevent overlapping.
    3. Font Enhancements:

      • LCD Font: Utilized a digital-style font (Digital-7 Mono) for the countdown timer to mimic real bomb timers. Ensure you have this font installed or replace it with another digital font.
      • Button Labels: Clear and legible with distinct colors for action buttons (CLR in red, ENT in green).
    4. Input Display Enhancement:

      • Underscores: Displays underscores for each missing digit, updating dynamically as the user inputs numbers. For example, if the user has entered "12", it shows 1 2 _ _.
      • Code Display: Positioned prominently at the top for easy visibility.
    5. Explosion Animation:

      • Maintained a simple yet visually impactful explosion effect with expanding circles and fading opacity.
    6. Functionality Enhancements:

      • Input Validation: Only numeric inputs are accepted, preventing non-digit characters from being entered.
      • Countdown Control: If the correct code is entered, the countdown stops and displays "SAFE" instead of the timer.
    7. Code Organization:

      • Cleaned up and modularized functions (draw_buttons, draw_lcd_time, etc.) for better readability and maintenance.

    Additional Recommendations:

    • Responsive Design: If you plan to support multiple screen sizes, consider calculating positions and sizes dynamically based on WIDTH and HEIGHT.

    • Sound Effects: Adding sounds for button presses, correct/incorrect code entries, and explosions can enhance the user experience.

    • Visual Feedback: Highlight buttons on hover or click to provide interactive feedback.

    • Error Handling: Implement more robust error handling, such as limiting input to digits and handling edge cases gracefully.

    Final Touches:

    Ensure you have the required fonts installed on your system. If Digital-7 Mono is unavailable, consider using alternative digital-style fonts like LCD, DS-Digital, or any other monospaced font that resembles digital displays.

    This optimized version should provide a cleaner, more modern interface while maintaining the core functionality of your bomb defusal game. Feel free to further customize the aesthetics to match your vision!