From 471b2c9692019d78bdc24485d8cdaf1bc3b8b69b Mon Sep 17 00:00:00 2001 From: yann Date: Thu, 30 Jan 2025 17:14:46 +0100 Subject: [PATCH 01/10] refactor with MVC folder; tests in vrac.py for now --- controllers/__init__.py | 0 .../__pycache__/__init__.cpython-310.pyc | Bin 0 -> 162 bytes controllers/__pycache__/base.cpython-310.pyc | Bin 0 -> 1646 bytes controllers/base.py | 61 +++++++ data/players/player_list.json | 1 + main.py | 43 ++--- models/__pycache__/match.cpython-310.pyc | Bin 0 -> 1174 bytes .../__pycache__/participant.cpython-310.pyc | Bin 0 -> 1982 bytes models/__pycache__/player.cpython-310.pyc | Bin 0 -> 878 bytes models/__pycache__/tournament.cpython-310.pyc | Bin 0 -> 1029 bytes models/__pycache__/turn.cpython-310.pyc | Bin 0 -> 2955 bytes models/match.py | 27 ++++ models/participant.py | 49 ++++++ models/player.py | 20 +++ models/scorelist.py | 4 + models/tournament.py | 31 ++++ models/turn.py | 74 +++++++++ player_list.json | 1 + tournoi/menu.py | 14 -- tournoi/player.py | 19 --- views/__pycache__/base.cpython-310.pyc | Bin 0 -> 637 bytes views/base.py | 9 ++ views/menu.py | 33 ++++ vrac.py | 151 +++++++++++++++++- 24 files changed, 467 insertions(+), 70 deletions(-) create mode 100644 controllers/__init__.py create mode 100644 controllers/__pycache__/__init__.cpython-310.pyc create mode 100644 controllers/__pycache__/base.cpython-310.pyc create mode 100644 controllers/base.py create mode 100644 data/players/player_list.json create mode 100644 models/__pycache__/match.cpython-310.pyc create mode 100644 models/__pycache__/participant.cpython-310.pyc create mode 100644 models/__pycache__/player.cpython-310.pyc create mode 100644 models/__pycache__/tournament.cpython-310.pyc create mode 100644 models/__pycache__/turn.cpython-310.pyc create mode 100644 models/match.py create mode 100644 models/participant.py create mode 100644 models/player.py create mode 100644 models/scorelist.py create mode 100644 models/tournament.py create mode 100644 models/turn.py create mode 100644 player_list.json delete mode 100644 tournoi/menu.py delete mode 100644 tournoi/player.py create mode 100644 views/__pycache__/base.cpython-310.pyc create mode 100644 views/base.py create mode 100644 views/menu.py diff --git a/controllers/__init__.py b/controllers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/controllers/__pycache__/__init__.cpython-310.pyc b/controllers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9401fc4e1157ccc2478717dcd3ed85317234a6a9 GIT binary patch literal 162 zcmd1j<>g`k0K0Y%q dvm`!Vub}c4hfQvNN@-529mx1%CLqDW000-vCk+4q literal 0 HcmV?d00001 diff --git a/controllers/__pycache__/base.cpython-310.pyc b/controllers/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1834512f965ff03635677011a84049cf946671f4 GIT binary patch literal 1646 zcmaJB%WfP+u)F86`9H}V&K<-{*=301vzJP<*Tx~8hSy580G#zshBeLDDg`kPP4A4qhU z1H>+D^$7q@I4wv?$CM(@3RXH}$Kp=mmfqN-$BvjE=6*X+^Z)I=0PQ2 z?tPWaWjz!6X0mrAl)6k(GI<@1N)9q5hVxSsq-kE|I!$|^P+|3a=F@-$G<4eS%lL;E za{rwObZJ3m*B(9E&+Wl0#~HDENsyM+tukvLNGvuTbb?DnABp zV0qpJPep(+*beNK9|`SPrSGi3ZDB#b(My$xIK0%+GXBys_Py z>R_mpJS7!9A=qm_(C1`f)3Bi6sMB8iT!?v;sc-XY3V!OmhnGBvb*TL`?*-DDnxsG1`4nal`+xeZ@EGf$*gB5!wKy5lNg$W=RbBl#vXGJ6K zOIb_f&1GI`>rLt-wqK`VEM0an6v18~XLmwDA zYOm~z??K{G@*o+-_RuvBl(fMaIWJ+m^@dL4JrvLxu`hQ(PQDGm1VyGazEQ@taP1(M z`p722pNfhL*_noS@S2^5E&1=bP@7Fiz(OyieYUwCvXF+ac6#l5|Cf+a?BkH5^)xkM znwB+h3dH+q`dyP1s}p$zjbp~;009nj2cTCHXAUP?VW$Qppuu|Ivs`@Fwm`8c)Ufk@ t*#~XooWH7%#Gy6o7qalQ*;meL>DaU8Z7PD>D~IpkqiZc=GxX_I_BVmqn!x}7 literal 0 HcmV?d00001 diff --git a/controllers/base.py b/controllers/base.py new file mode 100644 index 0000000..005953f --- /dev/null +++ b/controllers/base.py @@ -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) + + diff --git a/data/players/player_list.json b/data/players/player_list.json new file mode 100644 index 0000000..0eea98e --- /dev/null +++ b/data/players/player_list.json @@ -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"]} \ No newline at end of file diff --git a/main.py b/main.py index 9922a62..4a86937 100644 --- a/main.py +++ b/main.py @@ -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() + + + + diff --git a/models/__pycache__/match.cpython-310.pyc b/models/__pycache__/match.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a63f515146c742b5871f1b4a5708811425c31e GIT binary patch literal 1174 zcmZuwOK%e~5VrS~ZJHonst|{2IiW~ZmsT7Ls#K(&2#Cie2wB^;n};^pU^`Tea%=xZ z#f2MxX|J643qA3THz^UVBag>BBB#5UUyl1W~$ zG4FBCj+ykNf61hO;q^Qjd}N*Q4}4gMSJC?-J6AfV>-zF=Im9+EAQbCy$?%l-{5n)G zkbw*@Sud24Y~YM!EH`jAWE0^xtMF}R^TAvkE1TG}GMTzGrrAuerg}KBNtPH3rJtM) z?I1ZRA%@a82d(T(PvBu^(?TWXX;KW0T?W}nOkQf`9CHG_TBOrH!ZrsGk}a5E3l7N_ z9wZPz`c4K5Ho|S>_hA{)4*K3Hd4-YzgV)s@F*;EdOtP`68a0Hym9k$&u8zIsxnBh` zvsuTl0;7sk9pbT$Abv5uiR1cJIw;2~JxSk``E0Bv)}-%_KBQA!j+A|w9u1T+pGx3H zwuw#0rBsDU$JEE&>3J0kF`Nvo5E}?)S`ZOm{kHl1o@@B-$|KF zuD}bN9H;*y1mvK5&A-gOo#dK-?RaYlxF+g37`34ERYM3&P>2V(7$VFTpSM?KILoan z$jem`L$Mgo1xH@q1rvR|(D(8A|1?RGYe;m}W~;7outkfx*uT(py4&n`On)f^N$)M=#oxi+Zjfk)W=u zwT!5yX*`-*K-+O8W&w}GIF9{R;4EDbwOw;;w`R7c;W*n};i~wcF6=e2$zf@+hu&W$ CH2cf| literal 0 HcmV?d00001 diff --git a/models/__pycache__/participant.cpython-310.pyc b/models/__pycache__/participant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8249c89c854cb81e8e858dbad08a1fa943269a6 GIT binary patch literal 1982 zcmaJ?&2HQ_5GEx`EANlnq)r0^Mye!-Ru?M)ate$hg`E}!0@sLJ6j`7kWRYuYqm|aA z7Dg7@lYMK8K0pt(k9j3td-5yv;?7WOd+jvkg2NF-&CK`B47cp{+62bvuRr%^9wC3@ z!{T7@@B*fO20{=)b26fRN>O)mr|-b(=I)5~871El!Gw20geU2-+xLXCOCtXqz9bPf z!B1MMtt_p!;lba@lXp_3_-=8y@bChrehxyCJ{1If(7r2r!WHa<_Q8YjPY76Vi2zn# zEQvO(EzuEOSOe>I*>rXiRb^>5PKs*!EBXz~K{&QRPA;Mqe|XNy|DYG4)L}9I?uGVSndra*lzIHuavC7j1C3*Jj$wrx!327$L-Vs zY?lLdoSQK98i<JV@y}*_P>y807jKp6 z1WD2H51X&!u_}kMdKPaUNUeXoVk{n&LgqRiU(>!merE#Cvm&cF?;yYcgzxy&r)@f2 zS;)}(<*^&&U^QR`E|9ZDehFq!5j7c-+8NRfatQPcksN1RQ8*kq3f-6>#Q=FGB3EIN zo7S8#!?H?_u7N5H&8($LCY9t1@$-QyN0!4CIH8fAfG$Ju)2|jo|Gy7YjOcP;o-s5F zX9JW9@;ju*^p8(wv~o_}nx0|a+0W2k41UKhHrg(EO7#6BXgd78fr)$X>2~B9R*q$% zmcW)_n0v$WG7**l;K9OXgDjV~(caycl||NI#3QR<#A56M#zz;^2a6a#JbnWiQiIMc zvfn`2Co`ztnRA7(H*+mQ_l(XQz(+6f6#<}IT|`$qkmPX2YI@2luXbv-3YX0)q}yul zl?MCsJr6V{{NKGZyqesZcNo^>)JHy{Fj~{P$x)ch`!uxOi|Gxk0~sQ7A#%{PJ+}Tt zL+9gGm=$3^GdWwoWf zOjQTapVIjIa3@KndU&#>?!sb|tUf~xtI_z$7*a138dINwhk4=P=k@0xn9pbzerp$j!{`&rE_@dn_TlY{_`t%AqCmhnH_J!FbJOM=?x;zQ zdYALVNs`asv^W=K%DL)da7d;?8q`A+k5F6(X*Ikt6hgwn*T{GPakW{n6nKHxy<^`+ xzUic8p2OcmRu)=e@HT;_*W8us4S!7v(b|8xF~LR?_1DOyy+ONh4Rz^?`!D_y-sk`T literal 0 HcmV?d00001 diff --git a/models/__pycache__/player.cpython-310.pyc b/models/__pycache__/player.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e5348e00ed53626826c03228215cc984d9fec6f GIT binary patch literal 878 zcmZWny>8nu5I*XcR_z20y4UDXKpmo`V-XZ^fTD|AH0`2=utg@8p&yr|h8WtCx9Ah( zdAf1!)K}=#JE<|;mI6QC@x=S?KC+$762S5O{kNOv9>5QBj)#xVTb$-4f&|Gb$Z7Q| zR}&dWW?t{@G6;=iy=nd5S0l`U&k(9ZEVg~Mi|B}jY-|b^IL!-$p7kK0 z_Yhg{BYJ&+==ULFAmIug*fI@W(5!0Zc(pQiuqNwL+YL42q8rsnr5!Ie${10~G;)Da z)wK?hKog~o2{^$7;Q{m$Tz*|-o3>WjI=gI(u2zjT*@wlaY^U3;vahoR<@?-rniw0K z)vZ*O$#z4x=et|Sg(#cS3PBu(t}SBYm$3cmsK)u@KLx}1;~<;npaY%mVT-+{Y(M*A zl$@8%e5cFCrfe*jY05rSJ;D@S7Ykvm7Gj2uAz34Te{!H5LjSQI)F(A8^4{SC(E&R6 zI($5%Ptg9C2|Lwlhg4@69H{tlhhuEa5|b>Xm=G=z0!8a8vZq3P?N-&F2$n9}0<%)> z`jp`5-@J4~n%dO#GO55pVGaRH7>}pnu%G%a*qXM{)Yq_cRQe%><8Q_~E=Y7kf^(R% GGw(OpySJkN literal 0 HcmV?d00001 diff --git a/models/__pycache__/tournament.cpython-310.pyc b/models/__pycache__/tournament.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d700b76987cd0766c82fadb8f263ed99d61d483e GIT binary patch literal 1029 zcmY*Y&2H2%5VrH5Y%0+o4v0&{EgTvlaY6_c7Kz(Zm7a33(%7_tY@FJTP*=IpC*aBx z@JhaN>MQibOtwG4j=zjOlbLU39J#ZT5E#L)-{&t}LjK}rKH!WT!O|}QIN`JG6d7Jh-OdJ>=0fDSaM8l!Z-BB{;0sqBEPL_gO91y)cbwWS9MD%th9> z)s;{>t2&+;u+&MC!7$Z#q3@KeZM2zAt+#B4GwU14tE(Fi7}nv8Cdv-1B`p00V5B2q zWOM-O=mI*U2k4GIpf?79K1Z8?qfK~D03%L-xx3ngCvpH*uQtz)E1ik1mP%wCA6=`a z#~kw5dYGI|`^PG38?~~oP;V1n8Nsvxt&JvGblfIJnyO`(uTASgDX7kNx0pG%F&a$S z=b`nqXuqlmvQjYuUJJEAND+1b{t&eXuiFpBgcTuU>af4E5o1l)7{)M;Mz=v2(D_X0X8+O4;k|uL!S;TjjBDx$_G_vw zT}?c5s&?UMlDDuATN|sPn~I^I!&YNMJ-RuVg?cbp<(~4vV_z7v31g7p z(4w3&b~#k-ohD?A%bGEDfL}jFz&vMwd=%2gAo>YF1YDfZp*WMY}TbY}L`Ydg(X6Iu#gN>OVmvXvC6sES%pi$JIZ)K(lUq19$*lh|E*-I+Bg zE9aD6`2`hHa?G6{!0(t75~rTIRY>sOjGfp?U{>>H-p-qu_x&cX*8>9W!{ax*zrpNJ zM5dbs$mh`I0|1Ww%X?{SyY(bbhA5?MefRiTYasG&T724i zyq8M(;#38#Ue41@whGWmbFi=c%`EP1^Z4OB-iTNGq`ZkLY(`P1-zlP~xtZljoXLkU zF|@#f^)lUW_{v5_s@jwSrKuR)Jcg5(747?IKNr>yw6eoW=_p z)WpF70~YCsVLWK%uH=HJV$7lp^L{9kT%?zZi2))oKtu%rh65xUH_3;CEIluTqtE#O zXf)qG9eX(XU!>RMnUiZ=Ea(HpdpKA|GpHr;F@n?JGbXG~or9*9D6G$Ften@Dn_9jg z%c)*gV2?4`5u45w|DPkysX$;HoMTU1fq%E~KZba@cE*zN1sQGc8zr3SU=rv?4VG4e z@$74OP>A5160T|~&mZ{_P->m8(DM3!-#nuhRLN<4{tie14x@b;ixfMc1>>x+jCXVE z(1O_g;sB%8zE5D)#+4DoF2=8!b971}|0rOyubY1*!@&?YpfbLeg^b~SN8uCWexbusIU?@wrpn6FzHoq4S+Wo&BVNUw=r;mgyJ4F=L%WK0#2x&7&P26w3enem z0t6D>yGCugLVbFR&e4D&oMX$DOUs4nw4?XTmj5drGj1G+Uuihb6OjMW4otI2(z|2D`2aV<4Cl=X+3}J&35o09sHLVA< zUyo^>3$&Fntu_Vsfi|Bxw=#1sVB>S~W^>v!MTHxR%7`8X$55Z)tm;t>XzQjhAPy!D zw#xbsai{+ZZ5#4oSUTZ@aJ^aDYvD$-tgeOkn*CuGgpWc+*NwgDhNAa&L37alc+{9P zw#160?F)6WKNuFuGeNaJnQSQ66i^+JP(?9Gu8&7p91b`X6oF}4JBG3WkH=-`a>vjY zjWgkAuuo#X2xvfWLtjS6n1YD=bRMeh*hQvyZ#Ag!U~{926&kB$6saJJ;Mp;RG7_m; z6ulb8*?7f^BAzEvByJ$LHxXdU5VsMai;5-!e6CJ;v-WGOo&xg(Muo(h=@XjMOAv%|krZ=py?U5x$7o literal 0 HcmV?d00001 diff --git a/models/match.py b/models/match.py new file mode 100644 index 0000000..fc1cf0a --- /dev/null +++ b/models/match.py @@ -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 diff --git a/models/participant.py b/models/participant.py new file mode 100644 index 0000000..7ac702c --- /dev/null +++ b/models/participant.py @@ -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 + diff --git a/models/player.py b/models/player.py new file mode 100644 index 0000000..8091637 --- /dev/null +++ b/models/player.py @@ -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) + diff --git a/models/scorelist.py b/models/scorelist.py new file mode 100644 index 0000000..010935a --- /dev/null +++ b/models/scorelist.py @@ -0,0 +1,4 @@ + +class ScoreList(list): + """Player tuple (name, lastname) and score""" + def __init__(self): diff --git a/models/tournament.py b/models/tournament.py new file mode 100644 index 0000000..b104e23 --- /dev/null +++ b/models/tournament.py @@ -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": + diff --git a/models/turn.py b/models/turn.py new file mode 100644 index 0000000..82acf53 --- /dev/null +++ b/models/turn.py @@ -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 + diff --git a/player_list.json b/player_list.json new file mode 100644 index 0000000..0eea98e --- /dev/null +++ b/player_list.json @@ -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"]} \ No newline at end of file diff --git a/tournoi/menu.py b/tournoi/menu.py deleted file mode 100644 index 38c347d..0000000 --- a/tournoi/menu.py +++ /dev/null @@ -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') diff --git a/tournoi/player.py b/tournoi/player.py deleted file mode 100644 index d64df1e..0000000 --- a/tournoi/player.py +++ /dev/null @@ -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() diff --git a/views/__pycache__/base.cpython-310.pyc b/views/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3003b64720922bdee7728f8d30ddb1c1cbb9f8a GIT binary patch literal 637 zcmZuuy-or_5Z=8XI0+PDVl1yEFH3IVT`Zj(C|AE18u_5Sy>L!>g!U?BK(1jHdZuLmZ zjv@a?EQmUw+6N;@L^+8pP9vLJ++LE%;SP7fySxJZ)xx<;#MAufM#))b{FzAeV}C4+ zA5UZw3msD!vlTp}c0siRh7*`U!xdT4!qH+nQuusnK2L**oQYr Date: Fri, 31 Jan 2025 09:43:02 +0100 Subject: [PATCH 02/10] adapt folders to MVC --- models/participant.py | 9 +++------ models/scorelist.py | 4 ---- models/tournament.py | 5 +---- models/turn.py | 22 ++++++---------------- views/base.py | 5 ++++- vrac.py | 29 ++++++++++++++++++++++------- 6 files changed, 36 insertions(+), 38 deletions(-) delete mode 100644 models/scorelist.py diff --git a/models/participant.py b/models/participant.py index 7ac702c..468dc33 100644 --- a/models/participant.py +++ b/models/participant.py @@ -3,19 +3,16 @@ import json from models.player import Player -class Participant(UserDict): +class Participants(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): + def __init__(self, player_list): #player_list FOR TEST ; to feed when creating object #self.tournament self.player_list = player_list - self.identifiant = () self.data = {} - self.PLAYERS_FILE = "./data/players/player_list.json" - # initiate list - + self.PLAYERS_FILE = "./data/players/player_list.json" #FOR TEST def create_participant_from_list(self, players): for item in players: diff --git a/models/scorelist.py b/models/scorelist.py deleted file mode 100644 index 010935a..0000000 --- a/models/scorelist.py +++ /dev/null @@ -1,4 +0,0 @@ - -class ScoreList(list): - """Player tuple (name, lastname) and score""" - def __init__(self): diff --git a/models/tournament.py b/models/tournament.py index b104e23..a16a69b 100644 --- a/models/tournament.py +++ b/models/tournament.py @@ -1,4 +1,4 @@ -from models.participant import Participant +from models.participant import Participants from models.turn import Turn @@ -25,7 +25,4 @@ class Tournament: self.description = "Pas encore de description" self.turn_list = [] - def run_turns(self): - pass - #if self.current_turn == "Round 1": diff --git a/models/turn.py b/models/turn.py index 82acf53..a936da4 100644 --- a/models/turn.py +++ b/models/turn.py @@ -1,5 +1,5 @@ from random import choice, shuffle -from models.participant import Participant +from models.participant import Participants from models.match import Match class Turn: @@ -15,35 +15,25 @@ class Turn: 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): + """orders dict on value and returns sorted list""" return sorted(self.participants.items(), key=lambda t: t[1]) - def create_match(self): print("Liste des joueurs: ", self.player_list) j = 0 + k = 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]) + while match in self.match_history: + k += 1# If match has already been made, choose the next player + match = Match(self.player_list[i][0], self.player_list[i+k][0]) self.match_list.append(match) else: self.match_list.append(match) diff --git a/views/base.py b/views/base.py index c57baae..d86111c 100644 --- a/views/base.py +++ b/views/base.py @@ -6,4 +6,7 @@ class View: def prompt_for_scores(self): print() input("Saisir les scores ?") - return True \ No newline at end of file + return True + + def display_winner(self, participants): + pass diff --git a/vrac.py b/vrac.py index 68d7800..3923e64 100644 --- a/vrac.py +++ b/vrac.py @@ -1,4 +1,4 @@ -from models.participant import Participant +from models.participant import Participants from models.player import Player from models.match import Match from models.turn import Turn @@ -78,7 +78,7 @@ player_list = [joueur1, joueur2, joueur3, joueur4, joueur5, joueur6] #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) + participants = Participants("Tournoi de cajou", player_list) # display the dict print("print(participants) : ", participants.create_participant_from_list()) print(participants.data) @@ -117,15 +117,21 @@ def test(player_list): def test3(): # initialization - participants = Participant() + participants = Participants(player_list) participants.get_players_from_file() #load dict from file view = View() - tour = Turn(participants) + 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() @@ -133,11 +139,20 @@ def test3(): 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: + 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 - run_turn(turn_nb) + 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)) -- 2.39.5 From c30d9078479b2699f9945c6c819f8971997e31ec Mon Sep 17 00:00:00 2001 From: yann Date: Fri, 31 Jan 2025 09:47:40 +0100 Subject: [PATCH 03/10] clean __pycache__ should be ignored --- controllers/__pycache__/__init__.cpython-310.pyc | Bin 162 -> 0 bytes controllers/__pycache__/base.cpython-310.pyc | Bin 1646 -> 0 bytes models/__pycache__/match.cpython-310.pyc | Bin 1174 -> 0 bytes models/__pycache__/participant.cpython-310.pyc | Bin 1982 -> 0 bytes models/__pycache__/player.cpython-310.pyc | Bin 878 -> 0 bytes models/__pycache__/tournament.cpython-310.pyc | Bin 1029 -> 0 bytes models/__pycache__/turn.cpython-310.pyc | Bin 2955 -> 0 bytes views/__pycache__/base.cpython-310.pyc | Bin 637 -> 0 bytes 8 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 controllers/__pycache__/__init__.cpython-310.pyc delete mode 100644 controllers/__pycache__/base.cpython-310.pyc delete mode 100644 models/__pycache__/match.cpython-310.pyc delete mode 100644 models/__pycache__/participant.cpython-310.pyc delete mode 100644 models/__pycache__/player.cpython-310.pyc delete mode 100644 models/__pycache__/tournament.cpython-310.pyc delete mode 100644 models/__pycache__/turn.cpython-310.pyc delete mode 100644 views/__pycache__/base.cpython-310.pyc diff --git a/controllers/__pycache__/__init__.cpython-310.pyc b/controllers/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 9401fc4e1157ccc2478717dcd3ed85317234a6a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 162 zcmd1j<>g`k0K0Y%q dvm`!Vub}c4hfQvNN@-529mx1%CLqDW000-vCk+4q diff --git a/controllers/__pycache__/base.cpython-310.pyc b/controllers/__pycache__/base.cpython-310.pyc deleted file mode 100644 index 1834512f965ff03635677011a84049cf946671f4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1646 zcmaJB%WfP+u)F86`9H}V&K<-{*=301vzJP<*Tx~8hSy580G#zshBeLDDg`kPP4A4qhU z1H>+D^$7q@I4wv?$CM(@3RXH}$Kp=mmfqN-$BvjE=6*X+^Z)I=0PQ2 z?tPWaWjz!6X0mrAl)6k(GI<@1N)9q5hVxSsq-kE|I!$|^P+|3a=F@-$G<4eS%lL;E za{rwObZJ3m*B(9E&+Wl0#~HDENsyM+tukvLNGvuTbb?DnABp zV0qpJPep(+*beNK9|`SPrSGi3ZDB#b(My$xIK0%+GXBys_Py z>R_mpJS7!9A=qm_(C1`f)3Bi6sMB8iT!?v;sc-XY3V!OmhnGBvb*TL`?*-DDnxsG1`4nal`+xeZ@EGf$*gB5!wKy5lNg$W=RbBl#vXGJ6K zOIb_f&1GI`>rLt-wqK`VEM0an6v18~XLmwDA zYOm~z??K{G@*o+-_RuvBl(fMaIWJ+m^@dL4JrvLxu`hQ(PQDGm1VyGazEQ@taP1(M z`p722pNfhL*_noS@S2^5E&1=bP@7Fiz(OyieYUwCvXF+ac6#l5|Cf+a?BkH5^)xkM znwB+h3dH+q`dyP1s}p$zjbp~;009nj2cTCHXAUP?VW$Qppuu|Ivs`@Fwm`8c)Ufk@ t*#~XooWH7%#Gy6o7qalQ*;meL>DaU8Z7PD>D~IpkqiZc=GxX_I_BVmqn!x}7 diff --git a/models/__pycache__/match.cpython-310.pyc b/models/__pycache__/match.cpython-310.pyc deleted file mode 100644 index c7a63f515146c742b5871f1b4a5708811425c31e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1174 zcmZuwOK%e~5VrS~ZJHonst|{2IiW~ZmsT7Ls#K(&2#Cie2wB^;n};^pU^`Tea%=xZ z#f2MxX|J643qA3THz^UVBag>BBB#5UUyl1W~$ zG4FBCj+ykNf61hO;q^Qjd}N*Q4}4gMSJC?-J6AfV>-zF=Im9+EAQbCy$?%l-{5n)G zkbw*@Sud24Y~YM!EH`jAWE0^xtMF}R^TAvkE1TG}GMTzGrrAuerg}KBNtPH3rJtM) z?I1ZRA%@a82d(T(PvBu^(?TWXX;KW0T?W}nOkQf`9CHG_TBOrH!ZrsGk}a5E3l7N_ z9wZPz`c4K5Ho|S>_hA{)4*K3Hd4-YzgV)s@F*;EdOtP`68a0Hym9k$&u8zIsxnBh` zvsuTl0;7sk9pbT$Abv5uiR1cJIw;2~JxSk``E0Bv)}-%_KBQA!j+A|w9u1T+pGx3H zwuw#0rBsDU$JEE&>3J0kF`Nvo5E}?)S`ZOm{kHl1o@@B-$|KF zuD}bN9H;*y1mvK5&A-gOo#dK-?RaYlxF+g37`34ERYM3&P>2V(7$VFTpSM?KILoan z$jem`L$Mgo1xH@q1rvR|(D(8A|1?RGYe;m}W~;7outkfx*uT(py4&n`On)f^N$)M=#oxi+Zjfk)W=u zwT!5yX*`-*K-+O8W&w}GIF9{R;4EDbwOw;;w`R7c;W*n};i~wcF6=e2$zf@+hu&W$ CH2cf| diff --git a/models/__pycache__/participant.cpython-310.pyc b/models/__pycache__/participant.cpython-310.pyc deleted file mode 100644 index b8249c89c854cb81e8e858dbad08a1fa943269a6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1982 zcmaJ?&2HQ_5GEx`EANlnq)r0^Mye!-Ru?M)ate$hg`E}!0@sLJ6j`7kWRYuYqm|aA z7Dg7@lYMK8K0pt(k9j3td-5yv;?7WOd+jvkg2NF-&CK`B47cp{+62bvuRr%^9wC3@ z!{T7@@B*fO20{=)b26fRN>O)mr|-b(=I)5~871El!Gw20geU2-+xLXCOCtXqz9bPf z!B1MMtt_p!;lba@lXp_3_-=8y@bChrehxyCJ{1If(7r2r!WHa<_Q8YjPY76Vi2zn# zEQvO(EzuEOSOe>I*>rXiRb^>5PKs*!EBXz~K{&QRPA;Mqe|XNy|DYG4)L}9I?uGVSndra*lzIHuavC7j1C3*Jj$wrx!327$L-Vs zY?lLdoSQK98i<JV@y}*_P>y807jKp6 z1WD2H51X&!u_}kMdKPaUNUeXoVk{n&LgqRiU(>!merE#Cvm&cF?;yYcgzxy&r)@f2 zS;)}(<*^&&U^QR`E|9ZDehFq!5j7c-+8NRfatQPcksN1RQ8*kq3f-6>#Q=FGB3EIN zo7S8#!?H?_u7N5H&8($LCY9t1@$-QyN0!4CIH8fAfG$Ju)2|jo|Gy7YjOcP;o-s5F zX9JW9@;ju*^p8(wv~o_}nx0|a+0W2k41UKhHrg(EO7#6BXgd78fr)$X>2~B9R*q$% zmcW)_n0v$WG7**l;K9OXgDjV~(caycl||NI#3QR<#A56M#zz;^2a6a#JbnWiQiIMc zvfn`2Co`ztnRA7(H*+mQ_l(XQz(+6f6#<}IT|`$qkmPX2YI@2luXbv-3YX0)q}yul zl?MCsJr6V{{NKGZyqesZcNo^>)JHy{Fj~{P$x)ch`!uxOi|Gxk0~sQ7A#%{PJ+}Tt zL+9gGm=$3^GdWwoWf zOjQTapVIjIa3@KndU&#>?!sb|tUf~xtI_z$7*a138dINwhk4=P=k@0xn9pbzerp$j!{`&rE_@dn_TlY{_`t%AqCmhnH_J!FbJOM=?x;zQ zdYALVNs`asv^W=K%DL)da7d;?8q`A+k5F6(X*Ikt6hgwn*T{GPakW{n6nKHxy<^`+ xzUic8p2OcmRu)=e@HT;_*W8us4S!7v(b|8xF~LR?_1DOyy+ONh4Rz^?`!D_y-sk`T diff --git a/models/__pycache__/player.cpython-310.pyc b/models/__pycache__/player.cpython-310.pyc deleted file mode 100644 index 9e5348e00ed53626826c03228215cc984d9fec6f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 878 zcmZWny>8nu5I*XcR_z20y4UDXKpmo`V-XZ^fTD|AH0`2=utg@8p&yr|h8WtCx9Ah( zdAf1!)K}=#JE<|;mI6QC@x=S?KC+$762S5O{kNOv9>5QBj)#xVTb$-4f&|Gb$Z7Q| zR}&dWW?t{@G6;=iy=nd5S0l`U&k(9ZEVg~Mi|B}jY-|b^IL!-$p7kK0 z_Yhg{BYJ&+==ULFAmIug*fI@W(5!0Zc(pQiuqNwL+YL42q8rsnr5!Ie${10~G;)Da z)wK?hKog~o2{^$7;Q{m$Tz*|-o3>WjI=gI(u2zjT*@wlaY^U3;vahoR<@?-rniw0K z)vZ*O$#z4x=et|Sg(#cS3PBu(t}SBYm$3cmsK)u@KLx}1;~<;npaY%mVT-+{Y(M*A zl$@8%e5cFCrfe*jY05rSJ;D@S7Ykvm7Gj2uAz34Te{!H5LjSQI)F(A8^4{SC(E&R6 zI($5%Ptg9C2|Lwlhg4@69H{tlhhuEa5|b>Xm=G=z0!8a8vZq3P?N-&F2$n9}0<%)> z`jp`5-@J4~n%dO#GO55pVGaRH7>}pnu%G%a*qXM{)Yq_cRQe%><8Q_~E=Y7kf^(R% GGw(OpySJkN diff --git a/models/__pycache__/tournament.cpython-310.pyc b/models/__pycache__/tournament.cpython-310.pyc deleted file mode 100644 index d700b76987cd0766c82fadb8f263ed99d61d483e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1029 zcmY*Y&2H2%5VrH5Y%0+o4v0&{EgTvlaY6_c7Kz(Zm7a33(%7_tY@FJTP*=IpC*aBx z@JhaN>MQibOtwG4j=zjOlbLU39J#ZT5E#L)-{&t}LjK}rKH!WT!O|}QIN`JG6d7Jh-OdJ>=0fDSaM8l!Z-BB{;0sqBEPL_gO91y)cbwWS9MD%th9> z)s;{>t2&+;u+&MC!7$Z#q3@KeZM2zAt+#B4GwU14tE(Fi7}nv8Cdv-1B`p00V5B2q zWOM-O=mI*U2k4GIpf?79K1Z8?qfK~D03%L-xx3ngCvpH*uQtz)E1ik1mP%wCA6=`a z#~kw5dYGI|`^PG38?~~oP;V1n8Nsvxt&JvGblfIJnyO`(uTASgDX7kNx0pG%F&a$S z=b`nqXuqlmvQjYuUJJEAND+1b{t&eXuiFpBgcTuU>af4E5o1l)7{)M;Mz=v2(D_X0X8+O4;k|uL!S;TjjBDx$_G_vw zT}?c5s&?UMlDDuATN|sPn~I^I!&YNMJ-RuVg?cbp<(~4vV_z7v31g7p z(4w3&b~#k-ohD?A%bGEDfL}jFz&vMwd=%2gAo>YF1YDfZp*WMY}TbY}L`Ydg(X6Iu#gN>OVmvXvC6sES%pi$JIZ)K(lUq19$*lh|E*-I+Bg zE9aD6`2`hHa?G6{!0(t75~rTIRY>sOjGfp?U{>>H-p-qu_x&cX*8>9W!{ax*zrpNJ zM5dbs$mh`I0|1Ww%X?{SyY(bbhA5?MefRiTYasG&T724i zyq8M(;#38#Ue41@whGWmbFi=c%`EP1^Z4OB-iTNGq`ZkLY(`P1-zlP~xtZljoXLkU zF|@#f^)lUW_{v5_s@jwSrKuR)Jcg5(747?IKNr>yw6eoW=_p z)WpF70~YCsVLWK%uH=HJV$7lp^L{9kT%?zZi2))oKtu%rh65xUH_3;CEIluTqtE#O zXf)qG9eX(XU!>RMnUiZ=Ea(HpdpKA|GpHr;F@n?JGbXG~or9*9D6G$Ften@Dn_9jg z%c)*gV2?4`5u45w|DPkysX$;HoMTU1fq%E~KZba@cE*zN1sQGc8zr3SU=rv?4VG4e z@$74OP>A5160T|~&mZ{_P->m8(DM3!-#nuhRLN<4{tie14x@b;ixfMc1>>x+jCXVE z(1O_g;sB%8zE5D)#+4DoF2=8!b971}|0rOyubY1*!@&?YpfbLeg^b~SN8uCWexbusIU?@wrpn6FzHoq4S+Wo&BVNUw=r;mgyJ4F=L%WK0#2x&7&P26w3enem z0t6D>yGCugLVbFR&e4D&oMX$DOUs4nw4?XTmj5drGj1G+Uuihb6OjMW4otI2(z|2D`2aV<4Cl=X+3}J&35o09sHLVA< zUyo^>3$&Fntu_Vsfi|Bxw=#1sVB>S~W^>v!MTHxR%7`8X$55Z)tm;t>XzQjhAPy!D zw#xbsai{+ZZ5#4oSUTZ@aJ^aDYvD$-tgeOkn*CuGgpWc+*NwgDhNAa&L37alc+{9P zw#160?F)6WKNuFuGeNaJnQSQ66i^+JP(?9Gu8&7p91b`X6oF}4JBG3WkH=-`a>vjY zjWgkAuuo#X2xvfWLtjS6n1YD=bRMeh*hQvyZ#Ag!U~{926&kB$6saJJ;Mp;RG7_m; z6ulb8*?7f^BAzEvByJ$LHxXdU5VsMai;5-!e6CJ;v-WGOo&xg(Muo(h=@XjMOAv%|krZ=py?U5x$7o diff --git a/views/__pycache__/base.cpython-310.pyc b/views/__pycache__/base.cpython-310.pyc deleted file mode 100644 index e3003b64720922bdee7728f8d30ddb1c1cbb9f8a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 637 zcmZuuy-or_5Z=8XI0+PDVl1yEFH3IVT`Zj(C|AE18u_5Sy>L!>g!U?BK(1jHdZuLmZ zjv@a?EQmUw+6N;@L^+8pP9vLJ++LE%;SP7fySxJZ)xx<;#MAufM#))b{FzAeV}C4+ zA5UZw3msD!vlTp}c0siRh7*`U!xdT4!qH+nQuusnK2L**oQYr Date: Wed, 5 Feb 2025 13:47:52 +0100 Subject: [PATCH 04/10] refactored from simpliest models --- README.md | 6 +- controllers/base.py | 157 +++++++++++++++++++++++++------- data/players/player_list.json | 1 - models/match.py | 2 +- models/models.py | 73 +++++++++++++++ models/participant.py | 2 +- models/player.py | 22 +++-- models/tournament.py | 4 +- models/turn.py | 24 +++-- tournoi/__init_.py | 0 tournoi/match.py | 0 tournoi/players.json | 10 --- tournoi/tournament.py | 0 tournoi/turn.py | 74 --------------- views/base.py | 22 +++++ views/menu.py | 21 +++-- vrac.py | 165 ---------------------------------- 17 files changed, 272 insertions(+), 311 deletions(-) delete mode 100644 data/players/player_list.json create mode 100644 models/models.py delete mode 100644 tournoi/__init_.py delete mode 100644 tournoi/match.py delete mode 100644 tournoi/players.json delete mode 100644 tournoi/tournament.py delete mode 100644 tournoi/turn.py delete mode 100644 vrac.py diff --git a/README.md b/README.md index aef916a..19985a1 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/controllers/base.py b/controllers/base.py index 005953f..01db806 100644 --- a/controllers/base.py +++ b/controllers/base.py @@ -1,24 +1,107 @@ -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 +from ChessTournament.models.models import Player, Tournament, Round, Match +from ChessTournament.views.menu import Menu +from random import shuffle + class Controller: def __init__(self): # loading models - self.players_list: List[Player] = [] + self.players_list = [] self.score_list = [] - - + self.tournament = Tournament() + self.round = Round() + self.match = Match() # 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): # get_player = {} @@ -27,35 +110,41 @@ class Controller: # 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") + self.lastname = input("Nom de famille ? : ") + 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) # 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, "INE": self.ine} - 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) + menu_choice = self.menu.items(1) + if menu_choice == "4": + 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() + diff --git a/data/players/player_list.json b/data/players/player_list.json deleted file mode 100644 index 0eea98e..0000000 --- a/data/players/player_list.json +++ /dev/null @@ -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"]} \ No newline at end of file diff --git a/models/match.py b/models/match.py index fc1cf0a..81b6456 100644 --- a/models/match.py +++ b/models/match.py @@ -1,4 +1,4 @@ -from models.player import Player +from player import Player class Match: """Get two players diff --git a/models/models.py b/models/models.py new file mode 100644 index 0000000..d7cb450 --- /dev/null +++ b/models/models.py @@ -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") + diff --git a/models/participant.py b/models/participant.py index 468dc33..9e6f718 100644 --- a/models/participant.py +++ b/models/participant.py @@ -1,6 +1,6 @@ from collections import UserDict import json -from models.player import Player +from player import Player class Participants(UserDict): diff --git a/models/player.py b/models/player.py index 8091637..8fe54e6 100644 --- a/models/player.py +++ b/models/player.py @@ -2,19 +2,29 @@ import json from datetime import datetime class Player: - """Player from the club""" - def __init__(self, name, lastname, birthdate, gender, chess_id=None): + """A chess player""" + def __init__(self, name, lastname, birthdate, ine=None, score = 0): self.name = name self.lastname = lastname self.birthdate = birthdate - self.gender = gender - self.chess_id = chess_id + self.ine = ine + self.score = score def __str__(self): """Used in print""" -# return f"{self.name} {self.lastname}, né le {self.birthdate}, genre: {self.gender}" - return self.chess_id + return self.ine def __repr__(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) \ No newline at end of file diff --git a/models/tournament.py b/models/tournament.py index a16a69b..a60071c 100644 --- a/models/tournament.py +++ b/models/tournament.py @@ -1,5 +1,5 @@ -from models.participant import Participants -from models.turn import Turn +from ChessTournament.models.participant import Participants +from ChessTournament.models.turn import Turn class Tournament: diff --git a/models/turn.py b/models/turn.py index a936da4..f2d0902 100644 --- a/models/turn.py +++ b/models/turn.py @@ -1,13 +1,15 @@ from random import choice, shuffle -from models.participant import Participants -from models.match import Match +from datetime import datetime +from time import sleep +from participant import Participants +from match import Match class Turn: """Round for tournament 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.participants = participants self.match_history = [] @@ -15,16 +17,16 @@ class Turn: self.match_result = [] self.player_list = [] - def ramble_player_list(self): - """shuffle player's list""" - return shuffle(self.player_list) + def turn_time(self): + return(datetime.now()) def sort_players_by_score(self): """orders dict on value and returns sorted list""" return sorted(self.participants.items(), key=lambda t: t[1]) + + def create_match(self): - print("Liste des joueurs: ", self.player_list) j = 0 k = 0 for i in range(0, len(self.player_list), 2): @@ -62,3 +64,11 @@ class Turn: self.match_result.append(match.data) return self.match_result + + + +tour = Turn() + +tour.turn_time() +sleep(3) +tour.turn_time() diff --git a/tournoi/__init_.py b/tournoi/__init_.py deleted file mode 100644 index e69de29..0000000 diff --git a/tournoi/match.py b/tournoi/match.py deleted file mode 100644 index e69de29..0000000 diff --git a/tournoi/players.json b/tournoi/players.json deleted file mode 100644 index 27e7345..0000000 --- a/tournoi/players.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "lastname": "Prout", - "name": "Joe", - "birth_date": "23/02/2003" -} -{ - "lastname": "Dupont", - "name": "Pierre", - "birth_date": "20/01/2002" -} \ No newline at end of file diff --git a/tournoi/tournament.py b/tournoi/tournament.py deleted file mode 100644 index e69de29..0000000 diff --git a/tournoi/turn.py b/tournoi/turn.py deleted file mode 100644 index c48c80b..0000000 --- a/tournoi/turn.py +++ /dev/null @@ -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() \ No newline at end of file diff --git a/views/base.py b/views/base.py index d86111c..ae54370 100644 --- a/views/base.py +++ b/views/base.py @@ -1,3 +1,6 @@ +from datetime import datetime +import re + class View: """Prompt menu, get choices""" def __init__(self): @@ -10,3 +13,22 @@ class View: def display_winner(self, participants): 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") + diff --git a/views/menu.py b/views/menu.py index ff7ed20..478fade 100644 --- a/views/menu.py +++ b/views/menu.py @@ -15,19 +15,22 @@ class Menu: ] def items(self, value): + """displays menu depending on given 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 + while True: + try: + choice = input("Choix ? : ") + if int(choice) not in range(1, len(menu_type) + 1): + print("Veuillez saisir un chiffre entre 1 et", len(menu_type)) + print(int(choice) in range(1, len(menu_type))) + else: + return choice + except ValueError: + print("Veuillez entrer un chiffre") + diff --git a/vrac.py b/vrac.py deleted file mode 100644 index 3923e64..0000000 --- a/vrac.py +++ /dev/null @@ -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() \ No newline at end of file -- 2.39.5 From 425c5c716b78aa574dfa37f500e158f67e364031 Mon Sep 17 00:00:00 2001 From: yann Date: Wed, 5 Feb 2025 15:20:11 +0100 Subject: [PATCH 05/10] tournament works.. but things are not in the right place --- controllers/base.py | 78 +++++++++++++++++++-------------------------- models/models.py | 6 ++-- views/base.py | 23 +++++++++++++ 3 files changed, 59 insertions(+), 48 deletions(-) diff --git a/controllers/base.py b/controllers/base.py index 01db806..99069ee 100644 --- a/controllers/base.py +++ b/controllers/base.py @@ -1,5 +1,7 @@ from ChessTournament.models.models import Player, Tournament, Round, Match from ChessTournament.views.menu import Menu +from ChessTournament.views.base import View + from random import shuffle @@ -8,11 +10,11 @@ class Controller: # loading models self.players_list = [] self.score_list = [] - self.tournament = Tournament() - self.round = Round() self.match = Match() + self.tournament = Tournament() # loading views + self.view = View() self.menu = Menu() # for test @@ -26,7 +28,7 @@ class Controller: self.liste = [joueur1, joueur2, joueur3, joueur4, joueur5, joueur6] def sort_by_score(self): - return sorted(self.tournament.players_list, key=lambda t: t.score) + self.tournament.players_list.sort(key=lambda t: t.score, reverse = True) def shuffle_players(self): return shuffle(self.tournament.players_list) @@ -40,6 +42,7 @@ class Controller: 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) @@ -48,32 +51,37 @@ class Controller: def run_tournament(self): input("Prêt à lancer le premier round ?\n") #print("tour", self.tournament.current_round, round1.start_time) + print("Liste des joueurs : ", self.tournament.players_list) + shuffle(self.tournament.players_list) for i in range(1, self.tournament.total_round): + self.round = 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.start_time = self.round.get_time() self.round.match_list = self.create_match() - #self.view.print_match_list() - print(self.round.match_list) + + print("Liste des joueurs, après tri : ", self.tournament.players_list) + print("Liste des matchs du Round : ", self.round.match_list) #self.view.prompt_for_scores() print("saisir les scores :") - input("Round suivant ?") + self.view.input_scores(self.round.match_list) + # append self.tournament.round_list with [round, match_list] + self.sort_by_score() + + print("scores du round :\n") + for i in self.tournament.players_list: + print(i.ine, " : ", i.score) + + input("Continuer ?") + def create_match(self): """Create match with two consecutive players. Check if match already happened in round @@ -82,50 +90,29 @@ class Controller: """ j = 0 k = 0 + print(self.tournament.players_list) 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()) + match_name = "match" + str(j) + match = Match() + match.player1 = self.tournament.players_list[i] + match.player2 = self.tournament.players_list[i+1] + self.round.match_list.append(match) return self.round.match_list - 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 ? : ") 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() - - - # 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, "INE": self.ine} def run(self): - menu_choice = self.menu.items(1) if menu_choice == "4": print("Bye") @@ -137,8 +124,9 @@ class Controller: print("c'est parti") self.create_tournament() self.run_tournament() - - + print("Tournoi terminé.\n Les scores sont :\n") + for i in self.tournament.players_list: + print(i.ine, " : ", i.score) diff --git a/models/models.py b/models/models.py index d7cb450..833ced7 100644 --- a/models/models.py +++ b/models/models.py @@ -39,8 +39,8 @@ class Match: self.score2 = 0 def __str__(self): - return self.player1.name + " " + self.player1.lastname + " / " + self.player2.name + " " + self.player2.lastname - + #return self.player1.name + " " + self.player1.lastname + " / " + self.player2.name + " " + self.player2.lastname + return self.player1.ine + "/" + self.player2.ine def __repr__(self): return str(self) @@ -59,7 +59,7 @@ class Round: self.start_time = None self.end_time = None - def turn_time(self): + def get_time(self): return datetime.now().strftime("%d-%m-%Y, %H:%M:%S") def create_match2(self): diff --git a/views/base.py b/views/base.py index ae54370..b40e50b 100644 --- a/views/base.py +++ b/views/base.py @@ -32,3 +32,26 @@ class View: else: print("Mauvais format d'ine") + + def input_scores(self, match_list): + for match in match_list: + print(match) + print("Scores pour match", match_list.index(match) + 1, " :") + while True: + try: + result = input(f"1.{match.player1}, 2.{match.player2}, 3.Nul\n") + if result in ("1", "2", "3"): + if result == "1": + match.player1.score += 1 + elif result == "2": + match.player2.score += 1 + elif result == "3": + match.player1.score += 0.5 + match.player2.score += 0.5 + break + else: + print("Entrez un chiffre entre 1 et 3") + except ValueError: + print("Veuillez entrer un chiffre") + + -- 2.39.5 From 195c3f6b0268e41af2528ab4a822656d705f1d38 Mon Sep 17 00:00:00 2001 From: yann Date: Thu, 6 Feb 2025 10:16:16 +0100 Subject: [PATCH 06/10] moved some methods to view --- controllers/base.py | 38 +++++++++++--------------------------- models/models.py | 2 +- views/base.py | 43 ++++++++++++++++++++++++++++++++++--------- 3 files changed, 46 insertions(+), 37 deletions(-) diff --git a/controllers/base.py b/controllers/base.py index 99069ee..cd8badc 100644 --- a/controllers/base.py +++ b/controllers/base.py @@ -67,20 +67,18 @@ class Controller: self.round.start_time = self.round.get_time() self.round.match_list = self.create_match() - - print("Liste des joueurs, après tri : ", self.tournament.players_list) - print("Liste des matchs du Round : ", self.round.match_list) - #self.view.prompt_for_scores() - print("saisir les scores :") + self.view.prompt_for_scores() + self.round.end_time = self.round.get_time() self.view.input_scores(self.round.match_list) - # append self.tournament.round_list with [round, match_list] self.sort_by_score() + self.view.display_round_info(self.round) + self.view.display_scores(self.tournament.players_list) + + print("Le tournoi", self.tournament.name, "est terminé !") + + - print("scores du round :\n") - for i in self.tournament.players_list: - print(i.ine, " : ", i.score) - input("Continuer ?") def create_match(self): @@ -101,15 +99,6 @@ class Controller: return self.round.match_list - def record_new_player(self): - print("Enregistrez un nouveau joueur :\n") - self.lastname = input("Nom de famille ? : ") - 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() - return {"Nom": self.lastname, "Prénom": self.name, "Date de naissance": self.birthdate, "INE": self.ine} def run(self): @@ -119,18 +108,13 @@ class Controller: elif menu_choice == "3": self.menu.items(2) elif menu_choice == "2": - self.record_new_player() + self.view.prompt_for_new_player() elif menu_choice == "1": print("c'est parti") self.create_tournament() self.run_tournament() - print("Tournoi terminé.\n Les scores sont :\n") - for i in self.tournament.players_list: - print(i.ine, " : ", i.score) - - - - + self.view.display_winner(self.tournament.players_list) + self.view.display_scores(self.tournament.players_list) run = Controller() diff --git a/models/models.py b/models/models.py index 833ced7..e757134 100644 --- a/models/models.py +++ b/models/models.py @@ -41,10 +41,10 @@ class Match: def __str__(self): #return self.player1.name + " " + self.player1.lastname + " / " + self.player2.name + " " + self.player2.lastname return self.player1.ine + "/" + self.player2.ine + def __repr__(self): return str(self) - def create(self): pass diff --git a/views/base.py b/views/base.py index b40e50b..728a59b 100644 --- a/views/base.py +++ b/views/base.py @@ -6,14 +6,6 @@ class View: def __init__(self): pass - def prompt_for_scores(self): - print() - input("Saisir les scores ?") - return True - - def display_winner(self, participants): - pass - def check_date(self): while True: date = input("Date de naissance (jj/mm/aaaa) ? : ") @@ -22,7 +14,6 @@ class View: 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: @@ -32,6 +23,28 @@ class View: else: print("Mauvais format d'ine") + def prompt_for_scores(self): + print() + input("Saisir les scores ?") + return True + + def display_round_info(self, round): + print("Infos du round", round.name, "début le", round.start_time, "fin le", round.end_time, ":\n") + + def display_scores(self, players_list): + print("Les scores sont :\n") + for i in players_list: + print(i.ine, i.name, i.lastname, " : ", i.score) + + def prompt_for_new_player(self): + print("Enregistrez un nouveau joueur :\n") + self.lastname = input("Nom de famille ? : ") + 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() + return {"Nom": self.lastname, "Prénom": self.name, "Date de naissance": self.birthdate, "INE": self.ine} def input_scores(self, match_list): for match in match_list: @@ -54,4 +67,16 @@ class View: except ValueError: print("Veuillez entrer un chiffre") + def display_winner(self, player_list): + winner = max(player_list, key=lambda t: t.score) + print("Le gagnant est :", winner.name, winner.lastname, "avec un score de :", winner.score) + + + + + + + + + -- 2.39.5 From 6df0cf99fea39068b5ef96188fad32bbd124449b Mon Sep 17 00:00:00 2001 From: yann Date: Thu, 6 Feb 2025 10:23:57 +0100 Subject: [PATCH 07/10] add some explanation on sequence and tests --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 19985a1..d2b6605 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,8 @@ 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 + +To test, execute the controllers/base.py +- first menu is called from view +- the method to create player just returns the object (doesn't write anything) +- 1 -> creates a new tournament then run it -- 2.39.5 From a0cb9b0e1214c8f399b013fc1b40316ec0b6f333 Mon Sep 17 00:00:00 2001 From: yann Date: Thu, 6 Feb 2025 10:26:48 +0100 Subject: [PATCH 08/10] delete unused old models --- models/match.py | 27 ---------------- models/participant.py | 46 --------------------------- models/player.py | 30 ------------------ models/tournament.py | 28 ---------------- models/turn.py | 74 ------------------------------------------- 5 files changed, 205 deletions(-) delete mode 100644 models/match.py delete mode 100644 models/participant.py delete mode 100644 models/player.py delete mode 100644 models/tournament.py delete mode 100644 models/turn.py diff --git a/models/match.py b/models/match.py deleted file mode 100644 index 81b6456..0000000 --- a/models/match.py +++ /dev/null @@ -1,27 +0,0 @@ -from 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 diff --git a/models/participant.py b/models/participant.py deleted file mode 100644 index 9e6f718..0000000 --- a/models/participant.py +++ /dev/null @@ -1,46 +0,0 @@ -from collections import UserDict -import json -from player import Player - - -class Participants(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): #player_list FOR TEST ; to feed when creating object - #self.tournament - self.player_list = player_list - self.data = {} - self.PLAYERS_FILE = "./data/players/player_list.json" #FOR TEST - - 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 - diff --git a/models/player.py b/models/player.py deleted file mode 100644 index 8fe54e6..0000000 --- a/models/player.py +++ /dev/null @@ -1,30 +0,0 @@ -import json -from datetime import datetime - -class Player: - """A chess player""" - def __init__(self, name, lastname, birthdate, ine=None, score = 0): - self.name = name - self.lastname = lastname - self.birthdate = birthdate - self.ine = ine - self.score = score - - def __str__(self): - """Used in print""" - return self.ine - - def __repr__(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) \ No newline at end of file diff --git a/models/tournament.py b/models/tournament.py deleted file mode 100644 index a60071c..0000000 --- a/models/tournament.py +++ /dev/null @@ -1,28 +0,0 @@ -from ChessTournament.models.participant import Participants -from ChessTournament.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 = [] - - diff --git a/models/turn.py b/models/turn.py deleted file mode 100644 index f2d0902..0000000 --- a/models/turn.py +++ /dev/null @@ -1,74 +0,0 @@ -from random import choice, shuffle -from datetime import datetime -from time import sleep -from participant import Participants -from match import Match - -class Turn: - """Round for tournament - - has name, dict of participant (object) - """ - def __init__(self, participants = None, name="Round 1"): - self.name = name - self.participants = participants - self.match_history = [] - self.match_list = [] - self.match_result = [] - self.player_list = [] - - def turn_time(self): - return(datetime.now()) - - def sort_players_by_score(self): - """orders dict on value and returns sorted list""" - return sorted(self.participants.items(), key=lambda t: t[1]) - - - - def create_match(self): - j = 0 - k = 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) - while match in self.match_history: - k += 1# If match has already been made, choose the next player - match = Match(self.player_list[i][0], self.player_list[i+k][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 - - - - -tour = Turn() - -tour.turn_time() -sleep(3) -tour.turn_time() -- 2.39.5 From 0500dbeb7a2b5ae6ab8fcc6a4ff387a884a6a449 Mon Sep 17 00:00:00 2001 From: yann Date: Thu, 6 Feb 2025 11:25:56 +0100 Subject: [PATCH 09/10] improve round display with dunder --- models/models.py | 22 ++++++---------------- views/base.py | 2 +- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/models/models.py b/models/models.py index e757134..13d0e93 100644 --- a/models/models.py +++ b/models/models.py @@ -1,4 +1,5 @@ from datetime import datetime +from time import sleep class Tournament: """Chess tournament with player_list, keeps a list with all rounds""" @@ -35,8 +36,6 @@ 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 @@ -45,29 +44,20 @@ class Match: 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 + self.match_list = [] + def __str__(self): + return self.name + ": début le " + self.start_time + " et terminé le " + self.end_time def get_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") + return datetime.now().strftime("%d-%m-%Y à %Hh%M,%Ss") diff --git a/views/base.py b/views/base.py index 728a59b..1c30f83 100644 --- a/views/base.py +++ b/views/base.py @@ -29,7 +29,7 @@ class View: return True def display_round_info(self, round): - print("Infos du round", round.name, "début le", round.start_time, "fin le", round.end_time, ":\n") + print(round) def display_scores(self, players_list): print("Les scores sont :\n") -- 2.39.5 From a0f7004c7ff60c5d50d32186a654dbcf55aa807e Mon Sep 17 00:00:00 2001 From: yann Date: Thu, 13 Feb 2025 11:26:15 +0100 Subject: [PATCH 10/10] reorganized everything, put launcher in main --- controllers/base.py | 299 +++++++++++++++++++++++++++++++++----------- main.py | 24 ++-- models/__init__.py | 0 models/models.py | 122 +++++++++++++++--- player_list.json | 1 - views/__init__.py | 0 views/base.py | 136 ++++++++++++++------ views/menu.py | 10 +- 8 files changed, 445 insertions(+), 147 deletions(-) create mode 100644 models/__init__.py delete mode 100644 player_list.json create mode 100644 views/__init__.py diff --git a/controllers/base.py b/controllers/base.py index cd8badc..58be14b 100644 --- a/controllers/base.py +++ b/controllers/base.py @@ -1,122 +1,269 @@ -from ChessTournament.models.models import Player, Tournament, Round, Match +from ChessTournament.models.models import (Player, Tournament, Round, Match, + MatchHistory) +from ChessTournament.models.models import DATAPATH, PLAYERFILE, TOURNAMENTFILE from ChessTournament.views.menu import Menu from ChessTournament.views.base import View from random import shuffle +import os +import json -class Controller: +class Save: def __init__(self): - # loading models - self.players_list = [] - self.score_list = [] + pass + + def load_file(self, file): + try: + os.mkdir(DATAPATH) + except FileExistsError: + pass + # test if file exists... could be done more gracefully + try: + with open(file, "r") as json_file: + data_tmp = json.load(json_file) + return data_tmp + + except json.decoder.JSONDecodeError: + print("Erreur de format sur le fichier") + except FileNotFoundError: + return False + + def write_file(self, data_tmp, file): + with open(file, "w") as json_file: + json_file.write(json.dumps(data_tmp)) + return "Done." + + + def player_write(self, player) -> bool: + data_tmp = [] + if self.load_file(PLAYERFILE): + data_tmp = (self.load_file(PLAYERFILE)) + data_tmp.append(player) + self.write_file(data_tmp, PLAYERFILE) + print("Joueur créé !") + return True + + def player_load(self) -> list: + """Load and create player from JSON file + returns: + list of Player""" + if self.load_file(PLAYERFILE): + data_tmp = self.load_file(PLAYERFILE) + data_list = [] + for player in data_tmp: + data_list.append(Player(name=player['name'], + lastname=player['lastname'], + birthdate=player['birthdate'], + ine=player['ine'])) + + return data_list + else: + print("\n**** Pas de fichier joueur trouvé :/\n") + + def tournament_write(self, tournament): + data = { + tournament.name: tournament.data() + } + print(data) + + if self.load_file(TOURNAMENTFILE): + data_tmp = self.load_file(TOURNAMENTFILE) + data_tmp[tournament.name] = tournament.data() + self.write_file(data_tmp, TOURNAMENTFILE) + else: + self.write_file(data, TOURNAMENTFILE) + return True + + def tournament_load(self): + if self.load_file(TOURNAMENTFILE): + data_tmp = self.load_file(TOURNAMENTFILE) + return data_tmp + else: + print("\n**** Pas de fichier tournoi trouvé :/ \n") + + +class Application: + def __init__(self, tournament, save, view, menu): + self.tournament = tournament + self.save = save self.match = Match() - self.tournament = Tournament() - - # loading views - self.view = View() - 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] + self.match_history = MatchHistory() + self.view = view + self.menu = menu def sort_by_score(self): - self.tournament.players_list.sort(key=lambda t: t.score, reverse = True) + self.tournament.players_list.sort(key=lambda t: t.score, reverse=True) 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) - + tournament_details = self.view.prompt_for_tournament() + self.tournament.name = tournament_details['name'] + self.tournament.location = tournament_details['location'] + self.tournament.date_start = tournament_details['date_start'] + self.tournament.date_end = tournament_details['date_end'] + self.tournament.description = tournament_details['description'] + self.tournament.total_round = tournament_details['total_round'] + if self.save.player_load(): + self.tournament.players_list = self.save.player_load() + self.save.tournament_write(self.tournament) + else: + print("Placez un fichier joueur dans le répertoire data" + "ou créez des nouveaux joueurs depuis le menu") + print() + self.menu_manager() def run_tournament(self): - input("Prêt à lancer le premier round ?\n") - #print("tour", self.tournament.current_round, round1.start_time) - print("Liste des joueurs : ", self.tournament.players_list) shuffle(self.tournament.players_list) - - for i in range(1, self.tournament.total_round): + for each_round in range(1, self.tournament.total_round + 1): + self.tournament.current_round += 1 self.round = Round() - self.round.name = "Round " + str(i) - self.tournament.current_round = self.round.name - #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 - + self.round.name = "Round " + str(each_round) + self.view.prompt_for_round(self.round) + # set round start time self.round.start_time = self.round.get_time() + # create matches TODO : check from history self.round.match_list = self.create_match() + # display matches + self.view.display_matches(self.round.match_list) self.view.prompt_for_scores() self.round.end_time = self.round.get_time() - self.view.input_scores(self.round.match_list) + self.scores(self.round.match_list) self.sort_by_score() + self.tournament.round_list.append(self.round.save()) + print("après maj", self.tournament.round_list) + self.save.tournament_write(self.tournament) self.view.display_round_info(self.round) self.view.display_scores(self.tournament.players_list) - print("Le tournoi", self.tournament.name, "est terminé !") + print("\nLe tournoi", self.tournament.name, "est terminé !\n") + def get_match_info(self, match_list): + matches = [] + for i in match_list: + matches.append(i.get_data()) + return matches + def check_match(self, match, match_history): + for item in match_history: + if match in item: + return True + else: + return False + def create_match(self) -> list: + """Create match with two consecutive players - - - def create_match(self): - """Create match with two consecutive players. Check if match already happened in round - - returns a round.match_list + returns : + list of Match """ + match_list = [] j = 0 - k = 0 - print(self.tournament.players_list) for i in range(0, len(self.tournament.players_list), 2): j += 1 - match_name = "match" + str(j) match = Match() match.player1 = self.tournament.players_list[i] match.player2 = self.tournament.players_list[i+1] - self.round.match_list.append(match) + match_list.append(match) + return match_list - return self.round.match_list + def scores(self, match_list) -> list: + """user asked to enter scores, update Player + returns: + list of tuples + """ + matches = [] + for match in match_list: + count = match_list.index(match) + 1 + result = self.view.input_scores(match, count) + if result in ("1", "2", "3"): + if result == "1": + match.player1.score += 1 + match.score1 = 1 + elif result == "2": + match.player2.score += 1 + match.score2 = 1 + elif result == "3": + match.player1.score += 0.5 + match.player2.score += 0.5 + match.score1 = match.score2 = 0.5 + matches.append(match.get_data()) + return matches - - def run(self): + def menu_manager(self): menu_choice = self.menu.items(1) - if menu_choice == "4": - print("Bye") - elif menu_choice == "3": - self.menu.items(2) - elif menu_choice == "2": - self.view.prompt_for_new_player() - elif menu_choice == "1": - print("c'est parti") - self.create_tournament() - self.run_tournament() - self.view.display_winner(self.tournament.players_list) - self.view.display_scores(self.tournament.players_list) + while True: + # Quit + if menu_choice == "4": + print("Bye") + + # Rapports + elif menu_choice == "3": + rapport_choice = self.menu.items(2) + + # Go back + if rapport_choice == "4": + self.menu_manager() + + # Display players from file + elif rapport_choice == "1": + if self.save.player_load(): + self.view.display_players(self.save.player_load()) + input("?") + + # Display list of tournaments + elif rapport_choice == "2": + if self.save.tournament_load(): + self.view.display_tournaments(self.save.tournament_load()) + input("?") + + # display tournament's details + elif rapport_choice == "3": + temp = {} + if self.save.tournament_load(): + temp = self.save.tournament_load() + name = self.view.prompt_tournament_to_display(temp) + if name in temp: + self.view.display_tournament_detail( + temp[name]) + else: + self.view.display_error() + + # create new player and save it in file + elif menu_choice == "2": + joueur = self.view.prompt_for_new_player() + self.save.player_write(joueur) + input("Retour ?") + self.menu_manager() + + # create new tournament + elif menu_choice == "1": + print("c'est parti") + self.create_tournament() + self.run_tournament() + self.view.display_winner(self.tournament.players_list) + self.view.display_scores(self.tournament.players_list) + self.menu_manager() -run = Controller() -run.run() +class CheckMatch: + pass + + +class MenuManager: + pass + + +class TournamentManager: + def __init__(self): + pass + + +class UserManager: + pass + diff --git a/main.py b/main.py index 4a86937..e64c8c5 100644 --- a/main.py +++ b/main.py @@ -1,17 +1,21 @@ -from controllers.base import Controller -from views.base import View +from ChessTournament.models.models import Tournament +from ChessTournament.controllers.base import Application, Save +from ChessTournament.views.base import View +from ChessTournament.views.menu import Menu def main(): + tournament = Tournament() + save = Save() view = View() - menu = Controller(view) - menu.run() + menu = Menu() + application = Application(tournament=tournament, + save=save, + view=view, + menu=menu) + # launch application + application.menu_manager() -if __name__ == "__main__" : +if __name__ == "__main__": main() - - - - - diff --git a/models/__init__.py b/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/models/models.py b/models/models.py index 13d0e93..c6f93dc 100644 --- a/models/models.py +++ b/models/models.py @@ -1,26 +1,57 @@ from datetime import datetime -from time import sleep +from collections import UserList + +DATAPATH = ("data/") +PLAYERFILE = DATAPATH + "liste_joueurs.json" +TOURNAMENTFILE = DATAPATH + "liste_tournois.json" + 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): + 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.start = datetime.now().strftime("%d-%m-%Y") + self.end = self.start self.total_round = total_round self.round_list = [] - self.current_round = 1 + self.current_round = 0 self.players_list = players_list self.description = "Pas de description" + def __str__(self): + return "Tournoi " + self.name + " à " + self.location + + def data(self): + """Save tournament in file""" + players = [] + for i in self.players_list: + # players.append(i.name + " " + i.lastname) + players.append(i.data()) + tournament_dict = { + "name": self.name, + "location": self.location, + "description": self.location, + "start": self.start, + "end": self.end, + "total_rounds": self.total_round, + "current": self.current_round, + "players": players, + "rounds": self.round_list} + return tournament_dict + class Player: """A Chess player""" - def __init__(self, name, lastname, birth_date, ine): + def __init__(self, name, lastname, birthdate, ine): self.lastname = lastname self.name = name - self.birth_date = birth_date + self.birthdate = birthdate self.ine = ine self.score = 0 @@ -31,33 +62,88 @@ class Player: def __repr__(self): return str(self) + def data(self): + player_dict = { + 'prénom': self.name, + 'nom': self.lastname, + 'date de naissance': self.birthdate, + 'ine': self.ine + } + return player_dict + class Match: - def __init__(self, player1 = None, player2 = None): + 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 - return self.player1.ine + "/" + self.player2.ine - - def __repr__(self): - return str(self) + return self.player1.ine + " / " + self.player2.ine def get_data(self): - return ([self.player1.ine, self.player1.score], [self.player2.ine, self.player2.score]) + return ([self.player1.ine, self.score1], + [self.player2.ine, self.score2]) + + def get_scores(self) -> list: + return (self.player1.ine + + " : " + str(self.score1) + + " - " + self.player2.ine + + " : " + str(self.score2)) class Round: - def __init__(self, name = "Round 1"): + def __init__(self, name="Round 1"): self.name = name self.start_time = None self.end_time = None self.match_list = [] - def __str__(self): - return self.name + ": début le " + self.start_time + " et terminé le " + self.end_time - def get_time(self): + def __str__(self): + return (self.name + + ": début le " + + self.start_time + + " et terminé le " + + self.end_time) + + def get_time(self) -> str: return datetime.now().strftime("%d-%m-%Y à %Hh%M,%Ss") + def save(self) -> dict: + matches = [] + for match in self.match_list: + matches.append(match.get_data()) + dico = { + "Nom": self.name, + "Debut": self.start_time, + "Fin": self.end_time, + "Matches": matches + } + return dico + + +class MatchHistory(UserList): + """Keep a history of matches to avoid same match occur + + returns a list of matches + """ + def __init__(self): + self.matches = [] + + def add(self, match_list): + for match in match_list: + self.matches.append(match) + + def __str__(self): + return self.matches + + def check(self, given_match): + for match in self.matches: + if (given_match.player1 == match.player1 + or given_match.player1 == match.player2): + if (given_match.player2 == match.player2 + or given_match.player2 == match.player2): + return True + return False diff --git a/player_list.json b/player_list.json deleted file mode 100644 index 0eea98e..0000000 --- a/player_list.json +++ /dev/null @@ -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"]} \ No newline at end of file diff --git a/views/__init__.py b/views/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/views/base.py b/views/base.py index 1c30f83..70fb14f 100644 --- a/views/base.py +++ b/views/base.py @@ -1,6 +1,7 @@ from datetime import datetime import re + class View: """Prompt menu, get choices""" def __init__(self): @@ -25,58 +26,117 @@ class View: def prompt_for_scores(self): print() - input("Saisir les scores ?") + input("Saisir les scores ? (y)") return True + def prompt_for_round(self, round): + print() + input(f"Prêt à lancer le {round.name} ? (y)") + return True + + def display_matches(self, match_list): + print("Liste des matchs : ") + for match in match_list: + print(match.player1.name, match.player1.lastname.upper(), + "contre", match.player2.name, match.player2.lastname.upper(), + "(", match, ")" + ) + def display_round_info(self, round): - print(round) + print("\n -> ", round) def display_scores(self, players_list): - print("Les scores sont :\n") + print("\nLes scores sont :") + print("-----------------") for i in players_list: - print(i.ine, i.name, i.lastname, " : ", i.score) + print(i.ine, i.name, i.lastname, ":", i.score) - def prompt_for_new_player(self): + def prompt_for_new_player(self) -> dict: print("Enregistrez un nouveau joueur :\n") - self.lastname = input("Nom de famille ? : ") - 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() - return {"Nom": self.lastname, "Prénom": self.name, "Date de naissance": self.birthdate, "INE": self.ine} + lastname = input("Nom de famille ? : ") + name = input("Prénom ? : ") + birthdate = input("Date de naissance (jj/mm/aaaa) ? : ") + ine = input("Identifiant National d'Echecs (ine) ? : ") + return {'name': name, + 'lastname': lastname, + 'birthdate': birthdate, + 'ine': ine} - def input_scores(self, match_list): - for match in match_list: - print(match) - print("Scores pour match", match_list.index(match) + 1, " :") - while True: - try: - result = input(f"1.{match.player1}, 2.{match.player2}, 3.Nul\n") - if result in ("1", "2", "3"): - if result == "1": - match.player1.score += 1 - elif result == "2": - match.player2.score += 1 - elif result == "3": - match.player1.score += 0.5 - match.player2.score += 0.5 - break - else: - print("Entrez un chiffre entre 1 et 3") - except ValueError: - print("Veuillez entrer un chiffre") + def prompt_for_tournament(self) -> dict: + tournament_details = {} + tournament_details['name'] = str.lower(input("Nom du tournoi ? : ")) + tournament_details['location'] = str.lower(input("Lieu du tournoi : ")) + tournament_details['date_start'] = ( + input("date de début (jj/mm/aaaa) : [today] " + or datetime.now().strftime("%d/%m/%Y"))) + tournament_details['date_end'] = ( + input("date de fin (jj/mm/aaaa) : [today] " + or datetime.now().strftime("%d/%m/%Y"))) + tournament_details['description'] = input("Description ? : ") + total_round = input("Nombre de tours ? (4 par défaut) : ") or 4 + tournament_details['total_round'] = int(total_round) + return tournament_details + + def input_scores(self, match, count): + print("Scores pour le match", count, " :") + while True: + try: + result = input(f"1.{match.player1}, " + f"2.{match.player2}, " + f"3.Nul\n") + if result in ("1", "2", "3"): + return result + else: + print("Entrez un chiffre entre 1 et 3") + except ValueError: + print("Veuillez entrer un chiffre") def display_winner(self, player_list): winner = max(player_list, key=lambda t: t.score) - print("Le gagnant est :", winner.name, winner.lastname, "avec un score de :", winner.score) - - - - - + print("Le gagnant est :", + winner.name, + winner.lastname, + "avec un score de :", + winner.score) + def display_players(self, player_list_to_display): + print("Liste des joueurs :") + for player in player_list_to_display: + print(player.data()) + def display_tournaments(self, tournament_list_to_display): + print("Liste des tournois : ") + for tournament in tournament_list_to_display: + print("-", tournament, + "le", + tournament_list_to_display[tournament]['start']) + def prompt_tournament_to_display(self, tournament_list_to_display): + i = 0 + temp_list = [] + for tournament in tournament_list_to_display: + i += 1 + print(i, ".", tournament) + temp_list.append(tournament) + num = int(input("Numéro du tournoi à afficher ? ")) + return temp_list[num - 1] + def display_tournament_detail(self, tournament_to_display): + i = tournament_to_display + print("Nom du tournoi : ", i['name']) + print("Lieu : ", i['location']) + print("Le tournoi a débuté le : ", i['start']) + print("Et s'est terminé le : ", i['end']) + print("Les participants étaient : \n", i['players']) + print("\nLes matches et leurs résultats étaient :") + for j in i['rounds']: + print(j['Nom']) + print("Commencé à ", j['Debut']) + print("Terminé à ", j['Fin']) + print("Liste des matchs :") + for k in j['Matches']: + print(k) + print() + def display_error(self): + print("Erreur de saisie, recommencez;") diff --git a/views/menu.py b/views/menu.py index 478fade..378685e 100644 --- a/views/menu.py +++ b/views/menu.py @@ -11,7 +11,7 @@ class Menu: "[1] Afficher la liste des joueurs", "[2] Afficher l'historique des tournois", "[3] Afficher le détail d'un tournoi", - "[4] Quitter" + "[4] Retour" ] def items(self, value): @@ -19,18 +19,20 @@ class Menu: menu_type = [] if value == 1: menu_type = self.ITEMS + print() + print("MENU GENERAL") if value == 2: menu_type = self.RAPPORTS + print() + print("MENU RAPPORTS") for i in menu_type: print(i) while True: try: choice = input("Choix ? : ") if int(choice) not in range(1, len(menu_type) + 1): - print("Veuillez saisir un chiffre entre 1 et", len(menu_type)) - print(int(choice) in range(1, len(menu_type))) + print("Choisissez un chiffre entre 1 et", len(menu_type)) else: return choice except ValueError: print("Veuillez entrer un chiffre") - -- 2.39.5