#!/bin/bash

# Author: Christophe Casalegno / Brain 0verride
# Contact: brain@christophe-casalegno.com
# Version 0.1
#
# Copyright (c) 2023 Christophe Casalegno
# 
# This program is free software: you can redistribute it and/or modify
#
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>
#
# The license is available on this server here: 
# https://www.christophe-casalegno.com/licences/gpl-3.0.txt

# Variables d'initialisation
brain="☻"
trace="."
wall="▒"
up=0
down=0
left=0
right=0
maze_source="maze.txt"

#setuper le niveau de difficulté
function difficulty()
{
	clear
	echo "Choisissez votre niveau de difficulté"
	echo "1 : Facile"
	echo "2 : Moyen"
	echo "3 : Difficile"
	
	read -p "Entrez votre choix : " difficulty_level

	case $difficulty_level in 
    	1)
        	maze_cols="31"
		maze_rows="15"
        	;;	
    	2)
        	maze_cols="51"
                maze_rows="19"
		;;
    	3)
        	maze_cols="71"
                maze_rows="23"
		;;
    	*)
        	echo "Choix invalide. Veuillez sélectionner une option valide."
        ;;
esac
}


# Générer et récupérer le labyrinthe
function retrieve_maze() 
{

	difficulty
	./mazegenerator.sh ${maze_cols} ${maze_rows} > ${maze_source}
}

# Afficher le labyrinthe
function print_maze() 
{
    clear
    for ((i=0; i<${#maze[@]}; i++)); do
    	echo "${maze[$i]}"
    done
    echo "Position actuelle : (x=${brain_start_x}, y=${brain_start_y})"
}

# Initialiser le labyrinthe à partir du fichier source
function init_maze() 
{
    maze=()
    while IFS= read -r line; do
        maze+=("$line")
    done < "$maze_source"
}

# Vérifier si Brain a atteint la position de victoire
function check_victory() 
{

	brain_win_x=$(echo "$(($maze_cols -1))")
        brain_win_y=$(echo "$(($maze_rows - 2))")

    if ((brain_start_x == brain_win_x && brain_start_y == brain_win_y)) 
    then
        echo 'Félicitations, vous avez gagné !'
	echo 'Souhaitez-vous recommencer une partie ? (y/n)'
	read reponse
	if [[ ${reponse} = 'n' ]]
	then
		exit 0
	else
		echo "Ok, c'est reparti pour un tour"
		start_game		
    	fi
    fi
}

function start_game()
{
    # Réinitialiser la position de départ
    brain_start_x=0
    brain_start_y=1

    # Générer et récupérer un nouveau labyrinthe
    retrieve_maze
    init_maze

    # Démarrer la boucle principale du jeu
    main_loop
}


# Boucle principale du jeu

function main_loop()
{
while true; do
    # Mettre à jour le labyrinthe avec la position actuelle de Brain
    maze[$brain_start_y]="${maze[$brain_start_y]:0:$brain_start_x}$trace${maze[$brain_start_y]:$((brain_start_x + 1))}"

    # Mettre à jour la position de Brain
    if ((up)); then
        next_y=$((brain_start_y - 1))
        if [[ ${maze[$next_y]:$brain_start_x:1} != $wall ]]; then
            brain_start_y=$next_y
        fi
    elif ((down)); then
        next_y=$((brain_start_y + 1))
        if [[ ${maze[$next_y]:$brain_start_x:1} != $wall ]]; then
            brain_start_y=$next_y
        fi
    elif ((left)); then
        next_x=$((brain_start_x - 1))
        if [[ ${maze[$brain_start_y]:$next_x:1} != $wall ]]; then
            brain_start_x=$next_x
        fi
    elif ((right)); then
        next_x=$((brain_start_x + 1))
        if [[ ${maze[$brain_start_y]:$next_x:1} != $wall ]]; then
            brain_start_x=$next_x
        fi
    fi

    # Mettre à jour le labyrinthe avec la nouvelle position de Brain
    maze[$brain_start_y]="${maze[$brain_start_y]:0:$brain_start_x}$brain${maze[$brain_start_y]:$((brain_start_x + 1))}"

    # Vérifier si Brain a atteint la position de victoire
    check_victory

    # Afficher le labyrinthe
    print_maze

    # Lire l'entrée de l'utilisateur
    read -rsn3 input
    case "$input" in
        $'\e[A')
            up=1
            down=0
            left=0
            right=0
            ;;
        $'\e[B')
            up=0
            down=1
            left=0
            right=0
            ;;
        $'\e[D')
            up=0
            down=0
            left=1
            right=0
            ;;
        $'\e[C')
            up=0
            down=0
            left=0
            right=1
            ;;
    esac
done
}

start_game
