import pygame
from random import choice, randint
pygame.init()

pygame.display.set_caption("Pygame test")

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

screen_surface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

bonus_images = [
    'bonus_1.png',
    'bonus_2.png',
    'bonus_3.png'
]

FRAMES_PER_SECOND = 60
frames_cnt = 0


game_status = True
clock = pygame.time.Clock()
bonus_objects = []

def generate_bonus_object():
    image_name = choice(bonus_images)
    x = randint(0, SCREEN_WIDTH)
    y = randint(0, SCREEN_HEIGHT)
    position = [x,y]
    new_obj = load_image(image_name, position)
    bonus_objects.append(new_obj)

def print_bonus_objects():
    for obj in bonus_objects:
        print_image(obj)


def load_image(img_path, position):
    image = pygame.image.load(img_path)
    surface = image.convert()
    transparent_color = (0,0,0)
    surface.set_colorkey(transparent_color)
    rect = surface.get_rect(center=position)
    return [image, surface, rect]

def print_image(img_list):
    image, surface, rect = img_list
    screen_surface.blit(surface, rect)

def set_position_image(img_list, position):
    image, surface, rect = img_list
    rect = surface.get_rect(center=position)
    return [image,surface,rect]

def calculate_player_movement(keys):
    speed = 10
    delta_x = 0
    delta_y = 0

    if keys[pygame.K_LSHIFT]:
        speed *= 2
    if keys[pygame.K_w]:
        delta_y -= speed
    if keys[pygame.K_s]:
        delta_y += speed
    if keys[pygame.K_a]:
        delta_x -= speed
    if keys[pygame.K_d]:
        delta_x += speed
    
    return [delta_x, delta_y]
    
def limit_position(position):
    x,y = position
    x = max(0, min(x, SCREEN_WIDTH))
    y = max(0, min(y, SCREEN_HEIGHT))
    return [x,y]


player_pos = [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2]
player = load_image('player.png', player_pos)
background_color = [9,42,121]

while game_status == True:
    events = pygame.event.get()

    for event in events:
        if event.type == pygame.QUIT:
            game_status = False

    pressed_keys = pygame.key.get_pressed()
    delta_x, delta_y = calculate_player_movement(pressed_keys)

    player_pos[0] += delta_x
    player_pos[1] += delta_y
    player_pos = limit_position(player_pos)
    player = set_position_image(player, player_pos)

    screen_surface.fill(background_color)
    print_image(player)

    if frames_cnt % (FRAMES_PER_SECOND * 1) == 0:
        generate_bonus_object()

    print_bonus_objects()

    pygame.display.update()
    frames_cnt +=1
    clock.tick(60)

pygame.quit()
quit()