# Leo Salazar
# 6/17/2024
# Intro to platformers, player movement, and gravity

import pygame

# constants for screen dimensions
SCREEN_W = 600
SCREEN_H = 600

# basic set up
pygame.init()
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
pygame.display.set_caption("Basic Movement")
clock = pygame.time.Clock()
running = True

all_sprites = pygame.sprite.Group()

# player class
class Player(pygame.sprite.Sprite):

    # presets for our player (there will only be one)
    def __init__(self, group):
        super().__init__(group)
        self.image = pygame.Surface((50, 50))
        self.image.fill("red")
        self.rect = self.image.get_rect()
        self.rect.center = (SCREEN_W//2, SCREEN_H//2)

        # this sets up our player movement speed, its velocity in the y direction
        # the gravity and the jump power
        self.speed = 5
        self.vel_y = 0
        self.gravity = 0.5
        self.jump_pow = -10

    # this is called every game loop
    def update(self):

        # check for player movement (left, right, jump)
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            self.rect.x -= self.speed
        if keys[pygame.K_d]:
            self.rect.x += self.speed
        if keys[pygame.K_SPACE]:
            self.jump()

        # applies gravity
        self.apply_gravity()

        # traps player in the screen
        if self.rect.left <= 0:
            self.rect.left = 0
        if self.rect.right >= SCREEN_W:
            self.rect.right = SCREEN_W

    # moves the player in the y direction based on y velocity and updates it with gravity
    def apply_gravity(self):
        self.vel_y += self.gravity
        self.rect.y += self.vel_y

        if self.rect.bottom > SCREEN_H:
            self.rect.bottom = SCREEN_H
            self.vel_y = 0

    # will change the y velocity to jump pow only when the player is on the ground
    def jump(self):
        if self.rect.bottom >= SCREEN_H:
            self.vel_y = self.jump_pow

p1 = Player(all_sprites)

# main game loop
while running:

    for event in pygame.event.get():

        # exit loop
        if event.type == pygame.QUIT:
            running = False

    # bg color
    screen.fill("Black")

    # update and draw stuff
    all_sprites.update()
    all_sprites.draw(screen)

    # display on screen
    pygame.display.flip()

    # fps
    clock.tick(60)

# quit game
pygame.quit()