# coding: utf-8
"""First PyGame project. Run: python pygame-first-game.py"""
import random
import pygame

WIDTH, HEIGHT = 640, 400
SIZE = 32
SPEED = 220  # pixels per second


def new_target(player):
    while True:
        target = pygame.Rect(random.randrange(WIDTH - 24 + 1),
                             random.randrange(HEIGHT - 24 + 1), 24, 24)
        if not target.colliderect(player):
            return target


def main(max_frames=None):
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    clock = pygame.time.Clock()
    position = pygame.Vector2(50, 50)
    player = pygame.Rect(50, 50, SIZE, SIZE)
    target = new_target(player)
    score = 0
    frames = 0
    running = True
    try:
        while running:
            dt = min(clock.tick(60) / 1000.0, 0.1)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
            keys = pygame.key.get_pressed()
            direction = pygame.Vector2(int(keys[pygame.K_RIGHT]) - int(keys[pygame.K_LEFT]),
                                       int(keys[pygame.K_DOWN]) - int(keys[pygame.K_UP]))
            if direction.length_squared() > 0:
                direction = direction.normalize()
            position += direction * SPEED * dt
            position.x = max(0, min(WIDTH - SIZE, position.x))
            position.y = max(0, min(HEIGHT - SIZE, position.y))
            player.topleft = (round(position.x), round(position.y))
            if player.colliderect(target):
                score += 1
                target = new_target(player)
            screen.fill((242, 245, 250))
            pygame.draw.rect(screen, (45, 95, 215), player)
            pygame.draw.rect(screen, (239, 122, 41), target)
            pygame.display.set_caption("First game | Score: " + str(score))
            pygame.display.flip()
            frames += 1
            if max_frames is not None and frames >= max_frames:
                running = False
    finally:
        pygame.quit()
    return {"frames": frames, "score": score}


if __name__ == "__main__":
    main()
