def automatique(idul): """Section automatique""" identifiant, etat = débuter_partie(idul) partie = Quoridor(etat["joueurs"], etat['murs']) print(partie) while not partie.partie_terminée(): before = copy.deepcopy(partie.état_partie()) partie.jouer_coup(1) after = copy.deepcopy(partie.état_partie()) print(partie) if before["joueurs"][0]["pos"] != after["joueurs"][0]["pos"]: etat = jouer_coup(identifiant, "D", after["joueurs"][0]["pos"]) elif len(after["murs"]["horizontaux"]) != len( before["murs"]["horizontaux"]): etat = jouer_coup( identifiant, "MH", after["murs"]["horizontaux"][len(after["murs"]["horizontaux"]) - 1]) elif len(after["murs"]["verticaux"]) != len( before["murs"]["verticaux"]): etat = jouer_coup( identifiant, "MV", after["murs"]["verticaux"][len(after["murs"]["verticaux"]) - 1]) partie = Quoridor(etat["joueurs"], etat['murs'])
def auto_graph(idul): """ Fonction qui permet de jouer en mode automatique contre le serveur avec une affichage graphique. """ partie = api.débuter_partie(ARGUMENTS.idul.lower()) idp = partie[0] jeu = qrx.QuoridorX([idul, "automate"]) jeu.état = partie[1] jeu.afficher() while True: try: jeu.jouer_coup(1) jeu.afficher() jeu.état = api.jouer_coup(idp, jeu.type_coup, jeu.pos_coup) jeu.posj2 = (jeu.état['joueurs'][1]['pos'][0], jeu.état['joueurs'][1]['pos'][1]) jeu.posj2 = (jeu.état['joueurs'][1]['pos'][0], jeu.état['joueurs'][1]['pos'][1]) for i in jeu.état['murs']["horizontaux"]: jeu.murs['horizontaux'].append(i) jeu.murs['horizontaux'].append(i) for i in jeu.état['murs']["verticaux"]: jeu.murs['verticaux'].append(i) jeu.murs['verticaux'].append(i) jeu.afficher() except StopIteration as err: print(f"La partie est terminée, {err} est vainqueur!") break
def main(): """Fonction principale du jeu quoridor""" parsed_args = analyser_commande() game_idul = initialiser_partie(parsed_args.idul) game_state = game_idul['état'] lister_parties(parsed_args.idul) game_completed = False while not game_completed: afficher_damier_ascii(game_state) print( 'Types de coups disponibles: \n' ' - D: Deplacement \n - MH: Mur Horizontal \n - MV: Mur Vertical \n\n' ) type_coup = input('Choisissez votre type de coup (D, MH ou MV)') print('Vous avez effectué le coup ' + type_coup) ligne = input("Definissez la ligne de votre coup") print('Vous avez entré la ligne ' + ligne) colonne = input('Definissez la colonne de votre coup') print('Vous avez entré la colonne ' + colonne) position = [colonne, ligne] id_partie = game_idul['id'] game_state = jouer_coup(id_partie, type_coup, position)
def game(): """Jouer en console""" analyser = analyser_commande() partie_id = initialiser_partie(analyser.idul) print('\n') if analyser.lister: print(lister_parties(analyser.idul), '\n') print(afficher_damier_ascii(partie_id[1])) while 1: try: position = list( map( int, input('Entrez les coordonnees du coup x, y: ').strip(). split(','))) mouvement = input('Entrez le type de coup MH, MV ou D: ') except ValueError: print('La valeur entree est incorrect') position = list( map( int, input('Entrez les coordonnees du coup x, y: ').strip(). split(','))) mouvement = input('Entrez le type de coup MH, MV ou D: ') else: print( afficher_damier_ascii( jouer_coup(partie_id[0], mouvement, position)))
def on_draw(): nom_des_joueurs = pyglet.text.Label( 'Blanc : {} Noir : {}'.format( self.grille['joueurs'][0]['nom'], self.grille['joueurs'][1]['nom']), x=self.window.width / 2, y=self.window.height - 5, anchor_x='center', anchor_y='top') murs_a_placer = pyglet.text.Label( 'Murs : {} Murs : {}'.format( self.grille['joueurs'][0]['murs'], self.grille['joueurs'][1]['murs']), x=self.window.width / 2, y=self.window.height - 25, anchor_x='center', anchor_y='top') self.window.clear() nom_des_joueurs.draw() murs_a_placer.draw() draw_quadrillé() placeJoueurs(self.grille) placeMursHorizontaux(self.grille) placeMursVerticaux(self.grille) COUP = self.jouer_coup(1) self.grille = api.jouer_coup(self.id, COUP[0], COUP[1])
def newstart(newcommand): try: with open('id.txt', 'r') as file: id = file.read() newboard = api.jouer_coup(id, newcommand.lister[0], (newcommand.lister[1], newcommand.lister[2])) afficher_damier_ascii(newboard['état']) except Exception as e: print(str(e)) againinput()
def mode_automatique_graphique(idul): """mode atomatique graphique""" [identifiant, état] = initialiser_partie(idul) joueur = [état['joueurs'][0]['nom'], état['joueurs'][1]['nom']] jeu = QuoridorX(joueur) while 1: (coup, pos) = jeu.jouer_coup(1) jeu.afficher() état = jouer_coup(identifiant, coup, tuple(pos)) joueur1 = état['joueurs'] murs_j1 = état['murs'] jeu = QuoridorX(joueur1, murs_j1)
def mode_manuel(idul): """mode manuel""" etat_jeu = initialiser_partie(idul) print(afficher_damier_ascii(etat_jeu[1])) print('Quel coup désirer vous jouer ?') print("Deplacement pion: D , Mur Horizontal : MH, Mur Vertical : MV ") coup = input() print('Quel position sur le plateau désirer vous placer votre pièce?') print('(x,y)') position = input() etat_jeu_2 = jouer_coup(etat_jeu[0], coup, position) print(afficher_damier_ascii(etat_jeu_2)) while 1: print('Quel coup désirer vous jouer ?') print("Deplacement pion: D , Mur Horizontal : MH, Mur Vertical : MV ") coup = input() print('Quel position sur le plateau désirer vous placer votre pièce?') print('(x,y)') position = input() etat_jeu_2 = jouer_coup(etat_jeu[0], coup, position) print(afficher_damier_ascii(etat_jeu_2))
def jouer_coup(args, q, id_partie): """Boucle de saisie.""" if args.mode_auto: return api.jouer_coup(id_partie, q.type_coup.upper(), q.pos_coup) capture = None titre = "C'est votre tour!" question = "Entrez votre prochain coup sous la forme (D|MH|MV) x y :" while not capture: if args.mode_graphique: entree = turtle.textinput(titre, question) if entree is None: # bouton Cancel ou X turtle.mainloop() # pause sur damier raise RuntimeError("Fenêtre fermée par le joueur") else: print(question, end=" ") entree = input() capture = re.search(r'^(D|MH|MV)\s+(\d)\s+(\d)$', entree.strip(), re.IGNORECASE) if capture: entrees = capture.groups() try: return api.jouer_coup(id_partie, entrees[0].upper(), (int(entrees[1]), int(entrees[2]))) # except StopIteration as gagnant: # gagnant = str(gagnant) except RuntimeError as message: titre = str(message) capture = None if not args.mode_graphique: print(titre) else: titre = "Erreur de syntaxe, veuillez réessayer." if not args.mode_graphique: print(titre)
def mode_manuel_graphique(idul): """mode manuel graphique""" [identifiant, état] = initialiser_partie(idul) joueur = état['joueurs'] murs = état['murs'] QuoridorX(joueur, murs) print('Quel coup désirer vous jouer ?') print("Deplacement pion: D , Mur Horizontal : MH, Mur Vertical : MV ") coup = input() print('Quel position sur le plateau désirer vous placer votre pièce?') print('(x,y)') position = input() état_2 = jouer_coup(identifiant, coup, position) while 1: joueur = état_2['joueurs'] murs = état_2['murs'] QuoridorX(joueur, murs) print('Quel coup désirer vous jouer ?') print("Deplacement pion: D , Mur Horizontal: MH, Mur Vertical: MV ") coup = input().upper() print('Quel position sur le plateau désirer vous placer votre pièce?') print('(x,y)') position = input() état_2 = jouer_coup(identifiant, coup, position)
def mode_automatique(idul): """mode automatique""" [identifiant, état] = initialiser_partie(idul) print(afficher_damier_ascii(état)) joueur = [état['joueurs'][0]['nom'], état['joueurs'][1]['nom']] jeu = Quoridor(joueur) état = jeu.état_partie() while 1: (coup, pos) = jeu.jouer_coup(1) print(jeu) état = jouer_coup(identifiant, coup, tuple(pos)) afficher_damier_ascii(état) joueur1 = état['joueurs'] murs_j1 = état['murs'] jeu = Quoridor(joueur1, murs_j1)
def jouer_coup(args, q, id_partie): """Boucle de saisie.""" if args.mode_auto: return api.jouer_coup(id_partie, q.type_coup.upper(), q.pos_coup) capture = None titre = "C'est votre tour!" question = "Entrez votre prochain coup sous la forme (D|MH|MV) x y :" while not capture: if args.mode_graphique: entree = turtle.textinput(titre, question) if entree is None: turtle.mainloop() raise RuntimeError("Fenêtre fermée par le joueur") else: print(question, end=" ") entree = input()
def jouer_coup(a, q, partie): """ Main Frame """ #Mode automatic: if a.mode_auto: #on retourne un coup jouer de api.py return api.jouer_coup(id, q.type_coup.upper(), q.position) #initalise some variables cap = None title = "C'est à votre tour!" question = "Entrez votre prochain coup (D|MH|MV) (x, y):" #loop to determine how graphic mode functions while not cap: #as long as mode graphic is selected, we ask both questions if a.mode_graphique: #if nothing happens: if entry is None: #we pause the game turtle.mainloop() #raise an error to indicated a problem concerning window raise RuntimeError('Le joueur a fermer la fenêtre') #if something is entered else: print(question, end='') #the entry is manually entered entry = input() #we use the re module to separate the values #we use ^ to match the pattern at the start of the string #we use $ to match the end of the string #we use \s to match a single whitespace character like #we use \d to match decimal digit 0-9 #we add them because (position, x, y) #we use IGNORECASE to match lower case values cap = re.search(r'(D|MH|MV)\s + (\d)\s + (\d)$', entry.split(), re.IGNORECASE) #if we enter something if cap: entry = cap.groups()
def jouer(): ''' Fonction permettant de jouer au jeu. ''' idul = analyser_commande().idul etat = débuter_partie(idul)[1] identif = débuter_partie(idul)[0] while True: afficher_damier_ascii(etat) try: type_coup = input('Voulez-vous jouer un mur ou un déplacement ? (entrez D, MH ou MV) ') position_x = input('Choisissez une case en x :') position_y = input('Choisissez une case en y :') etat = jouer_coup(identif, type_coup, (position_x, position_y)) except RuntimeError as err: print(err) print('Veuillez reprendre votre coup') except StopIteration as name: print(f'Partie terminée, {name} a gagné !') break
def main(): command = analyser_commande() debut = api.lister_parties(command.idul) pp.pprint(debut) afficher_damier_ascii(debut['parties'][0]['état']) for i in debut['parties']: if i['id'] == id: afficher_damier_ascii(i['état']) while True: print("Type de coup ['D', 'MH', 'MV']: ") type_coup = input() print("Position x: ") position_x = int(input()) print("Position y: ") position_y = int(input()) position = (position_x, position_y) pp.pprint(api.jouer_coup(id, type_coup, position)) etat = api.lister_parties(command.idul) for i in etat['parties']: if i['id'] == id: afficher_damier_ascii(i['état'])
def jouer(): """Jouer directement sur le terminal""" idul = analyser_commande().idul etat = api.débuter_partie(idul)[1] identif = api.débuter_partie(idul)[0] while True: try: afficher_damier_ascii(etat) type_coup = input('Quel est votre coup (D, MH ou MV) ?') position_x = input('Veuillez choisir une case en x :') position_y = input('Veuillez choisir une case en y :') etat = api.jouer_coup(identif, type_coup, (position_x, position_y)) except RuntimeError as err: print(err) print('Veuillez reprendre votre coup') except StopIteration as err: print(f'{err} a gagné !') break
def jeu_console_serveur(idul, automode=False): """mode de jeu permettant de jouer en mode manuel contre le serveur - Les commandes sont entrées via le terminal - L'affichage s'effectue via le terminal en art ascii Arguments: idul {str} -- L'identifiant du joueur """ # débuter le jeu nouveaujeu = api.débuter_partie(idul) jeu = quoridor.Quoridor(nouveaujeu[1]['joueurs']) jeu.gameid = nouveaujeu[0] # afficher le jeu print(jeu) # boucler while True: # jouer manuellement ou demander au AI de le coup a joue if automode: coup = autocommande(jeu) else: coup = prompt_player() # jouer le coup try: if not verifier_validite(jeu, coup): print("coup invalide!") print(jeu) continue nouveaujeu = api.jouer_coup(jeu.gameid, coup[0], (coup[1], coup[2])) jeu.joueurs = nouveaujeu['joueurs'] jeu.murh = nouveaujeu['murs']['horizontaux'] jeu.murv = nouveaujeu['murs']['verticaux'] print(jeu) except StopIteration as s: # prévenir le joueur que la partie est terminée print('\n' + '~' * 39) print("LA PARTIE EST TERMINÉE!") print("LE JOUEUR {} À GAGNÉ!".format(s)) print('~' * 39 + '\n') return
def jeu_graphique_serveur(idul, automode=False): """jeu manuel affiché dans un interface graphique - Les coups sont entrés dans l'interface graphique - L'affichage se fait dans l'interface graphique Arguments: idul {str} -- L'identifiant du joueur """ # débuter le jeu nouveaujeu = api.débuter_partie(idul) jeu = quoridorx.QuoridorX(nouveaujeu[1]['joueurs']) jeu.gameid = nouveaujeu[0] coup = [] # boucler while True: # Obtenir le coup t = check_task(jeu, coup, automode) if t: try: coup = t # vérifier si le coup est valide if not verifier_validite(jeu, coup): mb.showerror("Erreur!", "Coup invalide!") continue jeu.afficher() nouveaujeu = api.jouer_coup(jeu.gameid, coup[0], (coup[1], coup[2])) jeu.joueurs = nouveaujeu['joueurs'] jeu.murh = nouveaujeu['murs']['horizontaux'] jeu.murv = nouveaujeu['murs']['verticaux'] # Afficher le jeu jeu.afficher() except StopIteration as s: # prévenir le joueur que la partie est terminée mb.showinfo("Partie terminée!", f"Le joueur {s} à gagné!") return # Boucler et continuellement afficher jeu.root.update_idletasks() jeu.root.update()
if not (c.a or c.x or c.ax): jeu = Quoridor((c.idul, 'robot')) ID, etat = debuter_partie(c.idul) while True: TYPE_COUP = input('Quel type de coup voulez-vous jouer? (D/MH/MV) ') POSI = input( 'À quelle position (x,y) voulez-vous jouer ce coup ? ').replace( ' ', '') x, y = int(POSI[1]), int(POSI[3]) if TYPE_COUP.lower() == 'd': jeu.déplacer_jeton(1, (x, y)) print(jeu) time.sleep(0.6) reponse = jouer_coup(ID, 'D', (x, y)) elif TYPE_COUP.lower() == 'mh': jeu.placer_mur(1, (x, y), 'horizontal') print(jeu) time.sleep(0.6) reponse = jouer_coup(ID, 'MH', (x, y)) elif TYPE_COUP.lower() == 'mv': jeu.placer_mur(1, (x, y), 'vertical') print(jeu) time.sleep(0.6) reponse = jouer_coup(ID, 'MV', (x, y)) jeu.pos2 = tuple(reponse['joueurs'][1]['pos']) jeu.hori = reponse['murs']['horizontaux'] jeu.ver = reponse['murs']['verticaux'] jeu.partie_terminée()
STR_POS_COUP = input( """Veuillez entrer la position sous la forme "x, y": """) LIST_POS_COUP = STR_POS_COUP.split(sep=",") try: POS_COUP = (int(LIST_POS_COUP[0]), int(LIST_POS_COUP[1])) except Exception: raise AssertionError("Le format entré est invalide") if TYPE_COUP == 'D': assert 1 <= POS_COUP[0] <= 9 and 1 <= POS_COUP[ 1] <= 9, "Indice invalide" else: assert 2 <= POS_COUP[0] <= 9 and 1 <= POS_COUP[ 1] <= 8, "Indice invalide" ETAT = api.jouer_coup(ID_PARTIE, TYPE_COUP, POS_COUP) afficher_damier_ascii(ETAT) except AssertionError as err: print(err) except RuntimeError as err: print(err) except StopIteration as gagnant: print(str(gagnant) + 'a gagné la partie!') EN_JEU = False except KeyboardInterrupt: print("\nPartie annulée par l'utilisateur\n")
if __name__ == "__main__": __args__ = analyser_commande() if __args__.auto and not __args__.graph: automatique(__args__.idul) elif __args__.graph and not __args__.auto: __infojeutupple__ = débuter_partie(__args__.idul) __infojeu1__ = __infojeutupple__[1] partie = QuoridorX(__infojeu1__["joueurs"], __infojeu1__['murs']) partie.afficher() while True: try: __coup_type__ = input("Choisir un coup: 'D', 'MH' ou 'MV'") __position_coup__ = input( "veuillez inscrire la position du coup sous format '(x, y)'" ) __infojeu1__ = jouer_coup(__infojeutupple__[0], __coup_type__, \ __position_coup__) partie = QuoridorX(__infojeu1__["joueurs"], __infojeu1__['murs']) partie.afficher() except RuntimeError as err: print(err) except StopIteration as err: print(err) break elif __args__.graph and __args__.auto: autograph(__args__.idul) else: __infojeutupple__ = débuter_partie(__args__.idul) __infojeu1__ = __infojeutupple__[1] afficher_damier_ascii(__infojeu1__) while True:
if type_coup not in ["D", "MH", "MV"]: return ask_type() return type_coup def ask_coords(): try: return literal_eval(input("coords (x,y) : ")) except ValueError as _: return ask_coords() if __name__ == "__main__": args = analyser_commande() if args.lister is not None: print(api.lister_parties(args.idul)[:20]) id_game, board = api.initialiser_partie(args.idul) while True: try: afficher_damier_ascii(board) type_coup = ask_type() coords = ask_coords() board = api.jouer_coup(id_game, type_coup, coords) except StopIteration as e: print(e) break except RuntimeError as e: print(e)
if __name__ == "__main__": ARGS = analyser_commande() PARTIE = initialiser_partie(ARGS.idul) ID_PARTIE = PARTIE[0] if ARGS.graphique: #objet classe QuoridorX q = QuoridorX(PARTIE[1]['joueurs'], PARTIE[1]['murs']) if ARGS.automatique: #automatique graphique print('automatique et graphique') while True: try: TYPE_COUP, POSITION = q.jouer_coup(1) DAMIER = jouer_coup(ID_PARTIE, TYPE_COUP, POSITION) q.window.clearscreen() q = QuoridorX(DAMIER['joueurs'], DAMIER['murs']) except RuntimeError as err: print(err) CHOIX = input( "Voulez-vous continuer à jouer, oui ou non? ") if CHOIX.lower() == 'non': break except StopIteration as err: q.window.clearscreen() q = QuoridorX(DAMIER['joueurs'], DAMIER['murs']) print(f'Le grand gagnant est le joueur {err} !\n') break else: #manuel graphique
tot[40 * (18 - adding - 2 * place[1]) + 4 * place[0] - 2] = '|' return deb + ''.join(tot) if analyser_commande().lister: print(api.lister_parties(analyser_commande().idul)['parties']) else: IDUL = a.idul v = api.débuter_partie(IDUL) if v.get('message') is not None: print(v['message']) else: q = afficher_damier_ascii(v['état']) print(q) CTE = v['id'] v = 0 while v < 1: b = input('Veuillez choisir un type de coup ! D, MH ou MV : ') c = input('Sélectionnez un point ! (x, y) : ') a = api.jouer_coup(CTE, b, c) if str(a) == a: if str(a) == 'robot' or (a) == str(IDUL): print(a + ' GAGNE !') v += 1 else: print(q) print(a) else: q = afficher_damier_ascii(a['état']) print(q)
PARTIE.automatique = ARGS.automatique PARTIE.id = ID_PARTIE else: PARTIE = quoridor.Quoridor(GRILLE['joueurs'], GRILLE['murs']) WIN = False while not WIN: PARTIE.afficher() if not ARGS.automatique: TYPE_COUP = input( "\nQuel type de coup voulez vous effectuer ?\n'D' pour déplacer le jeton,\ \n'MH' pour placer un mur horizontal,\n'MV' pour placer un mur vertical.\nType: " ) TYPE_COUP = TYPE_COUP.upper() if TYPE_COUP == '': TYPE_COUP = 'D' ISINT = False while not ISINT: try: POS_X = int(input("Coordonnée en 'x'? ")) POS_Y = int(input("Coordonnée en 'y'? ")) ISINT = True except ValueError: print('La valeur entrée est invalide.') POSITION = (POS_X, POS_Y) PARTIE.grille = jouer_coup(ID_PARTIE, TYPE_COUP, POSITION) else: time.sleep(0.35) COUP = PARTIE.jouer_coup(1) PARTIE.grille = jouer_coup(ID_PARTIE, COUP[0], COUP[1]) WIN = PARTIE.partie_terminée()
import quoridor import api #Liaison entre les différents modules if __name__ == "__main__": REP = vars(quoridor.analyser_commande()) idul = REP['idul'] x = api.initialiser_partie(idul) y = x[1] id_partie = x[0] print(id_partie) QUITTER = False while QUITTER != True: quoridor.afficher_damier_ascii(y) type_coup = quoridor.demander_typecoup() if type_coup == 'Q': QUITTER = True print('Au revoir') break position = quoridor.demander_position() y = api.jouer_coup(id_partie, type_coup, position)
IDGAME, STATE = api.débuter_partie(AN.idul) while not GAMEDONE: afficher_damier_ascii(STATE) try: print('\n\n\nChoisissez une option parmi les suivantes:') print('\n1- Déplacer son joueur') print('2- Placer un mur horizontal') print('3- Placer un mur vertical') print('4- Quitter') OK = False while not OK: CHOIX = input() if str(CHOIX) == '1': OK = True POS = getpos() STATE = api.jouer_coup(IDGAME, 'D', POS) elif str(CHOIX) == '2': POS = getpos() STATE = api.jouer_coup(IDGAME, 'MH', POS) OK = True elif str(CHOIX) == '3': POS = getpos() STATE = api.jouer_coup(IDGAME, 'MV', POS) OK = True elif str(CHOIX) == '4': OK = True GAMEDONE = True print('BYE BYE!!') else: print('Le choix rentré est invalide') except RuntimeError as err:
def jouer_manuel_graph(self, idf, typef, pos): self.partie = jouer_coup(idf, typef, str(pos))
def jouer_auto_graph(self, idf): """fonction""" typef, pos = self.jouer_coup_graph(1) self.partie = jouer_coup(idf, typef, str(pos))
def jouer_auto_console(self, idf): """fonction""" typef, pos = self.jouer_coup_graph(1) self.partie = jouer_coup(idf, typef, str(pos)) print(afficher_damier_ascii(self.partie))