You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.1 KiB

7 years ago
  1. import itertools
  2. import json
  3. EMPTY = ' '*9
  4. def get_pos(x,y,board):
  5. i=3*y+x
  6. return board[i]
  7. def set_pos(x,y,marker,board):
  8. i=3*y+x
  9. return board[:i]+marker+board[i+1:]
  10. def print_board(board):
  11. l = ('|'.join(board[i:i+3]) for i in range(0,9,3))
  12. print('\n-----\n'.join(l))
  13. def check_win(board):
  14. rows = ['']*3
  15. cols = ['']*3
  16. diags = ['']*2
  17. for y in range(3):
  18. for x in range(3):
  19. cur = get_pos(x,y,board)
  20. rows[y] += cur
  21. cols[x] += cur
  22. if x == y:
  23. diags[0] += cur
  24. if x == (2-y):
  25. diags[1] += cur
  26. for thing in rows+cols+diags:
  27. if thing == 'ooo':
  28. return 'o'
  29. if thing == 'xxx':
  30. return 'x'
  31. INIT_MOVES = set(itertools.product( *(range(3),)*2 ))
  32. def recurse(board=EMPTY,moveset=INIT_MOVES,x=True):
  33. #print_board(board)
  34. #print('-'*3)
  35. ret = {}# {'parent':parent}
  36. for move in moveset:
  37. if x:
  38. cur_board = set_pos(*move,'x',board)
  39. else:
  40. cur_board = set_pos(*move,'o',board)
  41. if len(moveset) > 1:
  42. cur_moves = moveset.copy()
  43. cur_moves.remove(move)
  44. ret[cur_board] = recurse(cur_board,cur_moves,not x)
  45. else:
  46. ret[cur_board] = None
  47. return ret
  48. def save():
  49. moves = recurse()
  50. with open('tree.json','w') as file:
  51. json.dump(moves,file,indent=4)
  52. return moves
  53. def count_wins(moves):
  54. x_total = 0
  55. o_total = 0
  56. for board,sub_board in moves.items():
  57. if len(board) == 9:
  58. if sub_board is not None:
  59. sub_x_total,sub_o_total = count_wins(sub_board)
  60. x_total += sub_x_total
  61. o_total += sub_o_total
  62. else:
  63. win = check_win(board)
  64. if win is not None:
  65. if win == 'x':
  66. x_total += 1
  67. else:
  68. o_total += 1
  69. moves['x'] = x_total
  70. moves['o'] = o_total
  71. return x_total,o_total
  72. def load():
  73. with open('tree.json') as file:
  74. return json.load(file)