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

import itertools
import json
EMPTY = ' '*9
def get_pos(x,y,board):
i=3*y+x
return board[i]
def set_pos(x,y,marker,board):
i=3*y+x
return board[:i]+marker+board[i+1:]
def print_board(board):
l = ('|'.join(board[i:i+3]) for i in range(0,9,3))
print('\n-----\n'.join(l))
def check_win(board):
rows = ['']*3
cols = ['']*3
diags = ['']*2
for y in range(3):
for x in range(3):
cur = get_pos(x,y,board)
rows[y] += cur
cols[x] += cur
if x == y:
diags[0] += cur
if x == (2-y):
diags[1] += cur
for thing in rows+cols+diags:
if thing == 'ooo':
return 'o'
if thing == 'xxx':
return 'x'
INIT_MOVES = set(itertools.product( *(range(3),)*2 ))
def recurse(board=EMPTY,moveset=INIT_MOVES,x=True):
#print_board(board)
#print('-'*3)
ret = {}# {'parent':parent}
for move in moveset:
if x:
cur_board = set_pos(*move,'x',board)
else:
cur_board = set_pos(*move,'o',board)
if len(moveset) > 1:
cur_moves = moveset.copy()
cur_moves.remove(move)
ret[cur_board] = recurse(cur_board,cur_moves,not x)
else:
ret[cur_board] = None
return ret
def save():
moves = recurse()
with open('tree.json','w') as file:
json.dump(moves,file,indent=4)
return moves
def count_wins(moves):
x_total = 0
o_total = 0
for board,sub_board in moves.items():
if len(board) == 9:
if sub_board is not None:
sub_x_total,sub_o_total = count_wins(sub_board)
x_total += sub_x_total
o_total += sub_o_total
else:
win = check_win(board)
if win is not None:
if win == 'x':
x_total += 1
else:
o_total += 1
moves['x'] = x_total
moves['o'] = o_total
return x_total,o_total
def load():
with open('tree.json') as file:
return json.load(file)