arbre_alpha_beta.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. from random import randint
  2. from random import shuffle
  3. from Outils.Elagage import *
  4. from Outils.Moteur_de_jeu import Distance
  5. from Outils.Moteur_de_jeu.Distance import *
  6. def obtenir_coup (num, plateau, fct_eval, H) :
  7. liste_coups = plateau.liste_coups_possibles()
  8. t = []
  9. for coup in liste_coups :
  10. if elagage(plateau, coup) :
  11. t.append ([coup, None ])
  12. alpha = -10**100
  13. beta = 10**100
  14. dist = distance_a_star(plateau)
  15. for k in range (len(t)) :
  16. plateau2 = plateau.copie()
  17. plateau2.executer_coup (t[k][0])
  18. t[k][1] = alphabeta (plateau2, num, alpha, beta, fct_eval, 1, H)
  19. alpha = max (alpha, t[k][1])
  20. maxi = t[0][1]
  21. l = []
  22. for i in range(len(t)) :
  23. l.append(t[i][1])
  24. if t[i][1] >= maxi :
  25. maxi = t[i][1]
  26. liste_coups = []
  27. a = []
  28. for i in range(len(t)) :
  29. if t[i][1] == maxi :
  30. liste_coups.append(t[i][0])
  31. shuffle(liste_coups)
  32. coup = liste_coups[0]
  33. liste = plateau.liste_coups_possibles()
  34. for i in range(len(liste)) :
  35. if liste[i] == coup :
  36. return i
  37. def alphabeta (plateau, num, alpha, beta, fct_eval, h, H) :
  38. if plateau.gagnant() !=-1 :
  39. return fct_eval (plateau, num )
  40. if h == H :
  41. return fct_eval (plateau, num )
  42. else :
  43. if h%2 == 1 :
  44. Val = 10**100
  45. liste_coups = plateau.liste_coups_possibles()
  46. t = []
  47. for coup in liste_coups :
  48. if elagage(plateau, coup) :
  49. t.append (coup)
  50. for k in range (len(t)) :
  51. plateau2 = plateau.copie()
  52. plateau2.executer_coup (t[k])
  53. Val = min (Val, alphabeta (plateau2, num, alpha, beta, fct_eval, h+1, H))
  54. if alpha > Val :
  55. return Val
  56. beta = min (beta, Val)
  57. else :
  58. Val = -10**100
  59. liste_coups = plateau.liste_coups_possibles()
  60. t = []
  61. for coup in liste_coups :
  62. if elagage(plateau, coup) :
  63. t.append (coup)
  64. for k in range (len(t)) :
  65. plateau2 = plateau.copie()
  66. plateau2.executer_coup (t[k])
  67. Val = max (Val, alphabeta (plateau2, num, alpha, beta, fct_eval, h+1, H))
  68. if beta <= Val :
  69. return Val
  70. alpha = max (alpha, Val)
  71. return Val