import pygame

pygame.init()

win = pygame.display.set_mode((500, 480))
pygame.display.set_caption("First Game")

clock = pygame.time.Clock()

# Shit vars
x, y = 200, 410
width, height = 40, 60
vel = 5
isJump = False
jumpCount = 10

# Animation Vars
left = False
right = False
walkCount = 0

# https://www.techwithtim.net/tutorials/game-development-with-python/pygame-tutorial/optimization
walkRight = [
    pygame.image.load("Images/R1.png"),
    pygame.image.load("Images/R2.png"),
    pygame.image.load("Images/R3.png"),
    pygame.image.load("Images/R4.png"),
    pygame.image.load("Images/R5.png"),
    pygame.image.load("Images/R6.png"),
    pygame.image.load("Images/R7.png"),
    pygame.image.load("Images/R8.png"),
    pygame.image.load("Images/R9.png"),
]

walkLeft = [
    pygame.image.load("Images/L1.png"),
    pygame.image.load("Images/L2.png"),
    pygame.image.load("Images/L3.png"),
    pygame.image.load("Images/L4.png"),
    pygame.image.load("Images/L5.png"),
    pygame.image.load("Images/L6.png"),
    pygame.image.load("Images/L7.png"),
    pygame.image.load("Images/L8.png"),
    pygame.image.load("Images/L9.png"),
]

bg = pygame.image.load("Images/bg.jpg")
char = pygame.image.load("Images/standing.png")


def redrawGameWindow():
    global walkCount

    win.blit(bg, (0, 0))
    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        win.blit(walkLeft[walkCount // 3], (x, y))
        walkCount += 1
    elif right:
        win.blit(walkRight[walkCount // 3], (x, y))
        walkCount += 1
    else:
        win.blit(char, (x, y))

    pygame.display.update()


run = True

while run:
    clock.tick(27)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x > vel:
        x -= vel
        left = True
        right = False
    elif keys[pygame.K_RIGHT] and x < 500 - vel - width:
        x += vel
        left = False
        right = True
    else:
        left = False
        right = False
        walkCount = 0

    if isJump is False:
        if keys[pygame.K_SPACE]:
            isJump = True
            left = False
            right = False
            walkCount = 0
    else:
        if jumpCount >= -10:
            y -= (jumpCount * abs(jumpCount)) * 0.5
            jumpCount -= 1
        else:
            jumpCount = 10
            isJump = False

    redrawGameWindow()


pygame.quit()
