用AI写游戏《敲砖块》

import pygame

import sys

import os

# Initialize Pygame

pygame.init()

# Window size

WIDTH, HEIGHT = 800, 600

# Paddle size and speed

PADDLE_WIDTH, PADDLE_HEIGHT = 150, 10

PADDLE_SPEED = 10

# Ball radius

BALL_RADIUS = 10

# Brick size and grid

BRICK_WIDTH, BRICK_HEIGHT = 80, 30

BRICK_ROWS = 5

BRICK_COLS = 10

BRICK_GAP = 4

# Colors

WHITE = (255, 255, 255)

RED = (255, 0, 0)

BLUE = (0, 0, 255)

YELLOW = (255, 255, 0)

# Frames per second

FPS = 60

# Create game window

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Brick Breaker")

# Function to find a font file

def find_font(name):

    if pygame.font.match_font(name):

        return pygame.font.match_font(name)

    else:

        for root, _, files in os.walk("C:\\Windows\\Fonts"):  # Search Windows font directory

            for file in files:

                if file.lower().startswith(name.lower()):

                    return os.path.join(root, file)

    return None

# Load English font

font_name = find_font("arial.ttf")  # Search for Arial font (you can change this to any English font you have)

if font_name:

    english_font = pygame.font.Font(font_name, 24)

else:

    english_font = pygame.font.SysFont(None, 24)  # Use system default font if Arial is not found

# Define game objects

class Paddle(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()

        self.image = pygame.Surface((PADDLE_WIDTH, PADDLE_HEIGHT))

        self.image.fill(WHITE)

        self.rect = self.image.get_rect()

        self.rect.centerx = WIDTH // 2

        self.rect.bottom = HEIGHT - 20

        self.speed = PADDLE_SPEED

    def update(self):

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and self.rect.left > 0:

            self.rect.x -= self.speed

        if keys[pygame.K_RIGHT] and self.rect.right < WIDTH:

            self.rect.x += self.speed

class Ball(pygame.sprite.Sprite):

    def __init__(self, paddle):

        super().__init__()

        self.image = pygame.Surface((BALL_RADIUS * 2, BALL_RADIUS * 2), pygame.SRCALPHA)

        pygame.draw.circle(self.image, WHITE, (BALL_RADIUS, BALL_RADIUS), BALL_RADIUS)

        self.rect = self.image.get_rect()

        self.rect.center = (WIDTH // 2, HEIGHT // 2)

        self.speed_x = 5

        self.speed_y = -5

        self.paddle = paddle

    def update(self):

        self.rect.x += self.speed_x

        self.rect.y += self.speed_y

        # Ball collision with edges

        if self.rect.left <= 0 or self.rect.right >= WIDTH:

            self.speed_x = -self.speed_x

        if self.rect.top <= 0:

            self.speed_y = -self.speed_y

        # Collision with paddle

        if pygame.sprite.collide_rect(self, self.paddle):

            self.speed_y = -self.speed_y

        # Collision with bricks

        brick_collision = pygame.sprite.spritecollide(self, bricks_group, True)

        if brick_collision:

            self.speed_y = -self.speed_y

            increase_score()

        # Game over if ball falls to the bottom

        if self.rect.bottom >= HEIGHT:

            lose_life()

def create_bricks():

    bricks = pygame.sprite.Group()

    colors = [RED, BLUE, YELLOW]

    for row in range(BRICK_ROWS):

        for col in range(BRICK_COLS):

            brick = Brick(col * (BRICK_WIDTH + BRICK_GAP) + 50,

                          row * (BRICK_HEIGHT + BRICK_GAP) + 50,

                          colors[row % len(colors)])

            bricks.add(brick)

    return bricks

class Brick(pygame.sprite.Sprite):

    def __init__(self, x, y, color):

        super().__init__()

        self.image = pygame.Surface((BRICK_WIDTH, BRICK_HEIGHT))

        self.image.fill(color)

        self.rect = self.image.get_rect()

        self.rect.x = x

        self.rect.y = y

def increase_score():

    global score

    score += 1

def lose_life():

    global lives

    lives -= 1

    if lives <= 0:

        game_over()

    else:

        reset_game()

def game_over():

    font = english_font

    text = font.render("Game Over", True, WHITE)

    text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))

    screen.blit(text, text_rect)

    # Prompt to restart or quit

    prompt = font.render("Press R to Restart or Q to Quit", True, WHITE)

    prompt_rect = prompt.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 50))

    screen.blit(prompt, prompt_rect)

    pygame.display.flip()

    # Wait for user to press R or Q

    while True:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.KEYDOWN:

                if event.key == pygame.K_r:

                    reset_game()

                elif event.key == pygame.K_q:

                    pygame.quit()

                    sys.exit()

def reset_game():

    global lives, score

    lives = 3

    score = 0

    main()

def main_menu():

    running = True

    while running:

        screen.fill((0, 0, 0))

        draw_text(screen, "Brick Breaker", 64, WHITE, WIDTH // 2, HEIGHT // 4)

        draw_text(screen, "Press Enter to Start", 36, WHITE, WIDTH // 2, HEIGHT // 2)

        pygame.display.flip()

        # Main menu event handling

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.KEYDOWN:

                if event.key == pygame.K_RETURN:

                    main()  # Start game when Enter is pressed

def draw_text(surface, text, size, color, x, y):

    font = english_font

    text_surface = font.render(text, True, color)

    text_rect = text_surface.get_rect()

    text_rect.midtop = (x, y)

    surface.blit(text_surface, text_rect)

def main():

    global bricks_group, score, lives

    # Create game objects

    paddle = Paddle()

    ball = Ball(paddle)

    bricks_group = create_bricks()

    # Create sprite groups

    all_sprites = pygame.sprite.Group()

    all_sprites.add(paddle, ball, bricks_group)

    # Game variables

    score = 0

    lives = 3

    # Main game loop

    clock = pygame.time.Clock()

    running = True

    while running:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

        all_sprites.update()

        screen.fill((0, 0, 0))

        all_sprites.draw(screen)

        # Display lives and score

        font = english_font

        lives_text = font.render(f"Lives: {lives}", True, WHITE)

        lives_rect = lives_text.get_rect(topleft=(10, 10))

        screen.blit(lives_text, lives_rect)

        score_text = font.render(f"Score: {score}", True, WHITE)

        score_rect = score_text.get_rect(topright=(WIDTH - 10, 10))

        screen.blit(score_text, score_rect)

        pygame.display.flip()

        clock.tick(FPS)

if __name__ == "__main__":

    main_menu()

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容