#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May  2 22:03:44 2024

@author: fjunier
"""

import pyxel

# Tutoriel détaillé de Peio47 : https://www.cahiernum.net/CGS8UD
# Autres tutoriels : https://nuit-du-code.forge.apps.education.fr/DOCUMENTATION/PYTHON/01-presentation/


# création de la fenêtre
pyxel.init(128, 128, title="Nuit du code")
# chargement du fichier de ressources (Univers de la NuitDuCode 2022)
pyxel.load("1.pyxres")

points = 0
xmin = 0
xmax = 248 * 8
y_min = 0
y_max = 128 - 8
x_scroll = 64
y_perso = 112
orientation = +1
TUILE_VIDE = (0, 0)
COULEUR_BLANC = 7
NOIR = (3, 3)

def detecte_mur(x, y):
    "Détection d'une tuile mur ou obstacle"
    # à partir d'une position on peut chevaucher 4 tuiles
    x1 = x // 8
    y1 = y // 8
    x2 = (x + 8 - 1) // 8
    y2 = (y + 8 - 1) // 8
    for yi in range(y1, y2 + 1):
        for xi in range(x1, x2 + 1):
            xtuile, ytuile = pyxel.tilemap(0).pget(xi, yi)
            # print(x, y, xi, yi, xtuile, ytuile)
            if xtuile > 3 or (xtuile, ytuile) == (1, 0) or ytuile > 4:
                return True
    return False


def detecte_bonbon(x, y):
    "Détection d'une tuile bonbon"
    global points
    # à partir d'une position on peut chevaucher 4 tuiles
    x1 = x // 8
    y1 = y // 8
    x2 = (x + 8 - 1) // 8
    y2 = (y + 8 - 1) // 8
    for yi in range(y1, y2 + 1):
        for xi in range(x1, x2 + 1):
            xtuile, ytuile = pyxel.tilemap(0).pget(xi, yi)
            if 0 <= xtuile <= 2 and ytuile == 1:
                pyxel.tilemap(0).pset(xi, yi,NOIR)
                points += 1
                return True
    return False


def deplacement():
    """déplacement  du personnage avec les touches de directions"""
    global x_scroll, y_perso, orientation

    if (
        pyxel.btn(pyxel.KEY_RIGHT)
        and x_scroll < xmax
        and not detecte_mur(x_scroll + 1, y_perso)
    ):
        x_scroll += 1
        orientation = 1
    if (
        pyxel.btn(pyxel.KEY_LEFT)
        and x_scroll > xmin
        and not detecte_mur(x_scroll - 1, y_perso)
    ):
        x_scroll -= 1
        orientation = -1
    if (
        pyxel.btn(pyxel.KEY_UP)
        and y_perso > y_min
        and not detecte_mur(x_scroll, y_perso - 1)
    ):
        y_perso -= 2  # pour compenser la gravité
    if y_perso < y_max and not detecte_mur(x_scroll, y_perso + 1):
        y_perso += 1  # gravité


def update():
    "Mise à jour des objets du jeu"
    global x_scroll, points
    if pyxel.frame_count % 3 == 0:
        deplacement()
        detecte_bonbon(x_scroll, y_perso)


def draw():
    "Dessin des objets du jeu"
    # vide la fenetre
    pyxel.cls(0)
    pyxel.camera()
    pyxel.bltm(0, 0, 0, x_scroll - 64, 0, 128, 128)
    pyxel.blt(64, y_perso, 0, 0, 16, orientation * 8, 8)
    pyxel.text(10, 10, f"Points : {points}", COULEUR_BLANC)


# Exécution du jeu
pyxel.run(update, draw)