simple #1

Merged
Yann merged 10 commits from simple into dev 2025-02-13 10:32:14 +00:00
17 changed files with 272 additions and 311 deletions
Showing only changes of commit 04aa65f2a8 - Show all commits

View File

@ -1,2 +1,6 @@
## Refactored
# work in progress All models are in `models/models.py`
Sequence can be seen in `controllers/base.py` in the `Controller.run()` method
for testing purpose, the players_list is created when controller is instantiated

View File

@ -1,24 +1,107 @@
from models.tournament import Tournament from ChessTournament.models.models import Player, Tournament, Round, Match
from models.player import Player from ChessTournament.views.menu import Menu
from models.turn import Turn from random import shuffle
from models.match import Match
from views.menu import Menu
class Controller: class Controller:
def __init__(self): def __init__(self):
# loading models # loading models
self.players_list: List[Player] = [] self.players_list = []
self.score_list = [] self.score_list = []
self.tournament = Tournament()
self.round = Round()
self.match = Match()
# loading views # loading views
self.view = Menu() self.menu = Menu()
# for test
joueur1 = Player("Bob", "Durand", "25/12/1995", "EF34924")
joueur2 = Player("Joe", "Bidjoba", "02/01/2001", "QS42622")
joueur3 = Player("Jeanine", "Mequesurton", "25/12/1995", "AB20022")
joueur4 = Player("Jean-Pierre", "Quiroul", "15/09/1992", "JF78739")
joueur5 = Player("René", "Nuphard", "25/12/1995", "ED22230")
joueur6 = Player("Sophie", "Fonfec", "24/05/1999", "EE49948")
self.liste = [joueur1, joueur2, joueur3, joueur4, joueur5, joueur6]
def sort_by_score(self):
return sorted(self.tournament.players_list, key=lambda t: t.score)
def shuffle_players(self):
return shuffle(self.tournament.players_list)
def create_tournament(self):
print("Nouveau tournoi ! \n")
self.tournament.name = input("Nom du tournoi ? : ")
self.tournament.location = input("Lieu du tournoi : ")
self.tournament.date_start = input("date de début (jj/mm/aaaa) : ")
self.tournament.date_end = input("date de fin (jj/mm/aaaa) : ")
self.tournament.description = input("Description ? : ")
#self.tournament.players_list = input("Liste des joueurs : ")
self.tournament.players_list = self.liste
total_round = input("Nombre de tours ? (4 par défaut) : ") or 4
if total_round != 4:
self.tournament.total_round = int(total_round)
def run_tournament(self):
input("Prêt à lancer le premier round ?\n")
#print("tour", self.tournament.current_round, round1.start_time)
for i in range(1, self.tournament.total_round):
self.round.name = "Round " + str(i)
self.tournament.current_round = self.round.name
if i == 1:
# self.tournament.players_list = self.shuffle_players()
print(self.tournament.players_list)
else:
self.tournament.players_list = self.sort_by_score()
#pour chaque tour :
# set le temps de début
# créer les matchs
# afficher les matchs
# attendre la saisie des scores
# ajouter le tour à la liste des tours du tournoi
print(self.round.name)
self.round.start_time = self.round.turn_time()
self.round.match_list = self.create_match()
#self.view.print_match_list()
print(self.round.match_list)
#self.view.prompt_for_scores()
print("saisir les scores :")
input("Round suivant ?")
def create_match(self):
"""Create match with two consecutive players. Check if match already happened in round
returns a round.match_list
"""
j = 0
k = 0
for i in range(0, len(self.tournament.players_list), 2):
j += 1
self.match.name = "match" + str(j)
print(self.match.name)
self.match.player1 = self.tournament.players_list[i]
self.match.player2 = self.tournament.players_list[i+1]
print(self.match)
if self.match in self.round.match_list:
k += 1
print(i, k)
print(self.tournament.players_list[i])
print(i + k)
#print(self.tournament.players_list[i+k].ine)
#self.match.player2 = self.tournament.players_list[i+k].ine
self.round.match_list.append(self.match.get_data())
else:
self.round.match_list.append(self.match.get_data())
return self.round.match_list
#self.tournament = Tournament(name = "Tournoi de Cajou", )
#self.turn = Turn()
def prompt_menu(self):
pass
def record_new_player(self): def record_new_player(self):
# get_player = {} # get_player = {}
@ -27,35 +110,41 @@ class Controller:
# get_player['name'] = input('Prénom :\n') # get_player['name'] = input('Prénom :\n')
#get_player['birth_date'] = input('Date de naissance :\n') #get_player['birth_date'] = input('Date de naissance :\n')
self.lastname = input("Nom de famille ? :\n") self.lastname = input("Nom de famille ? : ")
self.name = input("Prénom ? :\n") self.name = input("Prénom ? : ")
self.birthdate = input("Date de naissance (jj/mm/aaaa) ? : ")
#self.birthdate = self.check_date()
self.ine = input("Identifiant National d'Echecs (ine) ? : ")
#self.ine = self.test_ine()
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) # convert dict in json object and write it in players.json file (with "a" append to file)
# with open("players.json", "a") as output: # with open("players.json", "a") as output:
# output.write(json.dumps(get_player, indent=3)) # output.write(json.dumps(get_player, indent=3))
return {"Nom": self.lastname, "Prénom": self.name, "Date de naissance": self.birthdate, "INE": self.ine}
return {"Nom": self.lastname, "Prénom": self.name, "Date de naissance": self.birthdate, "Genre": self.gender}
def run(self): def run(self):
menu_choice = self.view.items(1) menu_choice = self.menu.items(1)
if menu_choice == 3: if menu_choice == "4":
self.view.items(2) print("Bye")
elif menu_choice == "3":
self.menu.items(2)
elif menu_choice == "2":
self.record_new_player()
elif menu_choice == "1":
print("c'est parti")
self.create_tournament()
self.run_tournament()
run = Controller()
run.run()

View File

@ -1 +0,0 @@
{"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,4 +1,4 @@
from models.player import Player from player import Player
class Match: class Match:
"""Get two players """Get two players

73
models/models.py Normal file
View File

@ -0,0 +1,73 @@
from datetime import datetime
class Tournament:
"""Chess tournament with player_list, keeps a list with all rounds"""
def __init__(self, name = None, players_list = None, location = "club", total_round = 4):
self.name = name
self.location = location
self.start = "start"
self.end = "end"
self.total_round = total_round
self.round_list = []
self.current_round = 1
self.players_list = players_list
self.description = "Pas de description"
class Player:
"""A Chess player"""
def __init__(self, name, lastname, birth_date, ine):
self.lastname = lastname
self.name = name
self.birth_date = birth_date
self.ine = ine
self.score = 0
def __str__(self):
"""Used in print"""
return self.ine
def __repr__(self):
return str(self)
class Match:
def __init__(self, player1 = None, player2 = None):
self.player1 = player1
self.player2 = player2
self.score1 = 0
self.score2 = 0
def __str__(self):
return self.player1.name + " " + self.player1.lastname + " / " + self.player2.name + " " + self.player2.lastname
def __repr__(self):
return str(self)
def create(self):
pass
def get_data(self):
return ([self.player1.ine, self.player1.score], [self.player2.ine, self.player2.score])
class Round:
def __init__(self, name = "Round 1"):
self.name = name
self.match_list = []
self.start_time = None
self.end_time = None
def turn_time(self):
return datetime.now().strftime("%d-%m-%Y, %H:%M:%S")
def create_match2(self):
pass
def start(self):
self.start_time = datetime.now().strftime("%d-%m-%Y, %H:%M:%S")
def stop(self):
self.end_time = datetime.now().strftime("%d-%m-%Y, %H:%M:%S")

View File

@ -1,6 +1,6 @@
from collections import UserDict from collections import UserDict
import json import json
from models.player import Player from player import Player
class Participants(UserDict): class Participants(UserDict):

View File

@ -2,19 +2,29 @@ import json
from datetime import datetime from datetime import datetime
class Player: class Player:
"""Player from the club""" """A chess player"""
def __init__(self, name, lastname, birthdate, gender, chess_id=None): def __init__(self, name, lastname, birthdate, ine=None, score = 0):
self.name = name self.name = name
self.lastname = lastname self.lastname = lastname
self.birthdate = birthdate self.birthdate = birthdate
self.gender = gender self.ine = ine
self.chess_id = chess_id self.score = score
def __str__(self): def __str__(self):
"""Used in print""" """Used in print"""
# return f"{self.name} {self.lastname}, né le {self.birthdate}, genre: {self.gender}" return self.ine
return self.chess_id
def __repr__(self): def __repr__(self):
return str(self) return str(self)
joueur1 = Player("Bob", "Durand", "25/12/1995", "EF34924")
joueur2 = Player("Joe", "Bidjoba", "02/01/2001", "QS42622")
joueur3 = Player("Jeanine", "Mequesurton", "25/12/1995", "AB20022")
joueur4 = Player("Jean-Pierre", "Quiroul", "15/09/1992", "JF78739")
joueur5 = Player("René", "Nuphard", "25/12/1995", "ED22230")
joueur6 = Player("Sophie", "Fonfec", "24/05/1999", "EE49948")
liste = [joueur1, joueur2, joueur3, joueur4, joueur5, joueur6]
print(joueur1)

View File

@ -1,5 +1,5 @@
from models.participant import Participants from ChessTournament.models.participant import Participants
from models.turn import Turn from ChessTournament.models.turn import Turn
class Tournament: class Tournament:

View File

@ -1,13 +1,15 @@
from random import choice, shuffle from random import choice, shuffle
from models.participant import Participants from datetime import datetime
from models.match import Match from time import sleep
from participant import Participants
from match import Match
class Turn: class Turn:
"""Round for tournament """Round for tournament
has name, dict of participant (object) has name, dict of participant (object)
""" """
def __init__(self, participants, name="Round 1"): def __init__(self, participants = None, name="Round 1"):
self.name = name self.name = name
self.participants = participants self.participants = participants
self.match_history = [] self.match_history = []
@ -15,16 +17,16 @@ class Turn:
self.match_result = [] self.match_result = []
self.player_list = [] self.player_list = []
def ramble_player_list(self): def turn_time(self):
"""shuffle player's list""" return(datetime.now())
return shuffle(self.player_list)
def sort_players_by_score(self): def sort_players_by_score(self):
"""orders dict on value and returns sorted list""" """orders dict on value and returns sorted list"""
return sorted(self.participants.items(), key=lambda t: t[1]) return sorted(self.participants.items(), key=lambda t: t[1])
def create_match(self): def create_match(self):
print("Liste des joueurs: ", self.player_list)
j = 0 j = 0
k = 0 k = 0
for i in range(0, len(self.player_list), 2): for i in range(0, len(self.player_list), 2):
@ -62,3 +64,11 @@ class Turn:
self.match_result.append(match.data) self.match_result.append(match.data)
return self.match_result return self.match_result
tour = Turn()
tour.turn_time()
sleep(3)
tour.turn_time()

View File

View File

View File

@ -1,10 +0,0 @@
{
"lastname": "Prout",
"name": "Joe",
"birth_date": "23/02/2003"
}
{
"lastname": "Dupont",
"name": "Pierre",
"birth_date": "20/01/2002"
}

View File

View File

@ -1,74 +0,0 @@
from random import choice
class Turn():
def __init__(self, name, matchs):
self.name = name
self.matchs = matchs
self.match_history = []
def rambling(self, player_list):
"""jumble (random order) players in list and return list"""
self.tmp_list = []
self.picked_player = []
for i in range(2^len(player_list)):
self.picked_player = choice(player_list)
self.tmp_list.append(self.picked_player)
return self.tmp_list
def sorting(self, player_list):
"""order players on score : use second index (for every item in the list) as key (given by function score)"""
def score(couple):
return couple[1]
return sorted(player_list, key=score)
def associate(self, player_list):
"""create a match list"""
self.match_list = []
self.couple = ()
for i in range(len(player_list)):
if i % 2 == 0 :
self.couple = (player_list[i][0], player_list[i+1][0])
if self.couple in self.match_history:
self.couple = (player_list[i][0], player_list[i + 2][0])
self.match_list.append(self.couple)
else:
self.match_list.append(self.couple)
self.match_history.append(self.name)
self.match_history.append(self.match_list)
return self.match_list
def matchmarking(self, player_list):
pass
list = [['Player1', 8],
['Player2', 2],
['Player3', 0],
['Player4', 5],
['Player5', 8],
['Player6', 3],
['Player7', 1],
['Player8', 6],
['Player9', 3],
['Player10', 4],
['Player11', 3],
['Player12', 2],
['Player13', 8],
['Player14', 4],
['Player15', 2],
['Player16', 7]]
tour = Turn("tour1", 1)
print(tour.sorting(list))
print(tour.rambling(list))
print(tour.associate(tour.sorting(list)))
print(f"Voici l'historique des matchs : {tour.match_history}")
tour2 = Turn()

View File

@ -1,3 +1,6 @@
from datetime import datetime
import re
class View: class View:
"""Prompt menu, get choices""" """Prompt menu, get choices"""
def __init__(self): def __init__(self):
@ -10,3 +13,22 @@ class View:
def display_winner(self, participants): def display_winner(self, participants):
pass pass
def check_date(self):
while True:
date = input("Date de naissance (jj/mm/aaaa) ? : ")
if datetime.strptime(date, '%d/%m/%Y'):
break
else:
print("La date doit être au format jj/mm/aaaa")
def test_ine(self):
ine_pattern = r'[a-zA-Z]{2}\d{5}'
while True:
ine = input("Identifiant National d'Echecs (ine) ? : ")
if re.match(ine_pattern, ine):
break
else:
print("Mauvais format d'ine")

View File

@ -15,19 +15,22 @@ class Menu:
] ]
def items(self, value): def items(self, value):
"""displays menu depending on given value"""
menu_type = [] menu_type = []
if value == 1: if value == 1:
menu_type = self.ITEMS menu_type = self.ITEMS
if value == 2: if value == 2:
menu_type = self.RAPPORTS menu_type = self.RAPPORTS
for i in menu_type: for i in menu_type:
print(i) print(i)
try: while True:
demande = input("Choix ? : ") try:
if demande not in range(1, len(menu_type)): choice = input("Choix ? : ")
demande = input("Choix ? : ") if int(choice) not in range(1, len(menu_type) + 1):
except ValueError: print("Veuillez saisir un chiffre entre 1 et", len(menu_type))
print("Veuillez saisir un chiffre") print(int(choice) in range(1, len(menu_type)))
demande = input("Choix ? : ") else:
return demande return choice
except ValueError:
print("Veuillez entrer un chiffre")

165
vrac.py
View File

@ -1,165 +0,0 @@
from models.participant import Participants
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
# 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 = Participants("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 = Participants(player_list)
participants.get_players_from_file() #load dict from file
view = View()
turn_nb = 1
tournoi1 = Tournament("Tournoi de Cajou", participants)
def run_turn(turn_nb):
tour = Turn(participants.data, name = "Round"+str(turn_nb))
print("Commençons le", tour.name)
if turn_nb == 1:
tour.player_list = tour.sort_players_by_score()
else:
tour.player_list = tour.sort_players_by_score()
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])
def display_winner(participants):
base =
for i in participants:
if participants[i]
print("Début du", tournoi1.name, "!")
while turn_nb < tournoi1.total_turn:
tournoi1.current_turn = turn_nb
run_turn(turn_nb)
turn_nb += 1
print("\nLe", tournoi1.name, "est terminé.\n")
print("Scores finaux:\n", participants.data)
print("liste des tours:\n", tournoi1.turn_list)
#for i in range(1, tournoi1.total_turn+1):
#tour = Turn(participants, name = "Round"+str(i))
#tour.
test3()