Life and Tech Talk

벽돌깨기 게임
import pygame
import sys
import random
import time


# Initialize Pygame
pygame.init()


# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600


# Colors
LIGHT_BLUE = (173, 216, 230)
WHITE = (255, 255, 255)
GRAY = (169, 169, 169)
DARK_GREEN = (0, 100, 0)  # Darker green for paddle
DARK_GREEN_TEXT = (34, 139, 34)  # Dark green for text
RED = (255, 0, 0)


# Initialize the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Brick Breaker Game")


# Fonts
FONT = pygame.font.Font(None, 74)
SMALL_FONT = pygame.font.Font(None, 36)


# Paddle
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 10
paddle = pygame.Rect(SCREEN_WIDTH // 2 - PADDLE_WIDTH // 2, SCREEN_HEIGHT - 20, PADDLE_WIDTH, PADDLE_HEIGHT)


# Ball
BALL_SIZE = 15  # Increased ball size
ball = pygame.Rect(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, BALL_SIZE, BALL_SIZE)
ball_speed_x = 4 * random.choice((-1, 1))
ball_speed_y = -4


# Brick dimensions
BRICK_WIDTH = 70
BRICK_HEIGHT = 20


# Generate random brick patterns
def generate_bricks():
    patterns = ["grid", "pyramid", "scattered"]
    pattern = random.choice(patterns)


    bricks = []
    if pattern == "grid":
        rows = 5
        cols = 10
        for row in range(rows):
            for col in range(cols):
                brick_x = col * (BRICK_WIDTH + 5)
                brick_y = row * (BRICK_HEIGHT + 5)
                brick = pygame.Rect(brick_x, brick_y, BRICK_WIDTH, BRICK_HEIGHT)
                bricks.append(brick)


    elif pattern == "pyramid":
        rows = 5
        for row in range(rows):
            cols = rows - row
            for col in range(cols):
                brick_x = SCREEN_WIDTH // 2 - (cols * (BRICK_WIDTH + 5)) // 2 + col * (BRICK_WIDTH + 5)
                brick_y = row * (BRICK_HEIGHT + 5)
                brick = pygame.Rect(brick_x, brick_y, BRICK_WIDTH, BRICK_HEIGHT)
                bricks.append(brick)


    elif pattern == "scattered":
        for _ in range(30):  # 30 random bricks
            brick_x = random.randint(0, SCREEN_WIDTH - BRICK_WIDTH)
            brick_y = random.randint(0, SCREEN_HEIGHT // 3)  # Limit to upper third
            brick = pygame.Rect(brick_x, brick_y, BRICK_WIDTH, BRICK_HEIGHT)
            bricks.append(brick)


    return bricks


# Create bricks
bricks = generate_bricks()


# Game variables
paddle_speed = 7
retry_count = 0
max_retries = 3
rounds_played = 1
total_rounds = 3
running = True
clock = pygame.time.Clock()


# Function to reset the ball and paddle position
def reset_game():
    global ball, ball_speed_x, ball_speed_y, bricks
    ball = pygame.Rect(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, BALL_SIZE, BALL_SIZE)
    ball_speed_x = 4 * random.choice((-1, 1))
    ball_speed_y = -4
    paddle.centerx = SCREEN_WIDTH // 2
    bricks = generate_bricks()


# Function to display "Mission Cleared" with animation
def display_mission_cleared():
    start_time = time.time()
    text_offset = 0
    direction = 1
    while time.time() - start_time < 2:  # Display for 2 seconds
        screen.fill(LIGHT_BLUE)
        cleared_text = FONT.render("MISSION CLEARED!", True, DARK_GREEN_TEXT)
        text_rect = cleared_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + text_offset))
        screen.blit(cleared_text, text_rect)


        # Draw game progress
        progress_text = SMALL_FONT.render(f"{rounds_played}/{total_rounds}", True, WHITE)
        progress_rect = progress_text.get_rect(bottomright=(SCREEN_WIDTH - 10, SCREEN_HEIGHT - 10))
        screen.blit(progress_text, progress_rect)


        pygame.display.flip()
        text_offset += direction
        if abs(text_offset) > 10:  # Reverse direction after a small movement
            direction *= -1
        clock.tick(30)  # Control animation speed


# Game loop
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


    # Paddle movement
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and paddle.left > 0:
        paddle.move_ip(-paddle_speed, 0)
    if keys[pygame.K_RIGHT] and paddle.right < SCREEN_WIDTH:
        paddle.move_ip(paddle_speed, 0)


    # Ball movement
    ball.x += ball_speed_x
    ball.y += ball_speed_y


    # Ball collision with walls
    if ball.left <= 0 or ball.right >= SCREEN_WIDTH:
        ball_speed_x = -ball_speed_x
    if ball.top <= 0:
        ball_speed_y = -ball_speed_y


    # Ball collision with paddle
    if ball.colliderect(paddle):
        ball_speed_y = -ball_speed_y


    # Ball collision with bricks
    for brick in bricks[:]:
        if ball.colliderect(brick):
            bricks.remove(brick)
            ball_speed_y = -ball_speed_y
            break


    # Check if all bricks are cleared
    if not bricks:
        display_mission_cleared()
        if rounds_played < total_rounds:
            rounds_played += 1
            reset_game()
        else:
            print("Game Over - All Missions Completed!")
            running = False


    # Ball falls below the screen
    if ball.bottom >= SCREEN_HEIGHT:
        retry_count += 1
        if retry_count < max_retries:
            reset_game()
        else:
            print("Game Over!")
            running = False


    # Clear the screen
    screen.fill(LIGHT_BLUE)


    # Draw paddle
    pygame.draw.rect(screen, DARK_GREEN, paddle)


    # Draw ball
    pygame.draw.ellipse(screen, WHITE, ball)


    # Draw bricks
    for brick in bricks:
        pygame.draw.rect(screen, GRAY, brick)


    # Draw game progress
    progress_text = SMALL_FONT.render(f"{rounds_played}/{total_rounds}", True, WHITE)
    progress_rect = progress_text.get_rect(bottomright=(SCREEN_WIDTH - 10, SCREEN_HEIGHT - 10))
    screen.blit(progress_text, progress_rect)


    # Update the display
    pygame.display.flip()
    clock.tick(60)


pygame.quit()
sys.exit()


* requirements: pip instlall pygame

올린날: 2024년 12월 5일
주제: 게임 관련 포스팅 클릭!!

* 올린이: 마이클

* VIEW: 54       0           위키홈     게시판     수정