simple #1

Merged
Yann merged 10 commits from simple into dev 2025-02-13 10:32:14 +00:00
24 changed files with 467 additions and 70 deletions
Showing only changes of commit 471b2c9692 - Show all commits

0
controllers/__init__.py Normal file
View File

Binary file not shown.

Binary file not shown.

61
controllers/base.py Normal file
View File

@ -0,0 +1,61 @@
from models.tournament import Tournament
from models.player import Player
from models.turn import Turn
from models.match import Match
from views.menu import Menu
class Controller:
def __init__(self):
# loading models
self.players_list: List[Player] = []
self.score_list = []
# loading views
self.view = Menu()
#self.tournament = Tournament(name = "Tournoi de Cajou", )
#self.turn = Turn()
def prompt_menu(self):
pass
def record_new_player(self):
# get_player = {}
print("Enregistrez un nouveau joueur :\n")
# get_player['lastname'] = input('Nom de famille :\n')
# get_player['name'] = input('Prénom :\n')
#get_player['birth_date'] = input('Date de naissance :\n')
self.lastname = input("Nom de famille ? :\n")
self.name = input("Prénom ? :\n")
def input_date(date):
"""Keep asking until date format is valid"""
try:
datetime.strptime(date, '%d/%m/%Y')
return date
except ValueError:
print("La date doit être au format jj/mm/aaaa")
new_date = input()
input_date(new_date)
return new_date
self.birthdate = input_date(input("Date de naissance (jj/mm/aaaa) ?:\n"))
while self.gender not in ("M", "F", "N"):
self.gender = input("Sexe (M/F/N) ?:\n")
# convert dict in json object and write it in players.json file (with "a" append to file)
# with open("players.json", "a") as output:
# output.write(json.dumps(get_player, indent=3))
return {"Nom": self.lastname, "Prénom": self.name, "Date de naissance": self.birthdate, "Genre": self.gender}
def run(self):
menu_choice = self.view.items(1)
if menu_choice == 3:
self.view.items(2)

View File

@ -0,0 +1 @@
{"EF34924": ["Bob", "Durand", "25/12/1995", "M"], "QS42622": ["Joe", "Bidjoba", "02/01/2001", "M"], "AB20022": ["Jeanine", "Mequesurton", "25/12/1995", "F"], "JF78739": ["Jean-Pierre", "Quiroul", "15/09/1992", "M"], "ED22230": ["Ren\u00e9", "Nuphard", "25/12/1995", "M"], "EE49948": ["Sophie", "Fonfec", "24/05/1999", "F"]}

43
main.py
View File

@ -1,40 +1,17 @@
from controllers.base import Controller
from views.base import View
def main():
view = View()
menu = Controller(view)
menu.run()
#Menu
## creer un nouveau tournoi
## enregistrer un nouveau joueur
## rapport
### afficher la liste des joueurs inscrits
### liste des tournois
### afficher un tounroi en particulier :
#### liste des joueurs du tournoi (alphab.)
#### liste des tours, matchs
# Nouveau Tournoi :
## entrer les infos :
## nom, lieu, date début, date fin, nombre de tours(opt)
# Participants / joueurs :
## besoin d'enregistrer des nouveaux joueurs ?
## selection des participant dans la liste des joueurs du club
## Creation du 1er tour : affichage du tour, de la liste des matchs (paire nom.prenom) :
## En attente saisie séquentielle des résultats pour chaque match :
### Saisie résultat match 1 : 1. Bob LEPONGE / 2. Bernard DINAMOUK / 3.Match Nul
### ?
## Tour suivant (puis itération) : affichage du tour, de la liste des matchs (paire nom.prenom) :
## etc
## Après le dernier tour : affichage du vainqueur
## sauvegarde du tournoi : tournois/{date.nom.lieu}/{date.nom.lieu}.json, matchs.json
##
if __name__ == "__main__" :
main()

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

27
models/match.py Normal file
View File

@ -0,0 +1,27 @@
from models.player import Player
class Match:
"""Get two players
print a string with both ids
return a tuple of list player, score
"""
def __init__(self, player1, player2):
self.name = None
self.player1 = player1
self.player2 = player2
self.score1 = 0
self.score2 = 0
self.data = ([self.player1, self.score1], [self.player2, self.score2])
def __str__(self):
return f"[{self.player1}, {self.player2}]" #pretty print for prompt
def __repr__(self):
#return ([self.player1, self.score1], [self.player2, self.score2])
return str(self)
def update(self):
"""Update tuple when attributs have change"""
self.data = ([self.player1, self.score1], [self.player2, self.score2])
return self.data

49
models/participant.py Normal file
View File

@ -0,0 +1,49 @@
from collections import UserDict
import json
from models.player import Player
class Participant(UserDict):
"""Dict of players and score attending a tournament
takes tournament's name and list of object Player
returns dict with player: score"""
def __init__(self, player_list = None):
#self.tournament
self.player_list = player_list
self.identifiant = ()
self.data = {}
self.PLAYERS_FILE = "./data/players/player_list.json"
# initiate list
def create_participant_from_list(self, players):
for item in players:
self.data[item.chess_id] = 0
return self.data
def get_list_from_file(self):
with open(self.PLAYERS_FILE) as file:
self.data = json.load(file)
def get_players_from_file(self):
"""create a Player list from the json file
uses file in current folder
return a list of object Player
"""
players = []
data = {}
with open(self.PLAYERS_FILE) as file:
data = json.load(file)
for i in data:
players.append(
Player(name=data[i][0], lastname=data[i][1], birthdate=data[i][2], gender=data[i][3], chess_id=i))
# print(data[i][0])
j = + 1
return self.create_participant_from_list(players)
def ask_for_new_participant(self):
pass

20
models/player.py Normal file
View File

@ -0,0 +1,20 @@
import json
from datetime import datetime
class Player:
"""Player from the club"""
def __init__(self, name, lastname, birthdate, gender, chess_id=None):
self.name = name
self.lastname = lastname
self.birthdate = birthdate
self.gender = gender
self.chess_id = chess_id
def __str__(self):
"""Used in print"""
# return f"{self.name} {self.lastname}, né le {self.birthdate}, genre: {self.gender}"
return self.chess_id
def __repr__(self):
return str(self)

4
models/scorelist.py Normal file
View File

@ -0,0 +1,4 @@
class ScoreList(list):
"""Player tuple (name, lastname) and score"""
def __init__(self):

31
models/tournament.py Normal file
View File

@ -0,0 +1,31 @@
from models.participant import Participant
from models.turn import Turn
class Tournament:
"""A competition with players and turns
takes player_list
"""
def __init__(self,
name,
participants,
location = "Club",
date_start = "today",
date_end = 'today',
current_turn = 1,
total_turn = 4 ):
self.name = name
self.participants = participants
self.location = location
self.date_start = date_start
self.date_end = date_end
self.total_turn = total_turn
self.current_turn = current_turn
self.description = "Pas encore de description"
self.turn_list = []
def run_turns(self):
pass
#if self.current_turn == "Round 1":

74
models/turn.py Normal file
View File

@ -0,0 +1,74 @@
from random import choice, shuffle
from models.participant import Participant
from models.match import Match
class Turn:
"""Round for tournament
has name, dict of participant (object)
"""
def __init__(self, participants, name="Round 1"):
self.name = name
self.participants = participants
self.match_history = []
self.match_list = []
self.match_result = []
self.player_list = []
def create_player_list(self): #not used for now
"""name list from dict"""
for player in self.participants:
self.player_list.append([player[0], player[1]])
def ramble_player_list(self):
"""shuffle player's list"""
return shuffle(self.player_list)
def sort_scores(self, player_list):
"""order players on score"""
def score(couple):
return couple[1]
return sorted(player_list, key=score)
def sort_players_by_score(self):
return sorted(self.participants.items(), key=lambda t: t[1])
def create_match(self):
print("Liste des joueurs: ", self.player_list)
j = 0
for i in range(0, len(self.player_list), 2):
j += 1
match = Match(self.player_list[i][0], self.player_list[i+1][0])
match.name = "match" + str(j)
if match in self.match_history: # If match has already been made, choose the next player
match = Match(self.player_list[i][0], self.player_list[i+2][0])
self.match_list.append(match)
else:
self.match_list.append(match)
#print(match)
self.match_history.append([self.name, self.match_list])
return self.match_list
# if i.index
def input_scores(self):
for match in self.match_list:
print(match.name)
self.result = input(f"Vainqueur du {match.name} : 1.{match.player1}, 2.{match.player2}, 3.nul\n ? ")
if self.result == "1":
self.participants[match.player1] += 1
match.score1 += 1
if self.result == "2":
self.participants[match.player2] += 1
match.score2 += 1
if self.result == "3":
self.participants[match.player1] += 0.5
match.score1 += 0.5
self.participants[match.player2] += 0.5
match.score2 += 0.5
match.update() # update match then save it at the end of the turn
self.match_result.append(match.data)
return self.match_result

1
player_list.json Normal file
View File

@ -0,0 +1 @@
{"EF34924": ["Bob", "Durand", "25/12/1995", "M"], "QS42622": ["Joe", "Bidjoba", "02/01/2001", "M"], "AB20022": ["Jeanine", "Mequesurton", "25/12/1995", "F"], "JF78739": ["Jean-Pierre", "Quiroul", "15/09/1992", "M"], "ED22230": ["Ren\u00e9", "Nuphard", "25/12/1995", "M"], "EE49948": ["Sophie", "Fonfec", "24/05/1999", "F"]}

View File

@ -1,14 +0,0 @@
class Menu:
def items(self):
print("[1] Créer un nouveau tournoi", end='\n')
print("[2] Enregistrer un nouveau joueur", end='\n')
print("[3] Rapports", end='\n')
print("[4] Quitter", end='\n')
def rapports():
print("[1] Afficher la liste des joueurs", end='\n')
print("[2] Afficher l'historique des tournois", end='\n')
print("[3] Afficher le détail d'un tournoi", end='\n')
print("[4] Quitter", end='\n')

View File

@ -1,19 +0,0 @@
import json
class Player:
"""Define player, should store only data for now ? Don't see further"""
def get_new_player(self):
get_player = {}
print("Enregistrez un nouveau joueur :\n")
get_player['lastname'] = input('Nom de famille :\n')
get_player['name'] = input('Prénom :\n')
get_player['birth_date'] = input('Date de naissance :\n')
#convert dict in json object and write it in players.json file (with "a" append to file)
with open("players.json", "a") as output:
output.write(json.dumps(get_player, indent=3))
new = Player()
new.get_new_player()

Binary file not shown.

9
views/base.py Normal file
View File

@ -0,0 +1,9 @@
class View:
"""Prompt menu, get choices"""
def __init__(self):
pass
def prompt_for_scores(self):
print()
input("Saisir les scores ?")
return True

33
views/menu.py Normal file
View File

@ -0,0 +1,33 @@
class Menu:
def __init__(self):
self.ITEMS = [
"[1] Créer un nouveau tournoi",
"[2] Enregistrer un nouveau joueur",
"[3] Rapports",
"[4] Quitter"
]
self.RAPPORTS = [
"[1] Afficher la liste des joueurs",
"[2] Afficher l'historique des tournois",
"[3] Afficher le détail d'un tournoi",
"[4] Quitter"
]
def items(self, value):
menu_type = []
if value == 1:
menu_type = self.ITEMS
if value == 2:
menu_type = self.RAPPORTS
for i in menu_type:
print(i)
try:
demande = input("Choix ? : ")
if demande not in range(1, len(menu_type)):
demande = input("Choix ? : ")
except ValueError:
print("Veuillez saisir un chiffre")
demande = input("Choix ? : ")
return demande

151
vrac.py
View File

@ -1,7 +1,150 @@
# generate player list
from models.participant import Participant
from models.player import Player
from models.match import Match
from models.turn import Turn
from models.tournament import Tournament
from views.base import View
from random import randint
import json
list = []
for i in range(16):
list.append(["Player"+str(i+1), randint(0, 8)])
# generate player list
def generate_liste():
liste = []
for i in range(16):
liste.append(["Player"+str(i+1), randint(0, 8)])
return liste
def create_player_list_file(player_list):
"""create a JSON file using a Player list
takes a list of object Player
returns nothing but write file"""
player_dict = {}
for i in player_list:
player_dict[i.chess_id] = [i.name, i.lastname, i.birthdate, i.gender]
# print(player_dict)
with open("player_list.json", "a") as file:
json.dump(player_dict, file)
print("done.")
def get_list_from_file():
"""create a Player list from the json file
uses file in current folder
return a list of object Player
"""
players = []
data = {}
with open("player_list.json") as file:
data = json.load(file)
for i in data:
players.append(Player(name = data[i][0], lastname = data[i][1], birthdate = data[i][2], gender = data[i][3], chess_id = i))
#print(data[i][0])
j =+ 1
return players
# joueur'data.index[i]' = Player(name = i)
def chess_id_from_name(name, player_list):
for i in player_list:
if str(name) == str(i.name + " " + i.lastname):
return i.chess_id
return None
def name_from_chess_id(chess_id, player_list):
for i in player_list:
if str(chess_id) == str(i.chess_id):
return str(i.name + " " + i.lastname)
return None
joueur1 = Player("Bob", "Durand", "25/12/1995", "M", "EF34924")
joueur2 = Player("Joe", "Bidjoba", "02/01/2001", "M", "QS42622")
joueur3 = Player("Jeanine", "Mequesurton", "25/12/1995", "F", "AB20022")
joueur4 = Player("Jean-Pierre", "Quiroul", "15/09/1992", "M", "JF78739")
joueur5 = Player("René", "Nuphard", "25/12/1995", "M", "ED22230")
joueur6 = Player("Sophie", "Fonfec", "24/05/1999", "F", "EE49948")
player_list = [joueur1, joueur2, joueur3, joueur4, joueur5, joueur6]
#create_player_list_file(player_list)
#print("la player_list from file : ", get_list_from_file())
#print("La player_list crée dans le script : ", player_list)
# print(liste_from_file)
#print(chess_id_from_name("Joe Bidjoba", player_list))
#print(name_from_chess_id("JF78739", player_list))
def test2(player_list):
# create new participants object (dict from list)...
participants = Participant("Tournoi de cajou", player_list)
# display the dict
print("print(participants) : ", participants.create_participant_from_list())
print(participants.data)
tour1 = Turn(participants.data)
print(tour1.create_match())
tour1.input_scores()
print(participants)
def test(player_list):
participants = Participant("Tournoi de cajou", player_list)
print("print(participants) : ", participants.create_participant_from_list())
print("Le score de ('Joe', 'Bidjoba') : ", participants.get((chess_id_from_name("Joe Bidjoba", player_list))))
match = Match(joueur1, joueur3)
print("print(match): ", match)
match.score2=1
print("print(match), après match.score2=1: ", match)
turn1 = Turn(participants, "Round 1")
turn1.create_player_list()
print("turn1.player_list : ",turn1.player_list)
turn1.ramble_player_list()
turn1.create_matches()
print("turn1.match_list : ", turn1.match_list )
turn1.input_scores()
print("print(participants) : ", participants)
def test3():
# initialization
participants = Participant()
participants.get_players_from_file() #load dict from file
view = View()
tour = Turn(participants)
tournoi1 = Tournament("Tournoi de Cajou", participants)
def run_turn(turn_nb):
tour = Turn(participants.data, name = "Round"+str(turn_nb))
tour.create_match()
print(f"La liste des matchs pour le {tour.name} est :\n {tour.match_list}")
view.prompt_for_scores()
tour.input_scores()
print("Save \n", tour.name, tour.match_result)
tournoi1.turn_list.append([tour.name, tour.match_result])
while i < tournoi1.total_turn:
if tounoi1.current_turn == 1:
run_turn(turn_nb)
#for i in range(1, tournoi1.total_turn+1):
#tour = Turn(participants, name = "Round"+str(i))
#tour.
test3()