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
code
Assistant
# 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
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
code
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 not display the (4) and show underscores for the missing numbers. Correct the input filed overlaying the "Code:" text. Also the countdown should stop if the code is correct and the app should remain open. Overlay the word "BUMM" on the explosion in Anmiated fire colors.
Here is the optimized version of your Pygame bomb defusal game with the requested enhancements:
Input Field Enhancements:
Removed the "(4)" from the "Code:" prompt.
Display underscores (_) for missing digits in the input field.
Adjusted the positioning to prevent overlaying the "Code:" text.
Countdown Behavior:
The countdown stops when the correct code is entered.
The application remains open, allowing the user to continue interacting.
Explosion Animation:
Overlays the word "BUMM" with animated fire colors during the explosion.
Below is the complete, optimized code with detailed comments explaining each change:
python
import pygame
import sys
import time
from pygame.locals import *
import math
import random
# Initialize Pygame
pygame.init()
# Window dimensions
WIDTH, HEIGHT = 800, 600
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bombenentwaffnungs-Spiel")
# Colors
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)
# Fonts
FONT = pygame.font.SysFont('Courier', 30)
LCD_FONT = pygame.font.SysFont('Courier', 40, bold=True)
BUMM_FONT = pygame.font.SysFont('Courier', 80, bold=True) # Added for "BUMM" text
# Timer settings
TOTAL_TIME = 180 # Seconds (3 minutes)
# Secret code (Example: "1234")
SECRET_CODE = "1234"
# Num pad settings
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
# Game status
STATUS_COUNTDOWN = 0
STATUS_EXPLOSION = 1
# Explosion settings
EXPLOSION_DURATION = 2 # Seconds
# 7-Segment Display Configuration
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)),
}
# Each digit defines which segments are on
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'],
':': [] # For the separator between minutes and seconds
}
def draw_segment(surface, segment, position, color):
"""Draws 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):
"""Draws a single digit in 7-segment style."""
if digit not in DIGITS:
digit = ' ' # Empty space for unknown characters
# Character area
digit_surface = pygame.Surface((80, 120), pygame.SRCALPHA)
digit_surface.fill(BLACK)
# Draw segments
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):
"""Draws the time as a 7-segment LCD."""
x, y = pos
for char in time_str:
if char == ':':
# Draw a simple dot as separator
pygame.draw.circle(surface, SEGMENT_ON, (x + 40, y + 60), 5)
x += 20 # Space between characters
continue
draw_digit(surface, char, (x, y))
x += 80 # Space between digits
def draw_buttons(current_input):
"""Draws the number pad and the input field."""
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)
# Input field
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
prompt_text = FONT.render("Code:", True, WHITE) # Removed "(4)"
WINDOW.blit(prompt_text, (input_rect.x + 10, input_rect.y + 10))
# Prepare input display with underscores for missing digits
display_input = current_input.ljust(4, '_')
input_text = FONT.render(display_input, True, WHITE)
WINDOW.blit(input_text, (input_rect.x + 100, input_rect.y + 10)) # Adjusted position to prevent overlay
def show_explosion():
"""Simple explosion animation with 'BUMM' overlay."""
start_time = time.time()
BUMM_FONT = pygame.font.SysFont('Courier', 80, bold=True) # Ensure font is defined
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 // 2, 0) # Adjusted for better visual
for i in range(1, 6):
radius = int(50 + i * 40 + elapsed * 100) # Adjusted expansion speed
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))
# Render "BUMM" with animated fire colors
color_cycle = [(255, 69, 0), (255, 140, 0), (255, 215, 0), (255, 255, 0)] # Fire-like colors
color_index = int(elapsed * 10) % len(color_cycle)
bumm_color = color_cycle[color_index]
bumm_text = BUMM_FONT.render("BUMM", True, bumm_color)
bumm_rect = bumm_text.get_rect(center=(WIDTH//2, HEIGHT//2))
WINDOW.blit(bumm_text, bumm_rect)
pygame.display.flip()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.time.delay(30)
def reset_game():
"""Resets the game to initial state."""
global countdown, current_input, status, countdown_active
countdown = TOTAL_TIME
current_input = ""
status = STATUS_COUNTDOWN
countdown_active = True
# Initialize game variables
countdown = TOTAL_TIME
current_input = ""
status = STATUS_COUNTDOWN
countdown_active = True
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 entered
print("Code korrekt! Countdown gestoppt.")
countdown_active = False # Stop the countdown
else:
# Incorrect code entered
show_explosion()
reset_game()
else:
if len(current_input) < 4:
current_input += label
break
if status == STATUS_COUNTDOWN:
# Update the countdown every second if active
current_time = time.time()
if countdown_active and (current_time - last_tick >= 1):
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
minutes = countdown // 60
seconds = countdown % 60
time_str = f"{minutes:02}:{seconds:02}"
draw_lcd_time(WINDOW, time_str, (WIDTH//2 - 160, 50))
# Draw the number pad and input field
draw_buttons(current_input)
elif status == STATUS_EXPLOSION:
show_explosion()
reset_game()
pygame.display.flip()
pygame.time.Clock().tick(30) # 30 FPS
Key Changes Explained:
Input Field Display:
Removed "(4)": The prompt now simply displays "Code:" without the "(4)".
Underscores for Missing Digits: The input field shows the current input padded with underscores to indicate missing digits. For example, if the user has entered "12", it will display "12__".
Position Adjustment: The input_text is positioned with an offset (x + 100) to ensure it doesn't overlap with the "Code:" prompt.
Countdown Control:
countdown_active Flag: Introduced a countdown_active boolean variable to control whether the countdown should decrement.
Stopping Countdown: When the correct code is entered (current_input == SECRET_CODE), countdown_active is set to False, thereby stopping the countdown without altering the countdown value to infinity.
Maintaining Application State: The application remains open after stopping the countdown, allowing continuous interaction or simply displaying the stopped time.
Explosion Animation with "BUMM":
Animated "BUMM" Text: The show_explosion function now includes rendering the word "BUMM" in fire-like colors that cycle through red, orange, golden, and yellow shades to simulate flames.
Color Cycling: A list color_cycle is used to cycle through different fire colors based on the elapsed time, creating an animated effect.
Positioning "BUMM": The "BUMM" text is centered on the screen during the explosion animation.
Overall Optimizations:
Font Definition: The BUMM_FONT is defined globally to ensure it's accessible within the show_explosion function.
Explosion Radius Adjustment: Modified the expansion speed of the explosion circles for a more visually appealing effect.
Code Structure: Enhanced readability by adding comments and organizing code sections logically.
Additional Suggestions:
Visual Enhancements: You can further enhance the explosion animation by adding particle effects or varying the explosion colors more dynamically.
Sound Effects: Incorporating sound effects for button presses, successful defusal, or explosions can make the game more engaging.
User Feedback: Display messages or indicators when the code is correct or incorrect to provide immediate feedback to the user.
Difficulty Levels: Introduce different difficulty levels by varying the TOTAL_TIME or the complexity of the secret code.
Feel free to customize and expand upon this foundation to create a more immersive and interactive game experience!