Skip to content

Commit

Permalink
FEAT: Sauvegarde score/stats JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
JML-0 committed Oct 9, 2024
1 parent 9f2e857 commit 6dcab38
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 5 deletions.
2 changes: 2 additions & 0 deletions AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@
- Samy FERGUI, [email protected]
- Marwane, RACHAD, [email protected]
- Mathis, Beauville, [email protected]
- Alexandre ANTUNES MENDES, [email protected]
- Jimmy, Levacher, [email protected]
66 changes: 61 additions & 5 deletions src/demineur.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@
"""Module providing Random variable generators."""
import random
import json
import os
from statistiques import Statistiques

class Demineur:
"""Class representing a Deminer game"""

def __init__(self, nombre_mines=10):
self.taille = 10
self.nombre_mines = nombre_mines

def __init__(self, fichier_sauvegarde='demineur.json', difficulte='moyen'):
"""
Initialize the game with a grid and place mines based on difficulty level.
:param difficulte: Difficulty level of the game ('facile', 'moyen', 'difficile').
:raises ValueError: If the difficulty level is not one of 'facile', 'moyen', or 'difficile'.
"""
if difficulte not in ['facile', 'moyen', 'difficile']:
raise ValueError("Le niveau de difficulté doit être 'facile', 'moyen' ou 'difficile'.")

if difficulte == 'facile':
self.taille = 8
self.nombre_mines = 10
elif difficulte == 'difficile':
self.taille = 16
self.nombre_mines = 40
else: # moyen
self.taille = 10
self.nombre_mines = 20

self.grille = [['.' for _ in range(self.taille)] for _ in range(self.taille)]
self.grille_visible = [['.' for _ in range(self.taille)] for _ in range(self.taille)]
self.statistiques = Statistiques()
self.fichier_sauvegarde = fichier_sauvegarde
self.__placer_mines()
self.__calculer_indices()

Expand Down Expand Up @@ -56,10 +79,28 @@ def afficher_grille(self):
for ligne in self.grille_visible:
print(' '.join(ligne))

def charger_jeu(self):
"""
Load the game state from a JSON file.
"""
if os.path.exists(self.fichier_sauvegarde):
with open(self.fichier_sauvegarde, 'r', encoding='utf-8') as file:
data = json.load(file)
self.taille = data.get('taille', 10)
self.nombre_mines = data.get('nombre_mines', 10)
self.grille = data.get(
'grille', [['.' for _ in range(self.taille)] for _ in range(self.taille)]
)
self.grille_visible = data.get(
'grille_visible',
[['.' for _ in range(self.taille)] for _ in range(self.taille)]
)

def jouer(self):
"""A Function to launch the game"""

game_in_progress = True
self.statistiques.start_timer()
while game_in_progress:
self.afficher_grille()
x, y = map(int, input("Entrez les coordonnees x et y separees par un espace: ").split())
Expand All @@ -70,13 +111,28 @@ def jouer(self):
print("Perdu !")
#End the game
game_in_progress = False
temps_ecoule = self.statistiques.stop_timer()
self.statistiques.record_loss()
break

self.decouvrir_cases(x, y)
if sum(row.count('.') for row in self.grille_visible) == self.nombre_mines:
print("Gagne !")
#End the game
game_in_progress = False
temps_ecoule = self.statistiques.stop_timer()
self.statistiques.record_victory()
break

print(f"Temps écoulé: {temps_ecoule:.2f} secondes")
self.statistiques.display_statistics()


if __name__ == "__main__":
jeu = Demineur()
jeu.jouer()
niveau_difficulte = input("Choisissez un niveau de difficulte (facile, moyen, difficile): ")
try:
jeu = Demineur(niveau_difficulte)
jeu.charger_jeu()
jeu.jouer()
except ValueError as e:
print(e)
86 changes: 86 additions & 0 deletions src/statistiques.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""
Module for tracking and managing game statistics.
"""
import time
import os
import json

class Statistiques:
"""
Class for tracking and managing game statistics.
"""
def __init__(self, fichier_stats='statistiques.json'):
self.parties_gagnees = 0
self.parties_perdues = 0
self.temps_total = 0.0
self.nombre_parties = 0
self.timer_start = None
self.fichier_stats = fichier_stats
self.load_statistics()

def load_statistics(self):
"""
Load statistics from the JSON file.
"""
if os.path.exists(self.fichier_stats):
with open(self.fichier_stats, 'r', encoding='utf-8') as file:
data = json.load(file)
self.parties_gagnees = data.get('parties_gagnees', 0)
self.parties_perdues = data.get('parties_perdues', 0)
self.temps_total = data.get('temps_total', 0.0)
self.nombre_parties = self.parties_gagnees + self.parties_perdues

def start_timer(self):
"""
Start the timer.
"""
self.timer_start = time.time()

def stop_timer(self):
"""
Stop the timer.
"""
if self.timer_start is not None:
elapsed_time = time.time() - self.timer_start
self.temps_total += elapsed_time
self.timer_start = None
return elapsed_time
return 0

def record_victory(self):
"""
Record a victory and update statistics.
"""
self.parties_gagnees += 1
self.nombre_parties += 1
self.save_statistics()

def record_loss(self):
"""
Record a loss and update statistics.
"""
self.parties_perdues += 1
self.nombre_parties += 1
self.save_statistics()

def save_statistics(self):
"""
Save the current statistics to the JSON file.
"""
data = {
'parties_gagnees': self.parties_gagnees,
'parties_perdues': self.parties_perdues,
'temps_total': self.temps_total,
}
with open(self.fichier_stats, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4)

def display_statistics(self):
"""
Display the current statistics.
"""
temps_moyen = self.temps_total / self.nombre_parties if self.nombre_parties > 0 else 0
print(f"Parties gagnées: {self.parties_gagnees}")
print(f"Parties perdues: {self.parties_perdues}")
print(f"Temps total: {self.temps_total:.2f} secondes")
print(f"Temps moyen par partie: {temps_moyen:.2f} secondes")

0 comments on commit 6dcab38

Please sign in to comment.