furas

Python - Tic Tac Toe (FB: LearnPython.org)

Oct 21st, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. #
  2. # http://pastebin.com/fNnk1Yen
  3. #
  4.  
  5. import random
  6.  
  7. # ----- functions -----
  8.  
  9. def draw_map(moves):
  10.    
  11.     print "+-------+-------+-------+"
  12.     print "|1      |2      |3      |"
  13.     print "|   {}   |   {}   |   {}   |".format(*moves[0:3])
  14.     print "|       |       |       |"
  15.     print "+-------+-------+-------+"
  16.     print "|4      |5      |6      |"
  17.     print "|   {}   |   {}   |   {}   |".format(*moves[3:6])
  18.     print "|       |       |       |"
  19.     print "+-------+-------+-------+"
  20.     print "|7      |8      |9      |"
  21.     print "|   {}   |   {}   |   {}   |".format(*moves[6:9])
  22.     print "|       |       |       |"
  23.     print "+-------+-------+-------+"
  24.  
  25. # ----- constants ----- (UPPER_CASE)
  26.  
  27. # winner moves
  28.  
  29. WINNER_MOVES = [
  30.     {1,2,3},
  31.     {4,5,6},
  32.     {7,8,9},
  33.     {1,5,9},
  34.     {2,5,8},
  35.     {3,6,9},
  36.     {1,4,7},
  37.     {3,5,7},
  38. ]
  39.  
  40. # ----- main -----
  41.  
  42. moves = [" "] * 10
  43.  
  44. slots = range(1, 10)
  45.  
  46. player_record = []
  47. AI_record = []
  48.  
  49. running = True
  50.  
  51. while True: # or: while running:
  52.  
  53.     # --- player ---
  54.    
  55.     # repeat till correct move        
  56.     while True:
  57.         draw_map(moves)
  58.  
  59.         try:
  60.            player_move = int(raw_input("MOVE :"))
  61.         except ValueError:
  62.             continue
  63.        
  64.         if player_move in slots:
  65.             break
  66.  
  67.     slots.remove(player_move)
  68.        
  69.     moves[player_move-1] = "X"
  70.     player_record.append(player_move)
  71.  
  72.     for check in WINNER_MOVES:
  73.         if set(player_record).intersection(check) == check:
  74.             draw_map(moves)
  75.             running = False
  76.             print "YOU WIN !"
  77.             break
  78.            
  79.     # ----
  80.    
  81.     if not running: # skip AI
  82.         break
  83.    
  84.     # --- AI ---
  85.    
  86.     AI_move = random.choice(slots)
  87.     slots.remove(AI_move)
  88.        
  89.     moves[AI_move-1] = "O"
  90.     AI_record.append(AI_move)
  91.  
  92.     for check in WINNER_MOVES:
  93.         if set(AI_record).intersection(check) == check:
  94.             draw_map(moves)
  95.             running = False
  96.             print "AI WIN !"
  97.             break
  98.  
  99.     # ----
  100.    
  101.     if not running: # skip Player
  102.         break
  103.    
  104. # ---- the end ---
  105.  
  106. raw_input("Press any key to exit!")
Add Comment
Please, Sign In to add comment