tirkdo/tirkdo.py

94 lines
2.5 KiB
Python
Raw Permalink Normal View History

2021-11-25 19:49:17 +01:00
#!/usr/bin/python
import datetime
import json
2021-11-25 19:49:17 +01:00
import random
import sys
2021-11-25 19:49:17 +01:00
annee = datetime.date.today().year
2021-11-25 19:49:17 +01:00
participants = [
'Maman',
'Papa',
'Mémé',
'Charlotte',
'Nico',
'Didi',
'Johnny',
'Ben',
'Ludo',
]
on_evite = {
'Ben': 'Ludo',
'Charlotte': 'Nico',
'Maman': 'Papa',
'Didi': 'Johnny',
}
# On charge le résultat de l'année dernière
nom_fichier = sys.argv[1] if len(sys.argv) > 1 else f"{annee-1}.json"
try:
with open(nom_fichier, "r", encoding="utf-8") as fd:
annee_passee = json.load(fd)
print(f"Résultat de l'an passée chargé depuis le fichier {nom_fichier} :")
print("\n".join([f"- {offre} => {recois}" for offre, recois in annee_passee.items()]))
except FileNotFoundError:
print(f"Échec de chargement du tirage de l'an passé depuis le fichier {nom_fichier}.")
sys.exit(1)
2021-11-25 19:49:17 +01:00
class EchecTirage(Exception):
pass
2021-11-25 19:49:17 +01:00
# On défine notre méthode de tirage
def tirage(nb_tentatives_max=99):
participants_offre = participants.copy()
participants_recois = participants.copy()
2021-11-25 19:49:17 +01:00
# On mélange les listes
random.shuffle(participants_offre)
random.shuffle(participants_recois)
2021-11-25 19:49:17 +01:00
result = dict()
for offre in participants_offre:
count = 0
while True:
count += 1
if count == nb_tentatives_max:
raise EchecTirage
recois = random.choice(participants_recois)
# Pas à soi même
if recois == offre:
continue
# On évite entre couple
if on_evite.get(offre) == recois or on_evite.get(recois) == offre:
continue
# On évite de faire comme l'an passée
if annee_passee.get(offre) == recois:
continue
# Trouvé !
result[offre] = recois
participants_recois.remove(recois)
break
return result
# On procède au tirage
print("On procède au tirage... Suspense !")
result = None
while not result:
try:
result = tirage()
except EchecTirage:
print("Échec du tirage, on recommence !")
result = None
2021-11-25 19:49:17 +01:00
# On affiche le résultat
print("Résultat du tirage pour l'année {annee} :")
for offre, recois in result.items():
print(f" - {offre} -> {recois}")
# On enregistre le tirage pour l'année passée
nom_fichier = f"{annee}.json"
with open(nom_fichier, "w", encoding="utf-8") as fichier:
fichier.write(json.dumps(result, indent=2, ensure_ascii=False))
print(f"Résultat enregistré dans le fichier {nom_fichier}.")