1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
|
import sys
import random
import math
marques = [" ", "X", "O"]
class MorpionCellError(Exception):
pass
class Morpion:
def __init__(self, joueurs):
self.joueurs = joueurs
def initialiser(self, historique=None):
self.etat = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
self.taille = len(self.etat)
self.tour = 0
if historique is None:
self.historique = []
else:
self.historique = historique
def afficher(self):
for i in range(self.taille):
if i != 0:
print("-" * (self.taille * 2 - 1))
for j in range(self.taille):
if j != 0:
print("|", end="")
# print(str(self.etat[i][j]), end="")
print(marques[self.etat[i][j]], end="")
print()
print("")
def afficher_fin(self):
self.afficher()
print("=" * 5)
gagnant = self.tester_victoire()
if gagnant == 0:
print("Match nul")
else:
print(f"Victoire joueur {gagnant} ({marques[gagnant]})")
print("=" * 5)
def jouer(self):
while True:
self.afficher()
a_joué = self.joueur.jouer(self)
if a_joué:
self.tour = self.tour + 1
if self.est_terminé():
break
def placer(self, coup):
i, j = coup
if self.etat[i][j] == 0:
self.etat[i][j] = self.joueur_id + 1
self.historique.append((i, j))
else:
raise MorpionCellError(
f"Case ({i}, {j}) déjà occupée par {self.etat[i][j]}"
)
def annuler(self, n=1):
for i in range(min(n, len(self.historique))):
del self.historique[-1]
self.initialiser(self.historique)
for coup in self.historique:
self.placer(coup)
@property
def joueur_id(self):
"""Retourne le joueur_id
0: Joueur 1
1: Joueur 2"""
return self.tour % 2
@property
def joueur(self):
"""Retourne l'objet joueur du tour actuel"""
return self.joueurs[self.joueur_id]
def a_une_case_vide(self):
"""Retourne vrai s'il reste au moins une case vide"""
for row in self.etat:
for val in row:
if val == 0:
return True
return False
def est_terminé(self):
"""Retourne vrai lorsque le jeu est terminé
Soit plus de case vide soit il y a un gagnant"""
gagnant = self.tester_victoire()
return not self.a_une_case_vide() or gagnant == 1 or gagnant == 2
def tester_victoire(self):
"""Retourne le numéro du gagnant
1 : victoire joueur 1
2 : victoire joueur 2
0 : pas de victoire
"""
# Horizontal
for i in range(self.taille):
if self.etat[i][0] == self.etat[i][1] == self.etat[i][2]:
return self.etat[i][0]
# Vertical
for j in range(self.taille):
if self.etat[0][j] == self.etat[1][j] == self.etat[2][j]:
return self.etat[0][j]
# Diag /
if self.etat[0][0] == self.etat[1][1] == self.etat[2][2]:
return self.etat[0][0]
# Diag \
if self.etat[2][0] == self.etat[1][1] == self.etat[0][2]:
return self.etat[2][0]
def coups_possibles(self):
"""Retourne les coups possibles (cases vides)"""
coups = []
for i in range(self.taille):
for j in range(self.taille):
if self.etat[i][j] == 0:
coups.append((i, j))
return coups
class Joueur:
"""Classe abstraite Joueur (ne pas instancier)"""
def __init__(self, id):
self.id = id
def jouer(self, jeu):
pass
class JoueurHumain(Joueur):
"""Joueur humain pour intéraction avec la console"""
def __init__(self, id):
super().__init__(id)
def jouer(self, jeu):
while True:
try:
print(
f"Tour {jeu.tour + 1} : joueur {self.id} ({marques[self.id]}) humain"
)
# print(f"coups possibles: {coups_possibles(jeu)}")
while True:
try:
i = int(input("ligne: "))
break
except ValueError:
return self.jouer(jeu)
if i >= 0:
while True:
try:
j = int(input("colonne: "))
break
except ValueError:
return self.jouer()
i = i - 1
j = j - 1
coup = i, j
jeu.placer(coup)
return True
else:
jeu.annuler(-i)
jeu.afficher()
return False
except MorpionCellError:
print("Case occupée")
class JoueurIABasique(Joueur):
"""Joueur IA basique qui
joue toujours du haut-gauche vers bas-droit"""
def __init__(self, id):
super().__init__(id)
def jouer(self, jeu):
print(f"Tour {jeu.tour + 1} : joueur {self.id} ({marques[self.id]}) IA basique")
coups = jeu.coups_possibles()
coup = coups[0]
i, j = coup
jeu.placer(coup)
print(f"ligne: {i+1}")
print(f"colonne: {j+1}")
# input("attente")
print("")
return True
class JoueurIARandom(Joueur):
"""Joueur IA basique qui joue au hazard"""
def __init__(self, id):
super().__init__(id)
def jouer(self, jeu):
print(f"Tour {jeu.tour + 1} : joueur {self.id} ({marques[self.id]}) IA random")
coups = jeu.coups_possibles()
coup = random.choice(coups)
i, j = coup
jeu.placer(coup)
print(f"ligne: {i+1}")
print(f"colonne: {j+1}")
# input("attente")
print("")
return True
class JoueurIAMiniMax(Joueur):
"""Joueur IA avec l'algo minimax"""
def __init__(self, id):
super().__init__(id)
def jouer(self, jeu):
print(f"Tour {jeu.tour + 1} : joueur {self.id} ({marques[self.id]}) IA MiniMax")
meilleurScore = -math.inf
meilleurCoup = None
for coup in jeu.coups_possibles():
print(jeu.etat, coup)
print("placer")
jeu.placer(coup)
print("minimax")
score = self.minimax(False, self.id, jeu)
print("annuler")
jeu.annuler()
if score > meilleurScore:
meilleurScore = score
meilleurCoup = coup
jeu.placer(meilleurCoup)
i, j = meilleurCoup
print(f"ligne: {i+1}")
print(f"colonne: {j+1}")
# input("attente")
print("")
return True
def minimax(self, estTourDeMax, idMax, jeu):
print(f"minimax2 {estTourDeMax} {idMax} {jeu.etat}")
if jeu.est_terminé():
gagnant = jeu.tester_victoire()
if gagnant == 0:
print("nul")
return 0
else:
print(f"gagnant {idMax}")
return 1 if gagnant == idMax else -1
scores = []
print(jeu.historique)
for coup in jeu.coups_possibles():
print(f"placer {coup}")
jeu.placer(coup)
score = self.minimax(not estTourDeMax, idMax, jeu)
print(f"score: {score}")
scores.append(score)
print("annuler")
jeu.annuler()
return max(scores) if estTourDeMax else min(scores)
if __name__ == "__main__":
types_partie = [
"P1 (H) vs P2 (H)",
"P1 (H) vs P2 (IA basique)",
"P1 (H) vs P2 (IA random)",
"P1 (H) vs P2 (IA minimax)",
]
for i, partie in enumerate(types_partie, 1):
print(f"{i} {partie}")
choix_partie = int(input("Choix 1-4: "))
if choix_partie == 1:
joueurs = [JoueurHumain(1), JoueurHumain(2)]
elif choix_partie == 2:
joueurs = [JoueurHumain(1), JoueurIABasique(2)]
elif choix_partie == 3:
joueurs = [JoueurHumain(1), JoueurIARandom(2)]
elif choix_partie == 4:
joueurs = [JoueurHumain(1), JoueurIAMiniMax(2)]
else:
sys.exit()
print("")
print(types_partie[choix_partie - 1])
print("")
morpion = Morpion(joueurs)
morpion.initialiser()
morpion.jouer()
morpion.afficher_fin() |
Partager