"""
CSCI 145 Day 20 - Animation and games

One activity after each video:
A. show_scene: draw a scene
B. Ball.update, show_balls: bouncing balls
C. Player.move: move a square with the arrow keys
D. Rock.update, Rock.get_rect, play: a dodge game

The last line of this file chooses which one runs.
"""

import random
import pygame

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
FPS = 60
BG_COLOR = (20, 30, 60)
TEXT_COLOR = (255, 255, 255)
FONT_SIZE = 36

NUM_BALLS = 20
BALL_MIN_RADIUS = 10
BALL_MAX_RADIUS = 30
BALL_MIN_SPEED = 1
BALL_MAX_SPEED = 5

PLAYER_SIZE = 40
PLAYER_SPEED = 5
PLAYER_COLOR = (255, 140, 0)
PLAYER_START_X = SCREEN_WIDTH // 2 - PLAYER_SIZE // 2
PLAYER_START_Y = SCREEN_HEIGHT - PLAYER_SIZE

NUM_ROCKS = 5
ROCK_RADIUS = 20
ROCK_MIN_SPEED = 2
ROCK_MAX_SPEED = 5
ROCK_COLOR = (130, 130, 130)


class Ball:
    """
    A ball that bounces off the edges of the screen.
    """

    def __init__(self, x, y, radius, color):
        """
        Make a new ball. Its velocity vx and vy are random integers from
        BALL_MIN_SPEED to BALL_MAX_SPEED, so it starts out moving down and
        to the right.

        Parameters:
            x (int): the x coordinate of the center
            y (int): the y coordinate of the center
            radius (int): the radius
            color (tuple): the color, as (red, green, blue)
        """
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color
        self.vx = random.randint(BALL_MIN_SPEED, BALL_MAX_SPEED)
        self.vy = random.randint(BALL_MIN_SPEED, BALL_MAX_SPEED)

    def draw(self, surface):
        """
        Draw the ball as a filled circle on surface.

        Parameters:
            surface (pygame.Surface): where to draw
        """
        pygame.draw.circle(surface, self.color, (self.x, self.y), self.radius)

    def update(self):
        """
        Move the ball by vx and vy. Then, if the ball is past the left or
        right edge of the screen (x - radius is less than 0, or x + radius
        is greater than SCREEN_WIDTH), reverse vx. Otherwise, vx stays the
        same. Do the same for y and vy with the top and bottom edges
        (0 and SCREEN_HEIGHT).
        """
        # Activity B
        self.x = self.x + self.vx
        self.y = self.y + self.vy
        if self.x - self.radius < 0 or self.x + self.radius > SCREEN_WIDTH:
            self.vx = -self.vx
        if self.y - self.radius < 0 or self.y + self.radius > SCREEN_HEIGHT:
            self.vy = -self.vy


class Player:
    """
    The square the player moves with the arrow keys.
    """

    def __init__(self, x, y):
        """
        Make a new player. Its attribute rect is a pygame.Rect with its
        upper-left corner at (x, y), PLAYER_SIZE wide and PLAYER_SIZE tall.

        Parameters:
            x (int): the x coordinate of the upper-left corner
            y (int): the y coordinate of the upper-left corner
        """
        self.rect = pygame.Rect(x, y, PLAYER_SIZE, PLAYER_SIZE)

    def move(self, dx, dy):
        """
        Move the player dx to the right and dy down, but keep it on the
        screen: if the move would put part of the player past an edge, the
        player stops at that edge instead. Otherwise, it moves the full
        dx and dy.

        Parameters:
            dx (int): how far to move right (negative moves left)
            dy (int): how far to move down (negative moves up)
        """
        # Activity C
        self.rect.x = max(0, min(self.rect.x + dx, SCREEN_WIDTH - PLAYER_SIZE))
        self.rect.y = max(0, min(self.rect.y + dy, SCREEN_HEIGHT - PLAYER_SIZE))

    def draw(self, surface):
        """
        Draw the player as a filled PLAYER_COLOR rectangle on surface.

        Parameters:
            surface (pygame.Surface): where to draw
        """
        pygame.draw.rect(surface, PLAYER_COLOR, self.rect)


class Rock:
    """
    A falling rock. When it falls off the bottom of the screen, it starts
    again above the top.
    """

    def __init__(self):
        """
        Make a new rock with radius ROCK_RADIUS, then call reset to give it
        a random position and speed.
        """
        self.radius = ROCK_RADIUS
        self.reset()

    def reset(self):
        """
        Give the rock a new random position above the top of the screen
        and a new random speed:
        - x: a random integer from radius to SCREEN_WIDTH - radius
        - y: a random integer from -SCREEN_HEIGHT to -radius
        - speed: a random integer from ROCK_MIN_SPEED to ROCK_MAX_SPEED
        """
        self.x = random.randint(self.radius, SCREEN_WIDTH - self.radius)
        self.y = random.randint(-SCREEN_HEIGHT, -self.radius)
        self.speed = random.randint(ROCK_MIN_SPEED, ROCK_MAX_SPEED)

    def update(self):
        """
        Move the rock down by speed. Then, if the rock is completely below
        the bottom of the screen (y - radius is greater than
        SCREEN_HEIGHT), call reset. Otherwise, nothing else changes.
        """
        # Activity D
        self.y = self.y + self.speed
        if self.y - self.radius > SCREEN_HEIGHT:
            self.reset()

    def get_rect(self):
        """
        Returns:
            pygame.Rect: the square around the rock, with upper-left corner
            (x - radius, y - radius) and width and height 2 * radius
        """
        # Activity D
        return pygame.Rect(self.x - self.radius, self.y - self.radius,
                           2 * self.radius, 2 * self.radius)

    def draw(self, surface):
        """
        Draw the rock as a filled ROCK_COLOR circle on surface.

        Parameters:
            surface (pygame.Surface): where to draw
        """
        pygame.draw.circle(surface, ROCK_COLOR, (self.x, self.y), self.radius)


def show_scene():
    """
    Show a scene that doesn't move. Close the window to stop.
    """
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("My scene")
    clock = pygame.time.Clock()

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

        screen.fill(BG_COLOR)
        # Activity A: a snowman at night
        pygame.draw.circle(screen, (250, 240, 190), (500, 70), 35)
        pygame.draw.rect(screen, (235, 240, 250), (0, 340, 600, 60))
        pygame.draw.circle(screen, (255, 255, 255), (300, 300), 55)
        pygame.draw.circle(screen, (255, 255, 255), (300, 220), 40)
        pygame.draw.circle(screen, (255, 255, 255), (300, 160), 28)
        pygame.draw.rect(screen, (200, 60, 60), (280, 105, 40, 32))
        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()


def show_balls():
    """
    Show NUM_BALLS bouncing balls of random sizes and colors. Close the
    window to stop.
    """
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Bouncing balls")
    clock = pygame.time.Clock()

    balls = []
    for i in range(NUM_BALLS):
        radius = random.randint(BALL_MIN_RADIUS, BALL_MAX_RADIUS)
        x = random.randint(radius, SCREEN_WIDTH - radius)
        y = random.randint(radius, SCREEN_HEIGHT - radius)
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        balls.append(Ball(x, y, radius, color))

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

        # Activity B: update each ball
        for ball in balls:
            ball.update()

        screen.fill(BG_COLOR)
        # Activity B: draw each ball
        for ball in balls:
            ball.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()


def move_player():
    """
    Move the player with the arrow keys. Close the window to stop.
    """
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Arrow keys")
    clock = pygame.time.Clock()

    player = Player(PLAYER_START_X, PLAYER_START_Y)

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

        keys = pygame.key.get_pressed()
        dx = 0
        dy = 0
        if keys[pygame.K_LEFT]:
            dx = -PLAYER_SPEED
        if keys[pygame.K_RIGHT]:
            dx = PLAYER_SPEED
        if keys[pygame.K_UP]:
            dy = -PLAYER_SPEED
        if keys[pygame.K_DOWN]:
            dy = PLAYER_SPEED
        player.move(dx, dy)

        screen.fill(BG_COLOR)
        player.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()


def play():
    """
    Play the dodge game: move with the arrow keys and don't get hit by a
    rock. Close the window to stop.
    """
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Dodge")
    clock = pygame.time.Clock()
    font = pygame.font.SysFont(None, FONT_SIZE)

    player = Player(PLAYER_START_X, PLAYER_START_Y)
    rocks = []
    for i in range(NUM_ROCKS):
        rocks.append(Rock())

    game_over = False
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        if not game_over:
            keys = pygame.key.get_pressed()
            dx = 0
            dy = 0
            if keys[pygame.K_LEFT]:
                dx = -PLAYER_SPEED
            if keys[pygame.K_RIGHT]:
                dx = PLAYER_SPEED
            if keys[pygame.K_UP]:
                dy = -PLAYER_SPEED
            if keys[pygame.K_DOWN]:
                dy = PLAYER_SPEED
            player.move(dx, dy)

            # Activity D: update each rock; a hit ends the game
            for rock in rocks:
                rock.update()
                if player.rect.colliderect(rock.get_rect()):
                    game_over = True

        screen.fill(BG_COLOR)
        # Activity D: draw each rock
        for rock in rocks:
            rock.draw(screen)
        player.draw(screen)
        if game_over:
            text = font.render("Game over", True, TEXT_COLOR)
            screen.blit(text, (SCREEN_WIDTH // 2 - text.get_width() // 2, SCREEN_HEIGHT // 2))
        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()


if __name__ == "__main__":
    # Change this line to run show_balls(), move_player(), or play()
    show_scene()
